diff --git a/testbed/matplotlib__matplotlib/.appveyor.yml b/testbed/matplotlib__matplotlib/.appveyor.yml new file mode 100644 index 0000000000000000000000000000000000000000..b48726bb3e51d21d869bc91fb8ff145c54923d37 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.appveyor.yml @@ -0,0 +1,107 @@ +# With infos from +# http://tjelvarolsson.com/blog/how-to-continuously-test-your-python-code-on-windows-using-appveyor/ +# https://packaging.python.org/en/latest/appveyor/ +# https://github.com/rmcgibbo/python-appveyor-conda-example + +# Backslashes in quotes need to be escaped: \ -> "\\" +branches: + except: + - /auto-backport-.*/ + - /^v\d+\.\d+\.[\dx]+-doc$/ + +skip_commits: + message: /\[ci doc\]/ + files: + - doc/ + - galleries/ + +clone_depth: 50 + +image: Visual Studio 2017 + +environment: + + global: + PYTHONFAULTHANDLER: 1 + PYTHONIOENCODING: UTF-8 + PYTEST_ARGS: -raR --numprocesses=auto --timeout=300 --durations=25 + --cov-report= --cov=lib --log-level=DEBUG + + matrix: + - PYTHON_VERSION: "3.9" + CONDA_INSTALL_LOCN: "C:\\Miniconda3-x64" + TEST_ALL: "no" + - PYTHON_VERSION: "3.10" + CONDA_INSTALL_LOCN: "C:\\Miniconda3-x64" + TEST_ALL: "no" + +# We always use a 64-bit machine, but can build x86 distributions +# with the PYTHON_ARCH variable +platform: + - x64 + +# all our python builds have to happen in tests_script... +build: false + +cache: + - '%LOCALAPPDATA%\pip\Cache' + - '%USERPROFILE%\.cache\matplotlib' + +init: + - echo %PYTHON_VERSION% %CONDA_INSTALL_LOCN% + +install: + - set PATH=%CONDA_INSTALL_LOCN%;%CONDA_INSTALL_LOCN%\scripts;%PATH%; + - conda config --set always_yes true + - conda config --set show_channel_urls yes + - conda config --prepend channels conda-forge + + # For building, use a new environment + # Add python version to environment + # `^ ` escapes spaces for indentation + - echo ^ ^ - python=%PYTHON_VERSION% >> environment.yml + - conda env create -f environment.yml + - activate mpl-dev + - conda install -c conda-forge pywin32 + - echo %PYTHON_VERSION% %TARGET_ARCH% + # Show the installed packages + versions + - conda list + +test_script: + # Now build the thing.. + - set LINK=/LIBPATH:%cd%\lib + - pip install -ve . + # this should show no freetype dll... + - set "DUMPBIN=%VS140COMNTOOLS%\..\..\VC\bin\dumpbin.exe" + - '"%DUMPBIN%" /DEPENDENTS lib\matplotlib\ft2font*.pyd | findstr freetype.*.dll && exit /b 1 || exit /b 0' + + # this are optional dependencies so that we don't skip so many tests... + - if x%TEST_ALL% == xyes conda install -q ffmpeg inkscape miktex + # missing packages on conda-forge for imagemagick + # This install sometimes failed randomly :-( + #- choco install imagemagick + + # Test import of tkagg backend + - python -c "import matplotlib as m; m.use('tkagg'); import matplotlib.pyplot as plt; print(plt.get_backend())" + # tests + - echo The following args are passed to pytest %PYTEST_ARGS% + - pytest %PYTEST_ARGS% + +artifacts: + - path: result_images\* + name: result_images + type: zip + +on_finish: + - conda install codecov + - codecov -e PYTHON_VERSION PLATFORM + +on_failure: + # Generate a html for visual tests + - python tools/visualize_tests.py --no-browser + - echo zipping images after a failure... + - 7z a result_images.zip result_images\ | grep -v "Compressing" + - appveyor PushArtifact result_images.zip + +matrix: + fast_finish: true diff --git a/testbed/matplotlib__matplotlib/.coveragerc b/testbed/matplotlib__matplotlib/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..f8d90f93e600d42f6f3143bcfe313da283a071e1 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.coveragerc @@ -0,0 +1,16 @@ +[run] +branch = true +source = + matplotlib + mpl_toolkits +omit = matplotlib/_version.py + +[report] +exclude_lines = + pragma: no cover + raise NotImplemented + def __str__ + def __repr__ + if __name__ == .__main__.: + if TYPE_CHECKING: + if typing.TYPE_CHECKING: diff --git a/testbed/matplotlib__matplotlib/.devcontainer/devcontainer.json b/testbed/matplotlib__matplotlib/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..814c066c43b183e9a72c4efc9943aa22a92c3c68 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.devcontainer/devcontainer.json @@ -0,0 +1,38 @@ +{ + "hostRequirements": { + "memory": "8gb", + "cpus": 4 + }, + "image": "mcr.microsoft.com/devcontainers/universal:2", + "features": { + "ghcr.io/devcontainers/features/desktop-lite:1": {}, + "ghcr.io/rocker-org/devcontainer-features/apt-packages:1": { + "packages": "inkscape,ffmpeg,dvipng,lmodern,cm-super,texlive-latex-base,texlive-latex-extra,texlive-fonts-recommended,texlive-latex-recommended,texlive-pictures,texlive-xetex,fonts-wqy-zenhei,graphviz,fonts-crosextra-carlito,fonts-freefont-otf,fonts-humor-sans,fonts-noto-cjk,optipng" + } + }, + "onCreateCommand": ".devcontainer/setup.sh", + "postCreateCommand": "", + "forwardPorts": [6080], + "portsAttributes": { + "6080": { + "label": "desktop" + } + }, + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "yy0931.mplstyle", + "eamodio.gitlens", + "ms-vscode.live-server" + ], + "settings": {} + }, + "codespaces": { + "openFiles": [ + "README.md", + "doc/devel/codespaces.md" + ] + } + } +} diff --git a/testbed/matplotlib__matplotlib/.devcontainer/setup.sh b/testbed/matplotlib__matplotlib/.devcontainer/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..88da5baf69e27258dbbd0ee3aaa501bac4b531f7 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.devcontainer/setup.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +set -e + +"${SHELL}" <(curl -Ls micro.mamba.pm/install.sh) < /dev/null + +conda init --all +micromamba shell init -s bash +micromamba env create -f environment.yml --yes +# Note that `micromamba activate mpl-dev` doesn't work, it must be run by the +# user (same applies to `conda activate`) +echo "envs_dirs: + - /home/codespace/micromamba/envs" > /opt/conda/.condarc diff --git a/testbed/matplotlib__matplotlib/.flake8 b/testbed/matplotlib__matplotlib/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..ee739cdf42319b2e1ed9b1127a2e1ceeabc4af8f --- /dev/null +++ b/testbed/matplotlib__matplotlib/.flake8 @@ -0,0 +1,97 @@ +[flake8] +max-line-length = 88 +select = + # flake8 default + D, E, F, W, +ignore = + # flake8 default + E121,E123,E126,E226,E24,E704,W503,W504, + # Additional ignores: + E127, E131, + E266, + E305, E306, + E741, + F841, + # pydocstyle + D100, D101, D102, D103, D104, D105, D106, + D200, D202, D204, D205, + D301, + D400, D401, D403, D404 + # ignored by pydocstyle numpy docstring convention + D107, D203, D212, D213, D402, D413, D415, D416, D417, + +exclude = + .git + build + doc/gallery + doc/tutorials + # External files. + tools/gh_api.py + .tox + .eggs + +per-file-ignores = + setup.py: E402 + + lib/matplotlib/__init__.py: E402, F401 + lib/matplotlib/_animation_data.py: E501 + lib/matplotlib/_api/__init__.py: F401 + lib/matplotlib/_cm.py: E122, E202, E203, E302 + lib/matplotlib/_mathtext.py: E221, E251 + lib/matplotlib/_mathtext_data.py: E122, E203, E261 + lib/matplotlib/axes/__init__.py: F401, F403 + lib/matplotlib/backends/backend_template.py: F401 + lib/matplotlib/font_manager.py: E501 + lib/matplotlib/image.py: F401, F403 + lib/matplotlib/mathtext.py: E221 + lib/matplotlib/pylab.py: F401, F403 + lib/matplotlib/pyplot.py: F401, F811 + lib/matplotlib/tests/test_mathtext.py: E501 + lib/matplotlib/transforms.py: E201, E202, E203 + lib/matplotlib/tri/_triinterpolate.py: E201, E221 + lib/mpl_toolkits/axes_grid1/axes_size.py: E272 + lib/mpl_toolkits/axisartist/__init__.py: F401 + lib/mpl_toolkits/axisartist/angle_helper.py: E221 + lib/pylab.py: F401, F403 + + doc/conf.py: E402 + galleries/users_explain/artists/paths.py: E402 + galleries/users_explain/artists/patheffects_guide.py: E402 + galleries/users_explain/artists/transforms_tutorial.py: E402, E501 + galleries/users_explain/colors/colormaps.py: E501 + galleries/users_explain/colors/colors.py: E402 + galleries/tutorials/artists.py: E402 + galleries/users_explain/axes/constrainedlayout_guide.py: E402 + galleries/users_explain/axes/legend_guide.py: E402 + galleries/users_explain/axes/tight_layout_guide.py: E402 + galleries/users_explain/animations/animations.py: E501 + galleries/tutorials/images.py: E501 + galleries/tutorials/pyplot.py: E402, E501 + galleries/users_explain/text/annotations.py: E402, E501 + galleries/users_explain/text/mathtext.py: E501 + galleries/users_explain/text/text_intro.py: E402 + galleries/users_explain/text/text_props.py: E501 + + galleries/examples/animation/frame_grabbing_sgskip.py: E402 + galleries/examples/images_contours_and_fields/tricontour_demo.py: E201 + galleries/examples/images_contours_and_fields/tripcolor_demo.py: E201 + galleries/examples/images_contours_and_fields/triplot_demo.py: E201 + galleries/examples/lines_bars_and_markers/marker_reference.py: E402 + galleries/examples/misc/print_stdout_sgskip.py: E402 + galleries/examples/misc/table_demo.py: E201 + galleries/examples/style_sheets/bmh.py: E501 + galleries/examples/subplots_axes_and_figures/demo_constrained_layout.py: E402 + galleries/examples/text_labels_and_annotations/custom_legends.py: E402 + galleries/examples/ticks/date_concise_formatter.py: E402 + galleries/examples/ticks/date_formatters_locators.py: F401 + galleries/examples/user_interfaces/embedding_in_gtk3_panzoom_sgskip.py: E402 + galleries/examples/user_interfaces/embedding_in_gtk3_sgskip.py: E402 + galleries/examples/user_interfaces/embedding_in_gtk4_panzoom_sgskip.py: E402 + galleries/examples/user_interfaces/embedding_in_gtk4_sgskip.py: E402 + galleries/examples/user_interfaces/gtk3_spreadsheet_sgskip.py: E402 + galleries/examples/user_interfaces/gtk4_spreadsheet_sgskip.py: E402 + galleries/examples/user_interfaces/mpl_with_glade3_sgskip.py: E402 + galleries/examples/user_interfaces/pylab_with_gtk3_sgskip.py: E402 + galleries/examples/user_interfaces/pylab_with_gtk4_sgskip.py: E402 + galleries/examples/userdemo/pgf_preamble_sgskip.py: E402 +force-check = True diff --git a/testbed/matplotlib__matplotlib/.git-blame-ignore-revs b/testbed/matplotlib__matplotlib/.git-blame-ignore-revs new file mode 100644 index 0000000000000000000000000000000000000000..613852425632b9cea7a24d2a2c02ae9bd3feaba6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.git-blame-ignore-revs @@ -0,0 +1,14 @@ +# style: end-of-file-fixer pre-commit hook +c1a33a481b9c2df605bcb9bef9c19fe65c3dac21 + +# style: trailing-whitespace pre-commit hook +213061c0804530d04bbbd5c259f10dc8504e5b2b + +# style: check-docstring-first pre-commit hook +046533797725293dfc2a6edb9f536b25f08aa636 + +# chore: fix spelling errors +686c9e5a413e31c46bb049407d5eca285bcab76d + +# chore: pyupgrade --py39-plus +4d306402bb66d6d4c694d8e3e14b91054417070e diff --git a/testbed/matplotlib__matplotlib/.git_archival.txt b/testbed/matplotlib__matplotlib/.git_archival.txt new file mode 100644 index 0000000000000000000000000000000000000000..3994ec0a83ea6af834f1e4cbd644435eb2168888 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.git_archival.txt @@ -0,0 +1,4 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true)$ +ref-names: $Format:%D$ diff --git a/testbed/matplotlib__matplotlib/.gitattributes b/testbed/matplotlib__matplotlib/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0c2c8627af739ecd1c4e153582803c0a0e3573d --- /dev/null +++ b/testbed/matplotlib__matplotlib/.gitattributes @@ -0,0 +1,6 @@ +* text=auto +*.m diff=objc +*.ppm binary +*.svg binary +*.svg linguist-language=true +.git_archival.txt export-subst diff --git a/testbed/matplotlib__matplotlib/.gitignore b/testbed/matplotlib__matplotlib/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..74080f6c50aed5600827b8b8fc95de8af26eef1f --- /dev/null +++ b/testbed/matplotlib__matplotlib/.gitignore @@ -0,0 +1,112 @@ +######################################### +# OS-specific temporary and backup files +.DS_Store + +######################################### +# Editor temporary/working/backup files # +.#* +[#]*# +*~ +*$ +*.bak +*.kdev4 +.project +.pydevproject +*.swp +.idea +.vscode/ + +# Compiled source # +################### +*.a +*.com +*.class +*.dll +*.exe +*.o +*.py[ocd] +*.so + +# Python files # +################ +# setup.py working directory +build + +# setup.py dist directory +dist +# Egg metadata +*.egg-info +.eggs +# wheel metadata +pip-wheel-metadata/* +# tox testing tool +.tox +mplsetup.cfg +# generated by setuptools_scm +lib/matplotlib/_version.py + +# OS generated files # +###################### +.directory +.gdb_history +.DS_Store? +ehthumbs.db +Icon? +Thumbs.db + +# Things specific to this project # +################################### +galleries/tutorials/intermediate/CL01.png +galleries/tutorials/intermediate/CL02.png + +# Documentation generated files # +################################# +# sphinx build directory +doc/_build +doc/api/_as_gen +# autogenerated by sphinx-gallery +doc/examples +doc/gallery +doc/modules +doc/plot_types +doc/pyplots/tex_demo.png +doc/tutorials +doc/users/explain +lib/dateutil +galleries/examples/*/*.bmp +galleries/examples/*/*.eps +galleries/examples/*/*.pdf +galleries/examples/*/*.png +galleries/examples/*/*.svg +galleries/examples/*/*.svgz +result_images +doc/_static/constrained_layout*.png +doc/.mpl_skip_subdirs.yaml + +# Nose/Pytest generated files # +############################### +.pytest_cache/ +.cache/ +.coverage +.coverage.* +*.py,cover +cover/ +.noseids + +# Conda files # +############### +__conda_version__.txt +lib/png.lib +lib/z.lib + +# Jupyter files # +################# + +.ipynb_checkpoints/ + +# Vendored dependencies # +######################### +lib/matplotlib/backends/web_backend/node_modules/ +lib/matplotlib/backends/web_backend/package-lock.json + +LICENSE/LICENSE_QHULL diff --git a/testbed/matplotlib__matplotlib/.mailmap b/testbed/matplotlib__matplotlib/.mailmap new file mode 100644 index 0000000000000000000000000000000000000000..44005da6e2d8e340ad0c5909bf1f5ee13deb8aa0 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.mailmap @@ -0,0 +1,284 @@ +Adam Ortiz + +Adrien F. Vincent +Adrien F. Vincent + +Aleksey Bilogur + +Alexander Rudy + +Alon Hershenhorn + +Alvaro Sanchez + +Andrew Dawson + +anykraus + +Ariel Hernán Curiale + +Ben Cohen + +Ben Root Benjamin Root + +Benedikt Daurer + +Benjamin Congdon +Benjamin Congdon bcongdon + +Bruno Zohreh + +Carsten Schelp + +Casper van der Wel + +Chris Holdgraf + +Cho Yin Yong + +Chris + +Christoph Gohlke cgohlke +Christoph Gohlke C. Gohlke +Christoph Gohlke + +Cimarron Mittelsteadt Cimarron + +cldssty + +Conner R. Phillips + +Dan Hickstein + +Daniel Hyams +Daniel Hyams Daniel Hyams + +David Kua + +Devashish Deshpande + +Dietmar Schwertberger + +Dora Fraeman Caswell + +endolith + +Eric Dill + +Erik Bray + +Eric Ma +Eric Ma + +esvhd + +Filipe Fernandes + +Florian Le Bourdais + +Francesco Montesano montefra + +Gauravjeet + +Hajoon Choi + +hannah + +Hans Moritz Günther + +Harshal Prakash Patankar + +Harshit Patni + +ImportanceOfBeingErnest + +J. Goutin JGoutin + +Jack Kelly +Jack Kelly + +Jaime Fernandez + +Jake Vanderplas +Jake Vanderplas +Jake Vanderplas + +James R. Evans + +Jeff Lutgen + +Jeffrey Bingham + +Jens Hedegaard Nielsen +Jens Hedegaard Nielsen + +Joel Frederico <458871+joelfrederico@users.noreply.github.com> + +John Hunter + +Jorrit Wronski + +Joseph Fox-Rabinovitz Mad Physicist +Joseph Fox-Rabinovitz Joseph Fox-Rabinovitz + +Jouni K. Seppänen + +Julien Lhermitte + +Julien Schueller +Julien Schueller + +Kevin Davies + +kikocorreoso + +Klara Gerlei +Klara Gerlei klaragerlei + +Kristen M. Thyng + +Kyle Sunden + +Leeonadoh + +Lennart Fricke + +Levi Kilcher + +Leon Yin + +Lion Krischer + +Manan Kevadiya +Manan Kevadiya <43081866+manan2501@users.noreply.github.com> + +Manuel Nuno Melo + +Marco Gorelli +Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com> + +Marek Rudnicki + +Martin Fitzpatrick + +Matt Newville + +Matthew Emmett +Matthew Emmett + +Matthias Bussonnier +Matthias Bussonnier + +Matthias Lüthi +Matthias Lüthi + +Matti Picus + +Michael Droettboom +Michael Droettboom Michael Droettboom + +Michiel de Hoon +Michiel de Hoon Michiel de Hoon +Michiel de Hoon Michiel de Hoon +Michiel de Hoon Michiel de Hoon +Michiel de Hoon Michiel de Hoon + +MinRK +MinRK Min RK + +Nelle Varoquaux + +Nic Eggert Nic Eggert +Nic Eggert Nic Eggert + +Nicolas P. Rougier + +OceanWolf + +Olivier Castany <1868182+ocastany@users.noreply.github.com> +Olivier Castany <1868182+ocastany@users.noreply.github.com> +Olivier Castany <1868182+ocastany@users.noreply.github.com> + +Om Sitapara + +Patrick Chen + +Paul Ganssle +Paul Ganssle + +Paul Hobson +Paul Hobson vagrant + +Paul Ivanov +Paul Ivanov +Paul Ivanov + +Per Parker + +Peter Würtz +Peter Würtz + +Phil Elson +Phil Elson +Phil Elson + +productivememberofsociety666 none + +Rishikesh + +RyanPan + +Samesh Lakhotia +Samesh Lakhotia <43701530+sameshl@users.noreply.github.com> ' + +Scott Lasley + +Sebastian Raschka +Sebastian Raschka + +Sidharth Bansal +Sidharth Bansal <20972099+SidharthBansal@users.noreply.github.com> + +Simon Cross + +Slav Basharov + +sohero sohero + +Stefan van der Walt + +switham switham + +Taehoon Lee + +Ted Drain + +Taras Kuzyo + +Terence Honles + +Thomas A Caswell Thomas A Caswell +Thomas A Caswell Thomas A Caswell +Thomas A Caswell Thomas A Caswell <“tcaswell@gmail.com”> +Thomas A Caswell Thomas A Caswell + +Till Stensitzki + +Trish Gillett-Kawamoto + +Tuan Dung Tran + +Víctor Zabalza + +Vidur Satija + +WANG Aiyong + +Zhili (Jerry) Pan + +Werner F Bruhin + +Yunfei Yang Yunfei Yang +Yunfei Yang Yunfei Yang + +Zac Hatfield-Dodds diff --git a/testbed/matplotlib__matplotlib/.matplotlib-repo b/testbed/matplotlib__matplotlib/.matplotlib-repo new file mode 100644 index 0000000000000000000000000000000000000000..0b1d699bcdb18e501986e2cfc3edfd3886b37039 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.matplotlib-repo @@ -0,0 +1,3 @@ +The existence of this file signals that the code is a matplotlib source repo +and not an installed version. We use this in __init__.py for gating version +detection. diff --git a/testbed/matplotlib__matplotlib/.meeseeksdev.yml b/testbed/matplotlib__matplotlib/.meeseeksdev.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bfd1b8e4257d5b614fc41566b6465d9b6febe57 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.meeseeksdev.yml @@ -0,0 +1,4 @@ +users: + Carreau: + can: + - backport diff --git a/testbed/matplotlib__matplotlib/.pre-commit-config.yaml b/testbed/matplotlib__matplotlib/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..198624ec99112665820ff6b04ed86bf65a636c68 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.pre-commit-config.yaml @@ -0,0 +1,53 @@ +ci: + autofix_prs: false + autoupdate_schedule: 'quarterly' +exclude: | + (?x)^( + extern| + LICENSE| + lib/matplotlib/mpl-data| + doc/devel/gitwash| + doc/users/prev| + doc/api/prev| + lib/matplotlib/tests/tinypages + ) +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-docstring-first + exclude: lib/matplotlib/typing.py # docstring used for attribute flagged by check + - id: end-of-file-fixer + exclude_types: [svg] + - id: mixed-line-ending + - id: name-tests-test + args: ["--pytest-test-first"] + - id: no-commit-to-branch #default is master and main + - id: trailing-whitespace + exclude_types: [svg] + + - repo: https://github.com/pycqa/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + additional_dependencies: [pydocstyle>5.1.0, flake8-docstrings>1.4.0, flake8-force] + args: ["--docstring-convention=all"] + - repo: https://github.com/codespell-project/codespell + rev: v2.2.4 + hooks: + - id: codespell + files: ^.*\.(py|c|cpp|h|m|md|rst|yml)$ + args: [ + "--ignore-words", + "ci/codespell-ignore-words.txt", + "--skip", + "doc/users/project/credits.rst" + ] + + - repo: https://github.com/pycqa/isort + rev: 5.12.0 + hooks: + - id: isort + name: isort (python) + files: ^galleries/tutorials/|^galleries/examples/|^galleries/plot_types/ diff --git a/testbed/matplotlib__matplotlib/CITATION.bib b/testbed/matplotlib__matplotlib/CITATION.bib new file mode 100644 index 0000000000000000000000000000000000000000..f9c78873bce38d2c75bf3b5fafa701abf16806e4 --- /dev/null +++ b/testbed/matplotlib__matplotlib/CITATION.bib @@ -0,0 +1,14 @@ +@Article{Hunter:2007, + Author = {Hunter, J. D.}, + Title = {Matplotlib: A 2D graphics environment}, + Journal = {Computing in Science \& Engineering}, + Volume = {9}, + Number = {3}, + Pages = {90--95}, + abstract = {Matplotlib is a 2D graphics package used for Python for + application development, interactive scripting, and publication-quality + image generation across user interfaces and operating systems.}, + publisher = {IEEE COMPUTER SOC}, + doi = {10.1109/MCSE.2007.55}, + year = 2007 +} diff --git a/testbed/matplotlib__matplotlib/CITATION.cff b/testbed/matplotlib__matplotlib/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..ad7af5f76681c5cb66678d73b5b1f65a02e33877 --- /dev/null +++ b/testbed/matplotlib__matplotlib/CITATION.cff @@ -0,0 +1,27 @@ +cff-version: 1.2.0 +message: 'If Matplotlib contributes to a project that leads to a scientific publication, please acknowledge this fact by citing J. D. Hunter, "Matplotlib: A 2D Graphics Environment", Computing in Science & Engineering, vol. 9, no. 3, pp. 90-95, 2007.' +title: 'Matplotlib: Visualization with Python' +authors: + - name: The Matplotlib Development Team + website: https://matplotlib.org/ +type: software +url: 'https://matplotlib.org/' +repository-code: 'https://github.com/matplotlib/matplotlib/' +preferred-citation: + type: article + authors: + - family-names: Hunter + given-names: John D. + title: "Matplotlib: A 2D graphics environment" + year: 2007 + date-published: 2007-06-18 + journal: Computing in Science & Engineering + volume: 9 + issue: 3 + start: 90 + end: 95 + doi: 10.1109/MCSE.2007.55 + publisher: + name: IEEE Computer Society + website: 'https://www.computer.org/' + abstract: Matplotlib is a 2D graphics package used for Python for application development, interactive scripting, and publication-quality image generation across user interfaces and operating systems. diff --git a/testbed/matplotlib__matplotlib/CODE_OF_CONDUCT.md b/testbed/matplotlib__matplotlib/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..1e35beeaf357fff8102804c6f93131f74b88f66a --- /dev/null +++ b/testbed/matplotlib__matplotlib/CODE_OF_CONDUCT.md @@ -0,0 +1,136 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[matplotlib-coc@numfocus.org](mailto:matplotlib-coc@numfocus.org) +(monitored by the [CoC subcommittee](https://matplotlib.org/governance/people.html#coc-subcommittee)) or a +report can be made using the [NumFOCUS Code of Conduct report form][numfocus +form]. If community leaders cannot come to a resolution about enforcement, +reports will be escalated to the NumFocus Code of Conduct committee +(conduct@numfocus.org). All complaints will be reviewed and investigated +promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +[numfocus form]: https://numfocus.typeform.com/to/ynjGdT + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/testbed/matplotlib__matplotlib/INSTALL.rst b/testbed/matplotlib__matplotlib/INSTALL.rst new file mode 100644 index 0000000000000000000000000000000000000000..ac24c70ac5186e970af4c79651d9392d1858bb9a --- /dev/null +++ b/testbed/matplotlib__matplotlib/INSTALL.rst @@ -0,0 +1 @@ +See doc/users/installing/index.rst diff --git a/testbed/matplotlib__matplotlib/README.md b/testbed/matplotlib__matplotlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5e15c645c9a2e1b016c8e22b1d969b248a7e07bc --- /dev/null +++ b/testbed/matplotlib__matplotlib/README.md @@ -0,0 +1,73 @@ +[![PyPi](https://img.shields.io/pypi/v/matplotlib)](https://pypi.org/project/matplotlib/) +[![Conda](https://img.shields.io/conda/vn/conda-forge/matplotlib)](https://anaconda.org/conda-forge/matplotlib) +[![Downloads](https://img.shields.io/pypi/dm/matplotlib)](https://pypi.org/project/matplotlib) +[![NUMFocus](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) + +[![Discourse help forum](https://img.shields.io/badge/help_forum-discourse-blue.svg)](https://discourse.matplotlib.org) +[![Gitter](https://badges.gitter.im/matplotlib/matplotlib.svg)](https://gitter.im/matplotlib/matplotlib) +[![GitHub issues](https://img.shields.io/badge/issue_tracking-github-blue.svg)](https://github.com/matplotlib/matplotlib/issues) +[![Contributing](https://img.shields.io/badge/PR-Welcome-%23FF8300.svg?)](https://matplotlib.org/stable/devel/index.html) + +[![GitHub actions status](https://github.com/matplotlib/matplotlib/workflows/Tests/badge.svg)](https://github.com/matplotlib/matplotlib/actions?query=workflow%3ATests) +[![Azure pipelines status](https://dev.azure.com/matplotlib/matplotlib/_apis/build/status/matplotlib.matplotlib?branchName=main)](https://dev.azure.com/matplotlib/matplotlib/_build/latest?definitionId=1&branchName=main) +[![AppVeyor status](https://ci.appveyor.com/api/projects/status/github/matplotlib/matplotlib?branch=main&svg=true)](https://ci.appveyor.com/project/matplotlib/matplotlib) +[![Codecov status](https://codecov.io/github/matplotlib/matplotlib/badge.svg?branch=main&service=github)](https://app.codecov.io/gh/matplotlib/matplotlib) + +![Matplotlib logotype](https://matplotlib.org/_static/logo2.svg) + +Matplotlib is a comprehensive library for creating static, animated, and +interactive visualizations in Python. + +Check out our [home page](https://matplotlib.org/) for more information. + +![image](https://matplotlib.org/_static/readme_preview.png) + +Matplotlib produces publication-quality figures in a variety of hardcopy +formats and interactive environments across platforms. Matplotlib can be +used in Python scripts, Python/IPython shells, web application servers, +and various graphical user interface toolkits. + +## Install + +See the [install +documentation](https://matplotlib.org/stable/users/installing/index.html), +which is generated from `/doc/users/installing/index.rst` + +## Contribute + +You've discovered a bug or something else you want to change — excellent! + +You've worked out a way to fix it — even better! + +You want to tell us about it — best of all! + +Start at the [contributing +guide](https://matplotlib.org/devdocs/devel/contributing.html)! + +## Contact + +[Discourse](https://discourse.matplotlib.org/) is the discussion forum +for general questions and discussions and our recommended starting +point. + +Our active mailing lists (which are mirrored on Discourse) are: + +- [Users](https://mail.python.org/mailman/listinfo/matplotlib-users) + mailing list: +- [Announcement](https://mail.python.org/mailman/listinfo/matplotlib-announce) + mailing list: +- [Development](https://mail.python.org/mailman/listinfo/matplotlib-devel) + mailing list: + +[Gitter](https://gitter.im/matplotlib/matplotlib) is for coordinating +development and asking questions directly related to contributing to +matplotlib. + +## Citing Matplotlib + +If Matplotlib contributes to a project that leads to publication, please +acknowledge this by citing Matplotlib. + +[A ready-made citation +entry](https://matplotlib.org/stable/users/project/citing.html) is +available. diff --git a/testbed/matplotlib__matplotlib/SECURITY.md b/testbed/matplotlib__matplotlib/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..1de4c3d8e4a3fb244b36471c4abc5f1fd5fc4445 --- /dev/null +++ b/testbed/matplotlib__matplotlib/SECURITY.md @@ -0,0 +1,29 @@ +# Security Policy + +## Supported Versions + +The following table lists versions and whether they are supported. Security +vulnerability reports will be accepted and acted upon for all supported +versions. + +| Version | Supported | +| ------- | ------------------ | +| 3.7.x | :white_check_mark: | +| 3.6.x | :white_check_mark: | +| 3.5.x | :x: | +| 3.4.x | :x: | +| 3.3.x | :x: | +| < 3.3 | :x: | + + +## Reporting a Vulnerability + + +To report a security vulnerability, please use the [Tidelift security +contact](https://tidelift.com/security). Tidelift will coordinate the fix and +disclosure. + +If you have found a security vulnerability, in order to keep it confidential, +please do not report an issue on GitHub. + +We do not award bounties for security vulnerabilities. diff --git a/testbed/matplotlib__matplotlib/azure-pipelines.yml b/testbed/matplotlib__matplotlib/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb38804ae1214b3333fc0d3bd518f85eead16d37 --- /dev/null +++ b/testbed/matplotlib__matplotlib/azure-pipelines.yml @@ -0,0 +1,165 @@ +# Python package +# Create and test a Python package on multiple Python versions. +# Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more: +# https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python?view=azure-devops + +trigger: + branches: + exclude: + - v*-doc +pr: + branches: + exclude: + - v*-doc + paths: + exclude: + - doc/**/* + - galleries/**/* + +stages: + +- stage: Check + jobs: + - job: Skip + pool: + vmImage: 'ubuntu-latest' + variables: + DECODE_PERCENTS: 'false' + RET: 'true' + steps: + - bash: | + git_log=`git log --max-count=1 --skip=1 --pretty=format:"%B" | tr "\n" " "` + echo "##vso[task.setvariable variable=log]$git_log" + - bash: echo "##vso[task.setvariable variable=RET]false" + condition: or(contains(variables.log, '[skip azp]'), contains(variables.log, '[azp skip]'), contains(variables.log, '[skip ci]'), contains(variables.log, '[ci skip]'), contains(variables.log, '[ci doc]')) + - bash: echo "##vso[task.setvariable variable=start_main;isOutput=true]$RET" + name: result + +- stage: Main + condition: and(succeeded(), eq(dependencies.Check.outputs['Skip.result.start_main'], 'true')) + dependsOn: Check + jobs: + - job: Pytest + strategy: + matrix: + Linux_py39: + vmImage: 'ubuntu-20.04' # keep one job pinned to the oldest image + python.version: '3.9' + Linux_py310: + vmImage: 'ubuntu-latest' + python.version: '3.10' + Linux_py311: + vmImage: 'ubuntu-latest' + python.version: '3.11' + macOS_py39: + vmImage: 'macOS-latest' + python.version: '3.9' + macOS_py310: + vmImage: 'macOS-latest' + python.version: '3.10' + macOS_py311: + vmImage: 'macOS-latest' + python.version: '3.11' + Windows_py39: + vmImage: 'windows-2019' # keep one job pinned to the oldest image + python.version: '3.9' + Windows_py310: + vmImage: 'windows-latest' + python.version: '3.10' + Windows_py311: + vmImage: 'windows-latest' + python.version: '3.11' + maxParallel: 4 + pool: + vmImage: '$(vmImage)' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '$(python.version)' + architecture: 'x64' + displayName: 'Use Python $(python.version)' + condition: and(succeeded(), ne(variables['python.version'], 'Pre')) + + - task: stevedower.python.InstallPython.InstallPython@1 + displayName: 'Use prerelease Python' + inputs: + prerelease: true + condition: and(succeeded(), eq(variables['python.version'], 'Pre')) + + - bash: | + set -e + case "$(python -c 'import sys; print(sys.platform)')" in + linux) + echo 'Acquire::Retries "3";' | sudo tee /etc/apt/apt.conf.d/80-retries + sudo apt update + sudo apt install \ + cm-super \ + dvipng \ + ffmpeg \ + fonts-noto-cjk \ + gdb \ + gir1.2-gtk-3.0 \ + graphviz \ + inkscape \ + libcairo2 \ + libgirepository-1.0-1 \ + lmodern \ + fonts-freefont-otf \ + poppler-utils \ + texlive-pictures \ + texlive-fonts-recommended \ + texlive-latex-base \ + texlive-latex-extra \ + texlive-latex-recommended \ + texlive-xetex texlive-luatex \ + ttf-wqy-zenhei + ;; + darwin) + brew install --cask xquartz + brew install pkg-config ffmpeg imagemagick mplayer ccache + brew tap homebrew/cask-fonts + brew install font-noto-sans-cjk-sc + ;; + win32) + ;; + *) + exit 1 + ;; + esac + displayName: 'Install dependencies' + + - bash: | + python -m pip install --upgrade pip + python -m pip install -r requirements/testing/all.txt -r requirements/testing/extra.txt || + [[ "$PYTHON_VERSION" = 'Pre' ]] + displayName: 'Install dependencies with pip' + + - bash: | + python -m pip install -ve . || + [[ "$PYTHON_VERSION" = 'Pre' ]] + displayName: "Install self" + + - script: env + displayName: 'print env' + + - script: pip list + displayName: 'print pip' + + - bash: | + PYTHONFAULTHANDLER=1 python -m pytest --junitxml=junit/test-results.xml -raR --maxfail=50 --timeout=300 --durations=25 --cov-report= --cov=lib -n 2 || + [[ "$PYTHON_VERSION" = 'Pre' ]] + displayName: 'pytest' + + - bash: | + bash <(curl -s https://codecov.io/bash) -f "!*.gcov" -X gcov + displayName: 'Upload to codecov.io' + + - task: PublishTestResults@2 + inputs: + testResultsFiles: '**/test-results.xml' + testRunTitle: 'Python $(python.version)' + condition: succeededOrFailed() + + - publish: $(System.DefaultWorkingDirectory)/result_images + artifact: $(Agent.JobName)-result_images + condition: and(failed(), ne(variables['python.version'], 'Pre')) diff --git a/testbed/matplotlib__matplotlib/environment.yml b/testbed/matplotlib__matplotlib/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..c35b90e9acba1ea373f9630cc0930af15de5ef2c --- /dev/null +++ b/testbed/matplotlib__matplotlib/environment.yml @@ -0,0 +1,65 @@ +# To set up a development environment using conda run: +# +# conda env create -f environment.yml +# conda activate mpl-dev +# pip install -e . +# +name: mpl-dev +channels: + - conda-forge +dependencies: + # runtime dependencies + - cairocffi + - contourpy>=1.0.1 + - cycler>=0.10.0 + - fonttools>=4.22.0 + - importlib-resources>=3.2.0 + - kiwisolver>=1.0.1 + - numpy>=1.21 + - pillow>=6.2 + - pybind11>=2.6.0 + - pygobject + - pyparsing>=2.3.1 + - pyqt + - python-dateutil>=2.1 + - setuptools + - setuptools_scm + - wxpython + # building documentation + - colorspacious + - graphviz + - ipython + - ipywidgets + - numpydoc>=0.8 + - packaging + - pydata-sphinx-theme + - pyyaml + - sphinx>=1.8.1,!=2.0.0 + - sphinx-copybutton + - sphinx-gallery>=0.12 + - sphinx-design + - pip + - pip: + - mpl-sphinx-theme + - sphinxcontrib-svg2pdfconverter + - pikepdf + # testing + - coverage + - flake8>=3.8 + - flake8-docstrings>=1.4.0 + - gtk4 + - ipykernel + - nbconvert[execute]!=6.0.0,!=6.0.1,!=7.3.0,!=7.3.1 + - nbformat!=5.0.0,!=5.0.1 + - pandas!=0.25.0 + - psutil + - pre-commit + - pydocstyle>=5.1.0 + - pytest!=4.6.0,!=5.4.0 + - pytest-cov + - pytest-rerunfailures + - pytest-timeout + - pytest-xdist + - tornado + - pytz + - black diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/README.txt b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ed26f5ef72f822dcefee447348a095ad7796e33 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/README.txt @@ -0,0 +1,4 @@ +.. _subplots_axes_and_figures_examples: + +Subplots, axes and figures +========================== diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..a8076db48528de8000f4804167d90fa1d96628bb --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py @@ -0,0 +1,122 @@ +""" +================ +Axes Zoom Effect +================ + +""" + +import matplotlib.pyplot as plt + +from matplotlib.transforms import (Bbox, TransformedBbox, + blended_transform_factory) +from mpl_toolkits.axes_grid1.inset_locator import (BboxConnector, + BboxConnectorPatch, + BboxPatch) + + +def connect_bbox(bbox1, bbox2, + loc1a, loc2a, loc1b, loc2b, + prop_lines, prop_patches=None): + if prop_patches is None: + prop_patches = { + **prop_lines, + "alpha": prop_lines.get("alpha", 1) * 0.2, + "clip_on": False, + } + + c1 = BboxConnector( + bbox1, bbox2, loc1=loc1a, loc2=loc2a, clip_on=False, **prop_lines) + c2 = BboxConnector( + bbox1, bbox2, loc1=loc1b, loc2=loc2b, clip_on=False, **prop_lines) + + bbox_patch1 = BboxPatch(bbox1, **prop_patches) + bbox_patch2 = BboxPatch(bbox2, **prop_patches) + + p = BboxConnectorPatch(bbox1, bbox2, + loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b, + clip_on=False, + **prop_patches) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs): + """ + Connect *ax1* and *ax2*. The *xmin*-to-*xmax* range in both axes will + be marked. + + Parameters + ---------- + ax1 + The main axes. + ax2 + The zoomed axes. + xmin, xmax + The limits of the colored area in both plot axes. + **kwargs + Arguments passed to the patch constructor. + """ + + bbox = Bbox.from_extents(xmin, 0, xmax, 1) + + mybbox1 = TransformedBbox(bbox, ax1.get_xaxis_transform()) + mybbox2 = TransformedBbox(bbox, ax2.get_xaxis_transform()) + + prop_patches = {**kwargs, "ec": "none", "alpha": 0.2} + + c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox( + mybbox1, mybbox2, + loc1a=3, loc2a=2, loc1b=4, loc2b=1, + prop_lines=kwargs, prop_patches=prop_patches) + + ax1.add_patch(bbox_patch1) + ax2.add_patch(bbox_patch2) + ax2.add_patch(c1) + ax2.add_patch(c2) + ax2.add_patch(p) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +def zoom_effect02(ax1, ax2, **kwargs): + """ + ax1 : the main axes + ax1 : the zoomed axes + + Similar to zoom_effect01. The xmin & xmax will be taken from the + ax1.viewLim. + """ + + tt = ax1.transScale + (ax1.transLimits + ax2.transAxes) + trans = blended_transform_factory(ax2.transData, tt) + + mybbox1 = ax1.bbox + mybbox2 = TransformedBbox(ax1.viewLim, trans) + + prop_patches = {**kwargs, "ec": "none", "alpha": 0.2} + + c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox( + mybbox1, mybbox2, + loc1a=3, loc2a=2, loc1b=4, loc2b=1, + prop_lines=kwargs, prop_patches=prop_patches) + + ax1.add_patch(bbox_patch1) + ax2.add_patch(bbox_patch2) + ax2.add_patch(c1) + ax2.add_patch(c2) + ax2.add_patch(p) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +axs = plt.figure().subplot_mosaic([ + ["zoom1", "zoom2"], + ["main", "main"], +]) + +axs["main"].set(xlim=(0, 5)) +zoom_effect01(axs["zoom1"], axs["main"], 0.2, 0.8) +axs["zoom2"].set(xlim=(2, 3)) +zoom_effect02(axs["zoom2"], axs["main"]) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axhspan_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axhspan_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1d7bff154b6a326f7815b4a13784e8f30966fe --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axhspan_demo.py @@ -0,0 +1,36 @@ +""" +============ +axhspan Demo +============ + +Create lines or rectangles that span the axes in either the horizontal or +vertical direction, and lines than span the axes with an arbitrary orientation. +""" + +import matplotlib.pyplot as plt +import numpy as np + +t = np.arange(-1, 2, .01) +s = np.sin(2 * np.pi * t) + +fig, ax = plt.subplots() + +ax.plot(t, s) +# Thick red horizontal line at y=0 that spans the xrange. +ax.axhline(linewidth=8, color='#d62728') +# Horizontal line at y=1 that spans the xrange. +ax.axhline(y=1) +# Vertical line at x=1 that spans the yrange. +ax.axvline(x=1) +# Thick blue vertical line at x=0 that spans the upper quadrant of the yrange. +ax.axvline(x=0, ymin=0.75, linewidth=8, color='#1f77b4') +# Default hline at y=.5 that spans the middle half of the axes. +ax.axhline(y=.5, xmin=0.25, xmax=0.75) +# Infinite black line going through (0, 0) to (1, 1). +ax.axline((0, 0), (1, 1), color='k') +# 50%-gray rectangle spanning the axes' width from y=0.25 to y=0.75. +ax.axhspan(0.25, 0.75, facecolor='0.5') +# Green rectangle spanning the axes' height from x=1.25 to x=1.55. +ax.axvspan(1.25, 1.55, facecolor='#2ca02c') + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_equal_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_equal_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac4d66da0e80a0eeec1ad44d6182f72ecffcc02 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_equal_demo.py @@ -0,0 +1,35 @@ +""" +======================= +Equal axis aspect ratio +======================= + +How to set and adjust plots with equal axis aspect ratios. +""" + +import matplotlib.pyplot as plt +import numpy as np + +# Plot circle of radius 3. + +an = np.linspace(0, 2 * np.pi, 100) +fig, axs = plt.subplots(2, 2) + +axs[0, 0].plot(3 * np.cos(an), 3 * np.sin(an)) +axs[0, 0].set_title('not equal, looks like ellipse', fontsize=10) + +axs[0, 1].plot(3 * np.cos(an), 3 * np.sin(an)) +axs[0, 1].axis('equal') +axs[0, 1].set_title('equal, looks like circle', fontsize=10) + +axs[1, 0].plot(3 * np.cos(an), 3 * np.sin(an)) +axs[1, 0].axis('equal') +axs[1, 0].set(xlim=(-3, 3), ylim=(-3, 3)) +axs[1, 0].set_title('still a circle, even after changing limits', fontsize=10) + +axs[1, 1].plot(3 * np.cos(an), 3 * np.sin(an)) +axs[1, 1].set_aspect('equal', 'box') +axs[1, 1].set_title('still a circle, auto-adjusted data limits', fontsize=10) + +fig.tight_layout() + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_labels_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_labels_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9d38240e423dcaf5f3e447a68af921faec9713 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_labels_demo.py @@ -0,0 +1,20 @@ +""" +=================== +Axis Label Position +=================== + +Choose axis label position when calling `~.Axes.set_xlabel` and +`~.Axes.set_ylabel` as well as for colorbar. + +""" +import matplotlib.pyplot as plt + +fig, ax = plt.subplots() + +sc = ax.scatter([1, 2], [1, 2], c=[1, 2]) +ax.set_ylabel('YLabel', loc='top') +ax.set_xlabel('XLabel', loc='left') +cbar = fig.colorbar(sc) +cbar.set_label("ZLabel", loc='top') + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/custom_figure_class.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/custom_figure_class.py new file mode 100644 index 0000000000000000000000000000000000000000..96c7f1113787b9aba588ca83201caa5afd93aa34 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/custom_figure_class.py @@ -0,0 +1,52 @@ +""" +======================== +Custom Figure subclasses +======================== + +You can pass a `.Figure` subclass to `.pyplot.figure` if you want to change +the default behavior of the figure. + +This example defines a `.Figure` subclass ``WatermarkFigure`` that accepts an +additional parameter ``watermark`` to display a custom watermark text. The +figure is created using the ``FigureClass`` parameter of `.pyplot.figure`. +The additional ``watermark`` parameter is passed on to the subclass +constructor. +""" + +import matplotlib.pyplot as plt +import numpy as np + +from matplotlib.figure import Figure + + +class WatermarkFigure(Figure): + """A figure with a text watermark.""" + + def __init__(self, *args, watermark=None, **kwargs): + super().__init__(*args, **kwargs) + + if watermark is not None: + bbox = dict(boxstyle='square', lw=3, ec='gray', + fc=(0.9, 0.9, .9, .5), alpha=0.5) + self.text(0.5, 0.5, watermark, + ha='center', va='center', rotation=30, + fontsize=40, color='gray', alpha=0.5, bbox=bbox) + + +x = np.linspace(-3, 3, 201) +y = np.tanh(x) + 0.1 * np.cos(5 * x) + +plt.figure(FigureClass=WatermarkFigure, watermark='draft') +plt.plot(x, y) + + +# %% +# +# .. admonition:: References +# +# The use of the following functions, methods, classes and modules is shown +# in this example: +# +# - `matplotlib.pyplot.figure` +# - `matplotlib.figure.Figure` +# - `matplotlib.figure.Figure.text` diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/demo_tight_layout.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/demo_tight_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc5f5301db4e3dfa871ba01d5943f5113246d70 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/demo_tight_layout.py @@ -0,0 +1,134 @@ +""" +=============================== +Resizing axes with tight layout +=============================== + +`~.Figure.tight_layout` attempts to resize subplots in a figure so that there +are no overlaps between axes objects and labels on the axes. + +See :ref:`tight_layout_guide` for more details and +:ref:`constrainedlayout_guide` for an alternative. + +""" + +import itertools +import warnings + +import matplotlib.pyplot as plt + +fontsizes = itertools.cycle([8, 16, 24, 32]) + + +def example_plot(ax): + ax.plot([1, 2]) + ax.set_xlabel('x-label', fontsize=next(fontsizes)) + ax.set_ylabel('y-label', fontsize=next(fontsizes)) + ax.set_title('Title', fontsize=next(fontsizes)) + + +# %% + +fig, ax = plt.subplots() +example_plot(ax) +fig.tight_layout() + +# %% + +fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) +fig.tight_layout() + +# %% + +fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1) +example_plot(ax1) +example_plot(ax2) +fig.tight_layout() + +# %% + +fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) +example_plot(ax1) +example_plot(ax2) +fig.tight_layout() + +# %% + +fig, axs = plt.subplots(nrows=3, ncols=3) +for ax in axs.flat: + example_plot(ax) +fig.tight_layout() + +# %% + +plt.figure() +ax1 = plt.subplot(221) +ax2 = plt.subplot(223) +ax3 = plt.subplot(122) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +plt.tight_layout() + +# %% + +plt.figure() +ax1 = plt.subplot2grid((3, 3), (0, 0)) +ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) +ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) +ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) +plt.tight_layout() + +# %% + +fig = plt.figure() + +gs1 = fig.add_gridspec(3, 1) +ax1 = fig.add_subplot(gs1[0]) +ax2 = fig.add_subplot(gs1[1]) +ax3 = fig.add_subplot(gs1[2]) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +gs1.tight_layout(fig, rect=[None, None, 0.45, None]) + +gs2 = fig.add_gridspec(2, 1) +ax4 = fig.add_subplot(gs2[0]) +ax5 = fig.add_subplot(gs2[1]) +example_plot(ax4) +example_plot(ax5) +with warnings.catch_warnings(): + # gs2.tight_layout cannot handle the subplots from the first gridspec + # (gs1), so it will raise a warning. We are going to match the gridspecs + # manually so we can filter the warning away. + warnings.simplefilter("ignore", UserWarning) + gs2.tight_layout(fig, rect=[0.45, None, None, None]) + +# now match the top and bottom of two gridspecs. +top = min(gs1.top, gs2.top) +bottom = max(gs1.bottom, gs2.bottom) + +gs1.update(top=top, bottom=bottom) +gs2.update(top=top, bottom=bottom) + +plt.show() + +# %% +# +# .. admonition:: References +# +# The use of the following functions, methods, classes and modules is shown +# in this example: +# +# - `matplotlib.figure.Figure.tight_layout` / +# `matplotlib.pyplot.tight_layout` +# - `matplotlib.figure.Figure.add_gridspec` +# - `matplotlib.figure.Figure.add_subplot` +# - `matplotlib.pyplot.subplot2grid` diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/gridspec_nested.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/gridspec_nested.py new file mode 100644 index 0000000000000000000000000000000000000000..a2750a0ecb497d5e8ca69e2bba3c11f438643a65 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/gridspec_nested.py @@ -0,0 +1,46 @@ +""" +================ +Nested Gridspecs +================ + +GridSpecs can be nested, so that a subplot from a parent GridSpec can +set the position for a nested grid of subplots. + +Note that the same functionality can be achieved more directly with +`~.FigureBase.subfigures`; see +:doc:`/gallery/subplots_axes_and_figures/subfigures`. + +""" +import matplotlib.pyplot as plt + +import matplotlib.gridspec as gridspec + + +def format_axes(fig): + for i, ax in enumerate(fig.axes): + ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center") + ax.tick_params(labelbottom=False, labelleft=False) + + +# gridspec inside gridspec +fig = plt.figure() + +gs0 = gridspec.GridSpec(1, 2, figure=fig) + +gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0]) + +ax1 = fig.add_subplot(gs00[:-1, :]) +ax2 = fig.add_subplot(gs00[-1, :-1]) +ax3 = fig.add_subplot(gs00[-1, -1]) + +# the following syntax does the same as the GridSpecFromSubplotSpec call above: +gs01 = gs0[1].subgridspec(3, 3) + +ax4 = fig.add_subplot(gs01[:, :-1]) +ax5 = fig.add_subplot(gs01[:-1, -1]) +ax6 = fig.add_subplot(gs01[-1, -1]) + +plt.suptitle("GridSpec Inside GridSpec") +format_axes(fig) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/multiple_figs_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/multiple_figs_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb9962c8e28874faad3679ee5850407235e6446 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/multiple_figs_demo.py @@ -0,0 +1,51 @@ +""" +=================================== +Managing multiple figures in pyplot +=================================== + +`matplotlib.pyplot` uses the concept of a *current figure* and *current axes*. +Figures are identified via a figure number that is passed to `~.pyplot.figure`. +The figure with the given number is set as *current figure*. Additionally, if +no figure with the number exists, a new one is created. + +.. note:: + + We discourage working with multiple figures through the implicit pyplot + interface because managing the *current figure* is cumbersome and + error-prone. Instead, we recommend using the explicit approach and call + methods on Figure and Axes instances. See :ref:`api_interfaces` for an + explanation of the trade-offs between the implicit and explicit interfaces. + +""" +import matplotlib.pyplot as plt +import numpy as np + +t = np.arange(0.0, 2.0, 0.01) +s1 = np.sin(2*np.pi*t) +s2 = np.sin(4*np.pi*t) + +# %% +# Create figure 1 + +plt.figure(1) +plt.subplot(211) +plt.plot(t, s1) +plt.subplot(212) +plt.plot(t, 2*s1) + +# %% +# Create figure 2 + +plt.figure(2) +plt.plot(t, s2) + +# %% +# Now switch back to figure 1 and make some changes + +plt.figure(1) +plt.subplot(211) +plt.plot(t, s2, 's') +ax = plt.gca() +ax.set_xticklabels([]) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/subplot.py b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/subplot.py new file mode 100644 index 0000000000000000000000000000000000000000..4b78e7a5a8401e6fbb19e41dff81a437186c8d8f --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/subplot.py @@ -0,0 +1,51 @@ +""" +================= +Multiple subplots +================= + +Simple demo with multiple subplots. + +For more options, see :doc:`/gallery/subplots_axes_and_figures/subplots_demo`. + +.. redirect-from:: /gallery/subplots_axes_and_figures/subplot_demo +""" + +import matplotlib.pyplot as plt +import numpy as np + +# Create some fake data. +x1 = np.linspace(0.0, 5.0) +y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) +x2 = np.linspace(0.0, 2.0) +y2 = np.cos(2 * np.pi * x2) + +# %% +# `~.pyplot.subplots()` is the recommended method to generate simple subplot +# arrangements: + +fig, (ax1, ax2) = plt.subplots(2, 1) +fig.suptitle('A tale of 2 subplots') + +ax1.plot(x1, y1, 'o-') +ax1.set_ylabel('Damped oscillation') + +ax2.plot(x2, y2, '.-') +ax2.set_xlabel('time (s)') +ax2.set_ylabel('Undamped') + +plt.show() + +# %% +# Subplots can also be generated one at a time using `~.pyplot.subplot()`: + +plt.subplot(2, 1, 1) +plt.plot(x1, y1, 'o-') +plt.title('A tale of 2 subplots') +plt.ylabel('Damped oscillation') + +plt.subplot(2, 1, 2) +plt.plot(x2, y2, '.-') +plt.xlabel('time (s)') +plt.ylabel('Undamped') + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/fancytextbox_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/fancytextbox_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..940ed9349170424988a00a8f58569891cc8fadc9 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/fancytextbox_demo.py @@ -0,0 +1,26 @@ +""" +================== +Styling text boxes +================== + +This example shows how to style text boxes using *bbox* parameters. +""" +import matplotlib.pyplot as plt + +plt.text(0.6, 0.7, "eggs", size=50, rotation=30., + ha="center", va="center", + bbox=dict(boxstyle="round", + ec=(1., 0.5, 0.5), + fc=(1., 0.8, 0.8), + ) + ) + +plt.text(0.55, 0.6, "spam", size=50, rotation=-25., + ha="right", va="top", + bbox=dict(boxstyle="square", + ec=(1., 0.5, 0.5), + fc=(1., 0.8, 0.8), + ) + ) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/mathtext_demo.py b/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/mathtext_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..c41596b91f49ffe94b73714309bfd16bd13102c4 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/mathtext_demo.py @@ -0,0 +1,26 @@ +""" +======== +Mathtext +======== + +Use Matplotlib's internal LaTeX parser and layout engine. For true LaTeX +rendering, see the text.usetex option. +""" + +import matplotlib.pyplot as plt + +fig, ax = plt.subplots() + +ax.plot([1, 2, 3], label=r'$\sqrt{x^2}$') +ax.legend() + +ax.set_xlabel(r'$\Delta_i^j$', fontsize=20) +ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20) +ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} ' + r'\Delta_{i+1}^j$', fontsize=20) + +tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$' +ax.text(1, 1.6, tex, fontsize=20, va='bottom') + +fig.tight_layout() +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/plot_types/README.rst b/testbed/matplotlib__matplotlib/galleries/plot_types/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..0bcbb3b804d78a36f5adc572ec77efdd77fa2fbf --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/plot_types/README.rst @@ -0,0 +1,11 @@ +.. _plot_types: + +.. redirect-from:: /tutorials/basic/sample_plots + +Plot types +========== + +Overview of many common plotting commands provided by Matplotlib. + +See the `gallery <../gallery/index.html>`_ for more examples and +the `tutorials page <../tutorials/index.html>`_ for longer examples. diff --git a/testbed/matplotlib__matplotlib/galleries/plot_types/stats/hist2d.py b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/hist2d.py new file mode 100644 index 0000000000000000000000000000000000000000..3e43f7ee8ace00f8a705f1c571cdb310fb267318 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/hist2d.py @@ -0,0 +1,25 @@ +""" +============ +hist2d(x, y) +============ + +See `~matplotlib.axes.Axes.hist2d`. +""" +import matplotlib.pyplot as plt +import numpy as np + +plt.style.use('_mpl-gallery-nogrid') + +# make data: correlated + noise +np.random.seed(1) +x = np.random.randn(5000) +y = 1.2 * x + np.random.randn(5000) / 3 + +# plot: +fig, ax = plt.subplots() + +ax.hist2d(x, y, bins=(np.arange(-3, 3, 0.1), np.arange(-3, 3, 0.1))) + +ax.set(xlim=(-2, 2), ylim=(-3, 3)) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/plot_types/stats/pie.py b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/pie.py new file mode 100644 index 0000000000000000000000000000000000000000..80484a0eb9328e6bb6457422418c527871b78fc4 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/pie.py @@ -0,0 +1,26 @@ +""" +====== +pie(x) +====== + +See `~matplotlib.axes.Axes.pie`. +""" +import matplotlib.pyplot as plt +import numpy as np + +plt.style.use('_mpl-gallery-nogrid') + + +# make data +x = [1, 2, 3, 4] +colors = plt.get_cmap('Blues')(np.linspace(0.2, 0.7, len(x))) + +# plot +fig, ax = plt.subplots() +ax.pie(x, colors=colors, radius=3, center=(4, 4), + wedgeprops={"linewidth": 1, "edgecolor": "white"}, frame=True) + +ax.set(xlim=(0, 8), xticks=np.arange(1, 8), + ylim=(0, 8), yticks=np.arange(1, 8)) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/plot_types/stats/violin.py b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/violin.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a987a690dd01aa793665b5e716f0655a63d3e5 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/plot_types/stats/violin.py @@ -0,0 +1,28 @@ +""" +============= +violinplot(D) +============= + +See `~matplotlib.axes.Axes.violinplot`. +""" +import matplotlib.pyplot as plt +import numpy as np + +plt.style.use('_mpl-gallery') + +# make data: +np.random.seed(10) +D = np.random.normal((3, 5, 4), (0.75, 1.00, 0.75), (200, 3)) + +# plot: +fig, ax = plt.subplots() + +vp = ax.violinplot(D, [2, 4, 6], widths=2, + showmeans=False, showmedians=False, showextrema=False) +# styling: +for body in vp['bodies']: + body.set_alpha(0.9) +ax.set(xlim=(0, 8), xticks=np.arange(1, 8), + ylim=(0, 8), yticks=np.arange(1, 8)) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/animations/animations.py b/testbed/matplotlib__matplotlib/galleries/users_explain/animations/animations.py new file mode 100644 index 0000000000000000000000000000000000000000..b022350c898554b5dc93545a2b7c210c3370cab3 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/animations/animations.py @@ -0,0 +1,247 @@ +""" +.. redirect-from:: /tutorials/introductory/animation_tutorial + +.. _animations: + +=========================== +Animations using Matplotlib +=========================== + +Based on its plotting functionality, Matplotlib also provides an interface to +generate animations using the `~matplotlib.animation` module. An +animation is a sequence of frames where each frame corresponds to a plot on a +`~matplotlib.figure.Figure`. This tutorial covers a general guideline on +how to create such animations and the different options available. +""" + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib.animation as animation + +# %% +# Animation Classes +# ================= +# +# The animation process in Matplotlib can be thought of in 2 different ways: +# +# - `~matplotlib.animation.FuncAnimation`: Generate data for first +# frame and then modify this data for each frame to create an animated plot. +# +# - `~matplotlib.animation.ArtistAnimation`: Generate a list (iterable) +# of artists that will draw in each frame in the animation. +# +# `~matplotlib.animation.FuncAnimation` is more efficient in terms of +# speed and memory as it draws an artist once and then modifies it. On the +# other hand `~matplotlib.animation.ArtistAnimation` is flexible as it +# allows any iterable of artists to be animated in a sequence. +# +# ``FuncAnimation`` +# ----------------- +# +# The `~matplotlib.animation.FuncAnimation` class allows us to create an +# animation by passing a function that iteratively modifies the data of a plot. +# This is achieved by using the *setter* methods on various +# `~matplotlib.artist.Artist` (examples: `~matplotlib.lines.Line2D`, +# `~matplotlib.collections.PathCollection`, etc.). A usual +# `~matplotlib.animation.FuncAnimation` object takes a +# `~matplotlib.figure.Figure` that we want to animate and a function +# *func* that modifies the data plotted on the figure. It uses the *frames* +# parameter to determine the length of the animation. The *interval* parameter +# is used to determine time in milliseconds between drawing of two frames. +# Animating using `.FuncAnimation` would usually follow the following +# structure: +# +# - Plot the initial figure, including all the required artists. Save all the +# artists in variables so that they can be updated later on during the +# animation. +# - Create an animation function that updates the data in each artist to +# generate the new frame at each function call. +# - Create a `.FuncAnimation` object with the `.Figure` and the animation +# function, along with the keyword arguments that determine the animation +# properties. +# - Use `.animation.Animation.save` or `.pyplot.show` to save or show the +# animation. +# +# The update function uses the ``set_*`` function for different artists to +# modify the data. The following table shows a few plotting methods, the artist +# types they return and some methods that can be used to update them. +# +# ======================================== ============================= =========================== +# Plotting method Artist Set method +# ======================================== ============================= =========================== +# `.Axes.plot` `.lines.Line2D` `~.lines.Line2D.set_data` +# `.Axes.scatter` `.collections.PathCollection` `~.collections.\ +# PathCollection.set_offsets` +# `.Axes.imshow` `.image.AxesImage` ``AxesImage.set_data`` +# `.Axes.annotate` `.text.Annotation` `~.text.Annotation.\ +# update_positions` +# `.Axes.barh` `.patches.Rectangle` `~.Rectangle.set_angle`, +# `~.Rectangle.set_bounds`, +# `~.Rectangle.set_height`, +# `~.Rectangle.set_width`, +# `~.Rectangle.set_x`, +# `~.Rectangle.set_y`, +# `~.Rectangle.set_xy` +# `.Axes.fill` `.patches.Polygon` `~.Polygon.set_xy` +# `.Axes.add_patch`\(`.patches.Ellipse`\) `.patches.Ellipse` `~.Ellipse.set_angle`, +# `~.Ellipse.set_center`, +# `~.Ellipse.set_height`, +# `~.Ellipse.set_width` +# ======================================== ============================= =========================== +# +# Covering the set methods for all types of artists is beyond the scope of this +# tutorial but can be found in their respective documentations. An example of +# such update methods in use for `.Axes.scatter` and `.Axes.plot` is as follows. + +fig, ax = plt.subplots() +t = np.linspace(0, 3, 40) +g = -9.81 +v0 = 12 +z = g * t**2 / 2 + v0 * t + +v02 = 5 +z2 = g * t**2 / 2 + v02 * t + +scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s') +line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0] +ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]') +ax.legend() + + +def update(frame): + # for each frame, update the data stored on each artist. + x = t[:frame] + y = z[:frame] + # update the scatter plot: + data = np.stack([x, y]).T + scat.set_offsets(data) + # update the line plot: + line2.set_xdata(t[:frame]) + line2.set_ydata(z2[:frame]) + return (scat, line2) + + +ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30) +plt.show() + + +# %% +# ``ArtistAnimation`` +# ------------------- +# +# `~matplotlib.animation.ArtistAnimation` can be used +# to generate animations if there is data stored on various different artists. +# This list of artists is then converted frame by frame into an animation. For +# example, when we use `.Axes.barh` to plot a bar-chart, it creates a number of +# artists for each of the bar and error bars. To update the plot, one would +# need to update each of the bars from the container individually and redraw +# them. Instead, `.animation.ArtistAnimation` can be used to plot each frame +# individually and then stitched together to form an animation. A barchart race +# is a simple example for this. + + +fig, ax = plt.subplots() +rng = np.random.default_rng(19680801) +data = np.array([20, 20, 20, 20]) +x = np.array([1, 2, 3, 4]) + +artists = [] +colors = ['tab:blue', 'tab:red', 'tab:green', 'tab:purple'] +for i in range(20): + data += rng.integers(low=0, high=10, size=data.shape) + container = ax.barh(x, data, color=colors) + artists.append(container) + + +ani = animation.ArtistAnimation(fig=fig, artists=artists, interval=400) +plt.show() + +# %% +# Animation Writers +# ================= +# +# Animation objects can be saved to disk using various multimedia writers +# (ex: Pillow, *ffpmeg*, *imagemagick*). Not all video formats are supported +# by all writers. There are 4 major types of writers: +# +# - `~matplotlib.animation.PillowWriter` - Uses the Pillow library to +# create the animation. +# +# - `~matplotlib.animation.HTMLWriter` - Used to create JavaScript-based +# animations. +# +# - Pipe-based writers - `~matplotlib.animation.FFMpegWriter` and +# `~matplotlib.animation.ImageMagickWriter` are pipe based writers. +# These writers pipe each frame to the utility (*ffmpeg* / *imagemagick*) +# which then stitches all of them together to create the animation. +# +# - File-based writers - `~matplotlib.animation.FFMpegFileWriter` and +# `~matplotlib.animation.ImageMagickFileWriter` are examples of +# file-based writers. These writers are slower than their pipe-based +# alternatives but are more useful for debugging as they save each frame in +# a file before stitching them together into an animation. +# +# Saving Animations +# ----------------- +# +# .. list-table:: +# :header-rows: 1 +# +# * - Writer +# - Supported Formats +# * - `~matplotlib.animation.PillowWriter` +# - .gif, .apng, .webp +# * - `~matplotlib.animation.HTMLWriter` +# - .htm, .html, .png +# * - | `~matplotlib.animation.FFMpegWriter` +# | `~matplotlib.animation.FFMpegFileWriter` +# - All formats supported by |ffmpeg|_: ``ffmpeg -formats`` +# * - | `~matplotlib.animation.ImageMagickWriter` +# | `~matplotlib.animation.ImageMagickFileWriter` +# - All formats supported by |imagemagick|_: ``magick -list format`` +# +# .. _ffmpeg: https://www.ffmpeg.org/general.html#Supported-File-Formats_002c-Codecs-or-Features +# .. |ffmpeg| replace:: *ffmpeg* +# +# .. _imagemagick: https://imagemagick.org/script/formats.php#supported +# .. |imagemagick| replace:: *imagemagick* +# +# To save animations using any of the writers, we can use the +# `.animation.Animation.save` method. It takes the *filename* that we want to +# save the animation as and the *writer*, which is either a string or a writer +# object. It also takes an *fps* argument. This argument is different than the +# *interval* argument that `~.animation.FuncAnimation` or +# `~.animation.ArtistAnimation` uses. *fps* determines the frame rate that the +# **saved** animation uses, whereas *interval* determines the frame rate that +# the **displayed** animation uses. +# +# Below are a few examples that show how to save an animation with different +# writers. +# +# +# Pillow writers:: +# +# ani.save(filename="/tmp/pillow_example.gif", writer="pillow") +# ani.save(filename="/tmp/pillow_example.apng", writer="pillow") +# +# HTML writers:: +# +# ani.save(filename="/tmp/html_example.html", writer="html") +# ani.save(filename="/tmp/html_example.htm", writer="html") +# ani.save(filename="/tmp/html_example.png", writer="html") +# +# FFMpegWriter:: +# +# ani.save(filename="/tmp/ffmpeg_example.mkv", writer="ffmpeg") +# ani.save(filename="/tmp/ffmpeg_example.mp4", writer="ffmpeg") +# ani.save(filename="/tmp/ffmpeg_example.mjpeg", writer="ffmpeg") +# +# Imagemagick writers:: +# +# ani.save(filename="/tmp/imagemagick_example.gif", writer="imagemagick") +# ani.save(filename="/tmp/imagemagick_example.webp", writer="imagemagick") +# ani.save(filename="apng:/tmp/imagemagick_example.apng", +# writer="imagemagick", extra_args=["-quality", "100"]) +# +# (the ``extra_args`` for *apng* are needed to reduce filesize by ~10x) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/animations/blitting.py b/testbed/matplotlib__matplotlib/galleries/users_explain/animations/blitting.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e658f8a3cbc2c2ba96bc380e3e51decb28cac0 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/animations/blitting.py @@ -0,0 +1,232 @@ +""" +.. redirect-from:: /tutorials/advanced/blitting + +.. _blitting: + +================================== +Faster rendering by using blitting +================================== + +*Blitting* is a `standard technique +`__ in raster graphics that, +in the context of Matplotlib, can be used to (drastically) improve +performance of interactive figures. For example, the +:mod:`.animation` and :mod:`.widgets` modules use blitting +internally. Here, we demonstrate how to implement your own blitting, outside +of these classes. + +Blitting speeds up repetitive drawing by rendering all non-changing +graphic elements into a background image once. Then, for every draw, only the +changing elements need to be drawn onto this background. For example, +if the limits of an Axes have not changed, we can render the empty Axes +including all ticks and labels once, and only draw the changing data later. + +The strategy is + +- Prepare the constant background: + + - Draw the figure, but exclude all artists that you want to animate by + marking them as *animated* (see `.Artist.set_animated`). + - Save a copy of the RBGA buffer. + +- Render the individual images: + + - Restore the copy of the RGBA buffer. + - Redraw the animated artists using `.Axes.draw_artist` / + `.Figure.draw_artist`. + - Show the resulting image on the screen. + +One consequence of this procedure is that your animated artists are always +drawn on top of the static artists. + +Not all backends support blitting. You can check if a given canvas does via +the `.FigureCanvasBase.supports_blit` property. + +.. warning:: + + This code does not work with the OSX backend (but does work with other + GUI backends on Mac). + +Minimal example +--------------- + +We can use the `.FigureCanvasAgg` methods +`~.FigureCanvasAgg.copy_from_bbox` and +`~.FigureCanvasAgg.restore_region` in conjunction with setting +``animated=True`` on our artist to implement a minimal example that +uses blitting to accelerate rendering + +""" + +import matplotlib.pyplot as plt +import numpy as np + +x = np.linspace(0, 2 * np.pi, 100) + +fig, ax = plt.subplots() + +# animated=True tells matplotlib to only draw the artist when we +# explicitly request it +(ln,) = ax.plot(x, np.sin(x), animated=True) + +# make sure the window is raised, but the script keeps going +plt.show(block=False) + +# stop to admire our empty window axes and ensure it is rendered at +# least once. +# +# We need to fully draw the figure at its final size on the screen +# before we continue on so that : +# a) we have the correctly sized and drawn background to grab +# b) we have a cached renderer so that ``ax.draw_artist`` works +# so we spin the event loop to let the backend process any pending operations +plt.pause(0.1) + +# get copy of entire figure (everything inside fig.bbox) sans animated artist +bg = fig.canvas.copy_from_bbox(fig.bbox) +# draw the animated artist, this uses a cached renderer +ax.draw_artist(ln) +# show the result to the screen, this pushes the updated RGBA buffer from the +# renderer to the GUI framework so you can see it +fig.canvas.blit(fig.bbox) + +for j in range(100): + # reset the background back in the canvas state, screen unchanged + fig.canvas.restore_region(bg) + # update the artist, neither the canvas state nor the screen have changed + ln.set_ydata(np.sin(x + (j / 100) * np.pi)) + # re-render the artist, updating the canvas state, but not the screen + ax.draw_artist(ln) + # copy the image to the GUI state, but screen might not be changed yet + fig.canvas.blit(fig.bbox) + # flush any pending GUI events, re-painting the screen if needed + fig.canvas.flush_events() + # you can put a pause in if you want to slow things down + # plt.pause(.1) + +# %% +# This example works and shows a simple animation, however because we +# are only grabbing the background once, if the size of the figure in +# pixels changes (due to either the size or dpi of the figure +# changing) , the background will be invalid and result in incorrect +# (but sometimes cool looking!) images. There is also a global +# variable and a fair amount of boilerplate which suggests we should +# wrap this in a class. +# +# Class-based example +# ------------------- +# +# We can use a class to encapsulate the boilerplate logic and state of +# restoring the background, drawing the artists, and then blitting the +# result to the screen. Additionally, we can use the ``'draw_event'`` +# callback to capture a new background whenever a full re-draw +# happens to handle resizes correctly. + + +class BlitManager: + def __init__(self, canvas, animated_artists=()): + """ + Parameters + ---------- + canvas : FigureCanvasAgg + The canvas to work with, this only works for subclasses of the Agg + canvas which have the `~FigureCanvasAgg.copy_from_bbox` and + `~FigureCanvasAgg.restore_region` methods. + + animated_artists : Iterable[Artist] + List of the artists to manage + """ + self.canvas = canvas + self._bg = None + self._artists = [] + + for a in animated_artists: + self.add_artist(a) + # grab the background on every draw + self.cid = canvas.mpl_connect("draw_event", self.on_draw) + + def on_draw(self, event): + """Callback to register with 'draw_event'.""" + cv = self.canvas + if event is not None: + if event.canvas != cv: + raise RuntimeError + self._bg = cv.copy_from_bbox(cv.figure.bbox) + self._draw_animated() + + def add_artist(self, art): + """ + Add an artist to be managed. + + Parameters + ---------- + art : Artist + + The artist to be added. Will be set to 'animated' (just + to be safe). *art* must be in the figure associated with + the canvas this class is managing. + + """ + if art.figure != self.canvas.figure: + raise RuntimeError + art.set_animated(True) + self._artists.append(art) + + def _draw_animated(self): + """Draw all of the animated artists.""" + fig = self.canvas.figure + for a in self._artists: + fig.draw_artist(a) + + def update(self): + """Update the screen with animated artists.""" + cv = self.canvas + fig = cv.figure + # paranoia in case we missed the draw event, + if self._bg is None: + self.on_draw(None) + else: + # restore the background + cv.restore_region(self._bg) + # draw all of the animated artists + self._draw_animated() + # update the GUI state + cv.blit(fig.bbox) + # let the GUI event loop process anything it has to do + cv.flush_events() + + +# %% +# Here is how we would use our class. This is a slightly more complicated +# example than the first case as we add a text frame counter as well. + +# make a new figure +fig, ax = plt.subplots() +# add a line +(ln,) = ax.plot(x, np.sin(x), animated=True) +# add a frame number +fr_number = ax.annotate( + "0", + (0, 1), + xycoords="axes fraction", + xytext=(10, -10), + textcoords="offset points", + ha="left", + va="top", + animated=True, +) +bm = BlitManager(fig.canvas, [ln, fr_number]) +# make sure our window is on the screen and drawn +plt.show(block=False) +plt.pause(.1) + +for j in range(100): + # update the artists + ln.set_ydata(np.sin(x + (j / 100) * np.pi)) + fr_number.set_text(f"frame: {j}") + # tell the blitting manager to do its thing + bm.update() + +# %% +# This class does not depend on `.pyplot` and is suitable to embed +# into larger GUI application. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/artist_intro.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/artist_intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..213a945f44b87df3ce2563ebfd593f1bf629d0d3 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/artist_intro.rst @@ -0,0 +1,186 @@ +.. _users_artists: + +Introduction to Artists +----------------------- + +Almost all objects you interact with on a Matplotlib plot are called "Artist" +(and are subclasses of the `.Artist` class). :doc:`Figure <../figure/index>` +and :doc:`Axes <../axes/index>` are Artists, and generally contain +`~.axis.Axis` Artists and Artists that contain data or annotation information. + + +Creating Artists +~~~~~~~~~~~~~~~~ + +Usually we do not instantiate Artists directly, but rather use a plotting +method on `~.axes.Axes`. Some examples of plotting methods and the Artist +object they create is given below: + +========================================= ================= +Axes helper method Artist +========================================= ================= +`~.axes.Axes.annotate` - text annotations `.Annotation` +`~.axes.Axes.bar` - bar charts `.Rectangle` +`~.axes.Axes.errorbar` - error bar plots `.Line2D` and + `.Rectangle` +`~.axes.Axes.fill` - shared area `.Polygon` +`~.axes.Axes.hist` - histograms `.Rectangle` +`~.axes.Axes.imshow` - image data `.AxesImage` +`~.axes.Axes.legend` - Axes legend `.Legend` +`~.axes.Axes.plot` - xy plots `.Line2D` +`~.axes.Axes.scatter` - scatter charts `.PolyCollection` +`~.axes.Axes.text` - text `.Text` +========================================= ================= + +As an example, we can save the Line2D Artist returned from `.axes.Axes.plot`: + +.. sourcecode:: ipython + + In [209]: import matplotlib.pyplot as plt + In [210]: import matplotlib.artist as martist + In [211]: import numpy as np + + In [212]: fig, ax = plt.subplots() + In [213]: x, y = np.random.rand(2, 100) + In [214]: lines = ax.plot(x, y, '-', label='example') + In [215]: print(lines) + [] + +Note that ``plot`` returns a _list_ of lines because you can pass in multiple x, +y pairs to plot. The line has been added to the Axes, and we can retrieve the +Artist via `~.Axes.get_lines()`: + +.. sourcecode:: ipython + + In [216]: print(ax.get_lines()) + + In [217]: print(ax.get_lines()[0]) + Line2D(example) + +Changing Artist properties +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Getting the ``lines`` object gives us access to all the properties of the +Line2D object. So if we want to change the *linewidth* after the fact, we can do so using `.Artist.set`. + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(4, 2.5)) + x = np.arange(0, 13, 0.2) + y = np.sin(x) + lines = ax.plot(x, y, '-', label='example', linewidth=0.2, color='blue') + lines[0].set(color='green', linewidth=2) + +We can interrogate the full list of settable properties with +`matplotlib.artist.getp`: + +.. sourcecode:: ipython + + In [218]: martist.getp(lines[0]) + agg_filter = None + alpha = None + animated = False + antialiased or aa = True + bbox = Bbox(x0=0.004013842290585101, y0=0.013914221641967... + children = [] + clip_box = TransformedBbox( Bbox(x0=0.0, y0=0.0, x1=1.0, ... + clip_on = True + clip_path = None + color or c = blue + dash_capstyle = butt + dash_joinstyle = round + data = (array([0.91377845, 0.58456834, 0.36492019, 0.0379... + drawstyle or ds = default + figure = Figure(550x450) + fillstyle = full + gapcolor = None + gid = None + in_layout = True + label = example + linestyle or ls = - + linewidth or lw = 2.0 + marker = None + markeredgecolor or mec = blue + markeredgewidth or mew = 1.0 + markerfacecolor or mfc = blue + markerfacecoloralt or mfcalt = none + markersize or ms = 6.0 + markevery = None + mouseover = False + path = Path(array([[0.91377845, 0.51224793], [0.58... + path_effects = [] + picker = None + pickradius = 5 + rasterized = False + sketch_params = None + snap = None + solid_capstyle = projecting + solid_joinstyle = round + tightbbox = Bbox(x0=70.4609002763619, y0=54.321277798941786, x... + transform = CompositeGenericTransform( TransformWrapper( ... + transformed_clip_path_and_affine = (None, None) + url = None + visible = True + window_extent = Bbox(x0=70.4609002763619, y0=54.321277798941786, x... + xdata = [0.91377845 0.58456834 0.36492019 0.03796664 0.884... + xydata = [[0.91377845 0.51224793] [0.58456834 0.9820474 ] ... + ydata = [0.51224793 0.9820474 0.24469912 0.61647032 0.483... + zorder = 2 + +Note most Artists also have a distinct list of setters; e.g. +`.Line2D.set_color` or `.Line2D.set_linewidth`. + +Changing Artist data +~~~~~~~~~~~~~~~~~~~~ + +In addition to styling properties like *color* and *linewidth*, the Line2D +object has a *data* property. You can set the data after the line has been +created using `.Line2D.set_data`. This is often used for Animations, where the +same line is shown evolving over time (see :doc:`../animations/index`) + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(4, 2.5)) + x = np.arange(0, 13, 0.2) + y = np.sin(x) + lines = ax.plot(x, y, '-', label='example') + lines[0].set_data([x, np.cos(x)]) + +Manually adding Artists +~~~~~~~~~~~~~~~~~~~~~~~ + +Not all Artists have helper methods, or you may want to use a low-level method +for some reason. For example the `.patches.Circle` Artist does not have a +helper, but we can still create and add to an Axes using the +`.axes.Axes.add_artist` method: + +.. plot:: + :include-source: + + import matplotlib.patches as mpatches + + fig, ax = plt.subplots(figsize=(4, 2.5)) + circle = mpatches.Circle((0.5, 0.5), 0.25, ec="none") + ax.add_artist(circle) + clipped_circle = mpatches.Circle((1, 0.5), 0.125, ec="none", facecolor='C1') + ax.add_artist(clipped_circle) + ax.set_aspect(1) + +The Circle takes the center and radius of the Circle as arguments to its +constructor; optional arguments are passed as keyword arguments. + +Note that when we add an Artist manually like this, it doesn't necessarily +adjust the axis limits like most of the helper methods do, so the Artists can +be clipped, as is the case above for the ``clipped_circle`` patch. + +See :ref:`artist_reference` for other patches. + +Removing Artists +~~~~~~~~~~~~~~~~ + +Sometimes we want to remove an Artist from a figure without re-specifying the +whole figure from scratch. Most Artists have a usable *remove* method that +will remove the Artist from its Axes list. For instance ``lines[0].remove()`` +would remove the *Line2D* artist created in the example above. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/imshow_extent.py b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/imshow_extent.py new file mode 100644 index 0000000000000000000000000000000000000000..d222af6aee26d35aa43b61fce865d5df6c219097 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/imshow_extent.py @@ -0,0 +1,266 @@ +""" +.. redirect-from:: /tutorials/intermediate/imshow_extent + +.. _imshow_extent: + +*origin* and *extent* in `~.Axes.imshow` +======================================== + +:meth:`~.Axes.imshow` allows you to render an image (either a 2D array which +will be color-mapped (based on *norm* and *cmap*) or a 3D RGB(A) array which +will be used as-is) to a rectangular region in data space. The orientation of +the image in the final rendering is controlled by the *origin* and *extent* +keyword arguments (and attributes on the resulting `.AxesImage` instance) and +the data limits of the axes. + +The *extent* keyword arguments controls the bounding box in data coordinates +that the image will fill specified as ``(left, right, bottom, top)`` in **data +coordinates**, the *origin* keyword argument controls how the image fills that +bounding box, and the orientation in the final rendered image is also affected +by the axes limits. + +.. hint:: Most of the code below is used for adding labels and informative + text to the plots. The described effects of *origin* and *extent* can be + seen in the plots without the need to follow all code details. + + For a quick understanding, you may want to skip the code details below and + directly continue with the discussion of the results. +""" +import matplotlib.pyplot as plt +import numpy as np + +from matplotlib.gridspec import GridSpec + + +def index_to_coordinate(index, extent, origin): + """Return the pixel center of an index.""" + left, right, bottom, top = extent + + hshift = 0.5 * np.sign(right - left) + left, right = left + hshift, right - hshift + vshift = 0.5 * np.sign(top - bottom) + bottom, top = bottom + vshift, top - vshift + + if origin == 'upper': + bottom, top = top, bottom + + return { + "[0, 0]": (left, bottom), + "[M', 0]": (left, top), + "[0, N']": (right, bottom), + "[M', N']": (right, top), + }[index] + + +def get_index_label_pos(index, extent, origin, inverted_xindex): + """ + Return the desired position and horizontal alignment of an index label. + """ + if extent is None: + extent = lookup_extent(origin) + left, right, bottom, top = extent + x, y = index_to_coordinate(index, extent, origin) + + is_x0 = index[-2:] == "0]" + halign = 'left' if is_x0 ^ inverted_xindex else 'right' + hshift = 0.5 * np.sign(left - right) + x += hshift * (1 if is_x0 else -1) + return x, y, halign + + +def get_color(index, data, cmap): + """Return the data color of an index.""" + val = { + "[0, 0]": data[0, 0], + "[0, N']": data[0, -1], + "[M', 0]": data[-1, 0], + "[M', N']": data[-1, -1], + }[index] + return cmap(val / data.max()) + + +def lookup_extent(origin): + """Return extent for label positioning when not given explicitly.""" + if origin == 'lower': + return (-0.5, 6.5, -0.5, 5.5) + else: + return (-0.5, 6.5, 5.5, -0.5) + + +def set_extent_None_text(ax): + ax.text(3, 2.5, 'equals\nextent=None', size='large', + ha='center', va='center', color='w') + + +def plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim): + """Actually run ``imshow()`` and add extent and index labels.""" + im = ax.imshow(data, origin=origin, extent=extent) + + # extent labels (left, right, bottom, top) + left, right, bottom, top = im.get_extent() + if xlim is None or top > bottom: + upper_string, lower_string = 'top', 'bottom' + else: + upper_string, lower_string = 'bottom', 'top' + if ylim is None or left < right: + port_string, starboard_string = 'left', 'right' + inverted_xindex = False + else: + port_string, starboard_string = 'right', 'left' + inverted_xindex = True + bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': "round4"} + ann_kwargs = {'xycoords': 'axes fraction', + 'textcoords': 'offset points', + 'bbox': bbox_kwargs} + ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1), + ha='center', va='top', **ann_kwargs) + ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1), + ha='center', va='bottom', **ann_kwargs) + ax.annotate(port_string, xy=(0, .5), xytext=(1, 0), + ha='left', va='center', rotation=90, + **ann_kwargs) + ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0), + ha='right', va='center', rotation=-90, + **ann_kwargs) + ax.set_title(f'origin: {origin}') + + # index labels + for index in ["[0, 0]", "[0, N']", "[M', 0]", "[M', N']"]: + tx, ty, halign = get_index_label_pos(index, extent, origin, + inverted_xindex) + facecolor = get_color(index, data, im.get_cmap()) + ax.text(tx, ty, index, color='white', ha=halign, va='center', + bbox={'boxstyle': 'square', 'facecolor': facecolor}) + if xlim: + ax.set_xlim(*xlim) + if ylim: + ax.set_ylim(*ylim) + + +def generate_imshow_demo_grid(extents, xlim=None, ylim=None): + N = len(extents) + fig = plt.figure(tight_layout=True) + fig.set_size_inches(6, N * (11.25) / 5) + gs = GridSpec(N, 5, figure=fig) + + columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)], + 'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)], + 'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]} + x, y = np.ogrid[0:6, 0:7] + data = x + y + + for origin in ['upper', 'lower']: + for ax, extent in zip(columns[origin], extents): + plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim) + + columns['label'][0].set_title('extent=') + for ax, extent in zip(columns['label'], extents): + if extent is None: + text = 'None' + else: + left, right, bottom, top = extent + text = (f'left: {left:0.1f}\nright: {right:0.1f}\n' + f'bottom: {bottom:0.1f}\ntop: {top:0.1f}\n') + ax.text(1., .5, text, transform=ax.transAxes, ha='right', va='center') + ax.axis('off') + return columns + + +# %% +# +# Default extent +# -------------- +# +# First, let's have a look at the default ``extent=None`` + +generate_imshow_demo_grid(extents=[None]) + +# %% +# +# Generally, for an array of shape (M, N), the first index runs along the +# vertical, the second index runs along the horizontal. +# The pixel centers are at integer positions ranging from 0 to ``N' = N - 1`` +# horizontally and from 0 to ``M' = M - 1`` vertically. +# *origin* determines how the data is filled in the bounding box. +# +# For ``origin='lower'``: +# +# - [0, 0] is at (left, bottom) +# - [M', 0] is at (left, top) +# - [0, N'] is at (right, bottom) +# - [M', N'] is at (right, top) +# +# ``origin='upper'`` reverses the vertical axes direction and filling: +# +# - [0, 0] is at (left, top) +# - [M', 0] is at (left, bottom) +# - [0, N'] is at (right, top) +# - [M', N'] is at (right, bottom) +# +# In summary, the position of the [0, 0] index as well as the extent are +# influenced by *origin*: +# +# ====== =============== ========================================== +# origin [0, 0] position extent +# ====== =============== ========================================== +# upper top left ``(-0.5, numcols-0.5, numrows-0.5, -0.5)`` +# lower bottom left ``(-0.5, numcols-0.5, -0.5, numrows-0.5)`` +# ====== =============== ========================================== +# +# The default value of *origin* is set by :rc:`image.origin` which defaults +# to ``'upper'`` to match the matrix indexing conventions in math and +# computer graphics image indexing conventions. +# +# +# Explicit extent +# --------------- +# +# By setting *extent* we define the coordinates of the image area. The +# underlying image data is interpolated/resampled to fill that area. +# +# If the axes is set to autoscale, then the view limits of the axes are set +# to match the *extent* which ensures that the coordinate set by +# ``(left, bottom)`` is at the bottom left of the axes! However, this +# may invert the axis so they do not increase in the 'natural' direction. +# + +extents = [(-0.5, 6.5, -0.5, 5.5), + (-0.5, 6.5, 5.5, -0.5), + (6.5, -0.5, -0.5, 5.5), + (6.5, -0.5, 5.5, -0.5)] + +columns = generate_imshow_demo_grid(extents) +set_extent_None_text(columns['upper'][1]) +set_extent_None_text(columns['lower'][0]) + + +# %% +# +# Explicit extent and axes limits +# ------------------------------- +# +# If we fix the axes limits by explicitly setting `~.axes.Axes.set_xlim` / +# `~.axes.Axes.set_ylim`, we force a certain size and orientation of the axes. +# This can decouple the 'left-right' and 'top-bottom' sense of the image from +# the orientation on the screen. +# +# In the example below we have chosen the limits slightly larger than the +# extent (note the white areas within the Axes). +# +# While we keep the extents as in the examples before, the coordinate (0, 0) +# is now explicitly put at the bottom left and values increase to up and to +# the right (from the viewer's point of view). +# We can see that: +# +# - The coordinate ``(left, bottom)`` anchors the image which then fills the +# box going towards the ``(right, top)`` point in data space. +# - The first column is always closest to the 'left'. +# - *origin* controls if the first row is closest to 'top' or 'bottom'. +# - The image may be inverted along either direction. +# - The 'left-right' and 'top-bottom' sense of the image may be uncoupled from +# the orientation on the screen. + +generate_imshow_demo_grid(extents=[None] + extents, + xlim=(-2, 8), ylim=(-1, 6)) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/index.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d3f2918c9a915e7a50d8fd93c1f83c50ea7abed8 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/index.rst @@ -0,0 +1,23 @@ ++++++++ +Artists ++++++++ + +Almost all objects you interact with on a Matplotlib plot are called "Artist" +(and are subclasses of the `.Artist` class). :doc:`Figure <../figure/index>` +and :doc:`Axes <../axes/index>` are Artists, and generally contain +`~.axis.Axis` Artists and Artists that contain data or annotation information. + +.. toctree:: + :maxdepth: 2 + + artist_intro + +.. toctree:: + :maxdepth: 1 + + Automated color cycle + Optimizing Artists for performance + Paths + Path effects guide + Understanding the extent keyword argument of imshow + transforms_tutorial diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/paths.py b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..d505711fd1c0a8a3153d600b06e844f893ec839e --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/paths.py @@ -0,0 +1,236 @@ +""" +.. redirect-from:: /tutorials/advanced/path_tutorial + +.. _paths: + +============= +Path Tutorial +============= + +Defining paths in your Matplotlib visualization. + +The object underlying all of the :mod:`matplotlib.patches` objects is +the :class:`~matplotlib.path.Path`, which supports the standard set of +moveto, lineto, curveto commands to draw simple and compound outlines +consisting of line segments and splines. The ``Path`` is instantiated +with a (N, 2) array of (x, y) vertices, and an N-length array of path +codes. For example to draw the unit rectangle from (0, 0) to (1, 1), we +could use this code: +""" + +import matplotlib.pyplot as plt + +import matplotlib.patches as patches +from matplotlib.path import Path + +verts = [ + (0., 0.), # left, bottom + (0., 1.), # left, top + (1., 1.), # right, top + (1., 0.), # right, bottom + (0., 0.), # ignored +] + +codes = [ + Path.MOVETO, + Path.LINETO, + Path.LINETO, + Path.LINETO, + Path.CLOSEPOLY, +] + +path = Path(verts, codes) + +fig, ax = plt.subplots() +patch = patches.PathPatch(path, facecolor='orange', lw=2) +ax.add_patch(patch) +ax.set_xlim(-2, 2) +ax.set_ylim(-2, 2) +plt.show() + + +# %% +# The following path codes are recognized +# +# ============= ======================== ====================================== +# Code Vertices Description +# ============= ======================== ====================================== +# ``STOP`` 1 (ignored) A marker for the end of the entire +# path (currently not required and +# ignored). +# ``MOVETO`` 1 Pick up the pen and move to the given +# vertex. +# ``LINETO`` 1 Draw a line from the current position +# to the given vertex. +# ``CURVE3`` 2: Draw a quadratic Bézier curve from the +# 1 control point, current position, with the given +# 1 end point control point, to the given end point. +# ``CURVE4`` 3: Draw a cubic Bézier curve from the +# 2 control points, current position, with the given +# 1 end point control points, to the given end +# point. +# ``CLOSEPOLY`` 1 (the point is ignored) Draw a line segment to the start point +# of the current polyline. +# ============= ======================== ====================================== +# +# +# .. path-curves: +# +# +# Bézier example +# ============== +# +# Some of the path components require multiple vertices to specify them: +# for example CURVE 3 is a `Bézier +# `_ curve with one +# control point and one end point, and CURVE4 has three vertices for the +# two control points and the end point. The example below shows a +# CURVE4 Bézier spline -- the Bézier curve will be contained in the +# convex hull of the start point, the two control points, and the end +# point + +verts = [ + (0., 0.), # P0 + (0.2, 1.), # P1 + (1., 0.8), # P2 + (0.8, 0.), # P3 +] + +codes = [ + Path.MOVETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, +] + +path = Path(verts, codes) + +fig, ax = plt.subplots() +patch = patches.PathPatch(path, facecolor='none', lw=2) +ax.add_patch(patch) + +xs, ys = zip(*verts) +ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10) + +ax.text(-0.05, -0.05, 'P0') +ax.text(0.15, 1.05, 'P1') +ax.text(1.05, 0.85, 'P2') +ax.text(0.85, -0.05, 'P3') + +ax.set_xlim(-0.1, 1.1) +ax.set_ylim(-0.1, 1.1) +plt.show() + +# %% +# .. compound_paths: +# +# Compound paths +# ============== +# +# All of the simple patch primitives in matplotlib, Rectangle, Circle, +# Polygon, etc, are implemented with simple path. Plotting functions +# like :meth:`~matplotlib.axes.Axes.hist` and +# :meth:`~matplotlib.axes.Axes.bar`, which create a number of +# primitives, e.g., a bunch of Rectangles, can usually be implemented more +# efficiently using a compound path. The reason ``bar`` creates a list +# of rectangles and not a compound path is largely historical: the +# :class:`~matplotlib.path.Path` code is comparatively new and ``bar`` +# predates it. While we could change it now, it would break old code, +# so here we will cover how to create compound paths, replacing the +# functionality in bar, in case you need to do so in your own code for +# efficiency reasons, e.g., you are creating an animated bar plot. +# +# We will make the histogram chart by creating a series of rectangles +# for each histogram bar: the rectangle width is the bin width and the +# rectangle height is the number of datapoints in that bin. First we'll +# create some random normally distributed data and compute the +# histogram. Because NumPy returns the bin edges and not centers, the +# length of ``bins`` is one greater than the length of ``n`` in the +# example below:: +# +# # histogram our data with numpy +# data = np.random.randn(1000) +# n, bins = np.histogram(data, 100) +# +# We'll now extract the corners of the rectangles. Each of the +# ``left``, ``bottom``, etc., arrays below is ``len(n)``, where ``n`` is +# the array of counts for each histogram bar:: +# +# # get the corners of the rectangles for the histogram +# left = np.array(bins[:-1]) +# right = np.array(bins[1:]) +# bottom = np.zeros(len(left)) +# top = bottom + n +# +# Now we have to construct our compound path, which will consist of a +# series of ``MOVETO``, ``LINETO`` and ``CLOSEPOLY`` for each rectangle. +# For each rectangle, we need five vertices: one for the ``MOVETO``, +# three for the ``LINETO``, and one for the ``CLOSEPOLY``. As indicated +# in the table above, the vertex for the closepoly is ignored, but we still +# need it to keep the codes aligned with the vertices:: +# +# nverts = nrects*(1+3+1) +# verts = np.zeros((nverts, 2)) +# codes = np.ones(nverts, int) * path.Path.LINETO +# codes[0::5] = path.Path.MOVETO +# codes[4::5] = path.Path.CLOSEPOLY +# verts[0::5, 0] = left +# verts[0::5, 1] = bottom +# verts[1::5, 0] = left +# verts[1::5, 1] = top +# verts[2::5, 0] = right +# verts[2::5, 1] = top +# verts[3::5, 0] = right +# verts[3::5, 1] = bottom +# +# All that remains is to create the path, attach it to a +# :class:`~matplotlib.patches.PathPatch`, and add it to our axes:: +# +# barpath = path.Path(verts, codes) +# patch = patches.PathPatch(barpath, facecolor='green', +# edgecolor='yellow', alpha=0.5) +# ax.add_patch(patch) + +import numpy as np + +import matplotlib.patches as patches +import matplotlib.path as path + +fig, ax = plt.subplots() +# Fixing random state for reproducibility +np.random.seed(19680801) + +# histogram our data with numpy +data = np.random.randn(1000) +n, bins = np.histogram(data, 100) + +# get the corners of the rectangles for the histogram +left = np.array(bins[:-1]) +right = np.array(bins[1:]) +bottom = np.zeros(len(left)) +top = bottom + n +nrects = len(left) + +nverts = nrects*(1+3+1) +verts = np.zeros((nverts, 2)) +codes = np.ones(nverts, int) * path.Path.LINETO +codes[0::5] = path.Path.MOVETO +codes[4::5] = path.Path.CLOSEPOLY +verts[0::5, 0] = left +verts[0::5, 1] = bottom +verts[1::5, 0] = left +verts[1::5, 1] = top +verts[2::5, 0] = right +verts[2::5, 1] = top +verts[3::5, 0] = right +verts[3::5, 1] = bottom + +barpath = path.Path(verts, codes) +patch = patches.PathPatch(barpath, facecolor='green', + edgecolor='yellow', alpha=0.5) +ax.add_patch(patch) + +ax.set_xlim(left[0], right[-1]) +ax.set_ylim(bottom.min(), top.max()) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/performance.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/performance.rst new file mode 100644 index 0000000000000000000000000000000000000000..20ac800abad6e51f6a7aced1ee297eef129ba212 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/performance.rst @@ -0,0 +1,148 @@ +.. redirect-from:: /users/explain/performance + +.. _performance: + +Performance +=========== + +Whether exploring data in interactive mode or programmatically +saving lots of plots, rendering performance can be a challenging +bottleneck in your pipeline. Matplotlib provides multiple +ways to greatly reduce rendering time at the cost of a slight +change (to a settable tolerance) in your plot's appearance. +The methods available to reduce rendering time depend on the +type of plot that is being created. + +Line segment simplification +--------------------------- + +For plots that have line segments (e.g. typical line plots, outlines +of polygons, etc.), rendering performance can be controlled by +:rc:`path.simplify` and :rc:`path.simplify_threshold`, which +can be defined e.g. in the :file:`matplotlibrc` file (see +:ref:`customizing` for more information about +the :file:`matplotlibrc` file). :rc:`path.simplify` is a Boolean +indicating whether or not line segments are simplified at all. +:rc:`path.simplify_threshold` controls how much line segments are simplified; +higher thresholds result in quicker rendering. + +The following script will first display the data without any +simplification, and then display the same data with simplification. +Try interacting with both of them:: + + import numpy as np + import matplotlib.pyplot as plt + import matplotlib as mpl + + # Setup, and create the data to plot + y = np.random.rand(100000) + y[50000:] *= 2 + y[np.geomspace(10, 50000, 400).astype(int)] = -1 + mpl.rcParams['path.simplify'] = True + + mpl.rcParams['path.simplify_threshold'] = 0.0 + plt.plot(y) + plt.show() + + mpl.rcParams['path.simplify_threshold'] = 1.0 + plt.plot(y) + plt.show() + +Matplotlib currently defaults to a conservative simplification +threshold of ``1/9``. To change default settings to use a different +value, change the :file:`matplotlibrc` file. Alternatively, users +can create a new style for interactive plotting (with maximal +simplification) and another style for publication quality plotting +(with minimal simplification) and activate them as necessary. See +:ref:`customizing` for instructions on +how to perform these actions. + +The simplification works by iteratively merging line segments +into a single vector until the next line segment's perpendicular +distance to the vector (measured in display-coordinate space) +is greater than the ``path.simplify_threshold`` parameter. + +.. note:: + Changes related to how line segments are simplified were made + in version 2.1. Rendering time will still be improved by these + parameters prior to 2.1, but rendering time for some kinds of + data will be vastly improved in versions 2.1 and greater. + +Marker subsampling +------------------ + +Markers can also be simplified, albeit less robustly than line +segments. Marker subsampling is only available to `.Line2D` objects +(through the ``markevery`` property). Wherever `.Line2D` construction +parameters are passed through, such as `.pyplot.plot` and `.Axes.plot`, +the ``markevery`` parameter can be used:: + + plt.plot(x, y, markevery=10) + +The ``markevery`` argument allows for naive subsampling, or an +attempt at evenly spaced (along the *x* axis) sampling. See the +:doc:`/gallery/lines_bars_and_markers/markevery_demo` +for more information. + +Splitting lines into smaller chunks +----------------------------------- + +If you are using the Agg backend (see :ref:`what-is-a-backend`), +then you can make use of :rc:`agg.path.chunksize` +This allows users to specify a chunk size, and any lines with +greater than that many vertices will be split into multiple +lines, each of which has no more than ``agg.path.chunksize`` +many vertices. (Unless ``agg.path.chunksize`` is zero, in +which case there is no chunking.) For some kind of data, +chunking the line up into reasonable sizes can greatly +decrease rendering time. + +The following script will first display the data without any +chunk size restriction, and then display the same data with +a chunk size of 10,000. The difference can best be seen when +the figures are large, try maximizing the GUI and then +interacting with them:: + + import numpy as np + import matplotlib.pyplot as plt + import matplotlib as mpl + mpl.rcParams['path.simplify_threshold'] = 1.0 + + # Setup, and create the data to plot + y = np.random.rand(100000) + y[50000:] *= 2 + y[np.geomspace(10, 50000, 400).astype(int)] = -1 + mpl.rcParams['path.simplify'] = True + + mpl.rcParams['agg.path.chunksize'] = 0 + plt.plot(y) + plt.show() + + mpl.rcParams['agg.path.chunksize'] = 10000 + plt.plot(y) + plt.show() + +Legends +------- + +The default legend behavior for axes attempts to find the location +that covers the fewest data points (``loc='best'``). This can be a +very expensive computation if there are lots of data points. In +this case, you may want to provide a specific location. + +Using the *fast* style +---------------------- + +The *fast* style can be used to automatically set +simplification and chunking parameters to reasonable +settings to speed up plotting large amounts of data. +The following code runs it:: + + import matplotlib.style as mplstyle + mplstyle.use('fast') + +It is very lightweight, so it works well with other +styles. Be sure the fast style is applied last +so that other styles do not overwrite the settings:: + + mplstyle.use(['dark_background', 'ggplot', 'fast']) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/artists/transforms_tutorial.py b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/transforms_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e71ad111d711aac875e9f2683f8d63596ddbc3 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/artists/transforms_tutorial.py @@ -0,0 +1,587 @@ +""" +.. redirect-from:: /tutorials/advanced/transforms_tutorial + +.. _transforms_tutorial: + +======================== +Transformations Tutorial +======================== + +Like any graphics packages, Matplotlib is built on top of a transformation +framework to easily move between coordinate systems, the userland *data* +coordinate system, the *axes* coordinate system, the *figure* coordinate +system, and the *display* coordinate system. In 95% of your plotting, you +won't need to think about this, as it happens under the hood, but as you push +the limits of custom figure generation, it helps to have an understanding of +these objects, so you can reuse the existing transformations Matplotlib makes +available to you, or create your own (see :mod:`matplotlib.transforms`). The +table below summarizes some useful coordinate systems, a description of each +system, and the transformation object for going from each coordinate system to +the *display* coordinates. In the "Transformation Object" column, ``ax`` is a +:class:`~matplotlib.axes.Axes` instance, ``fig`` is a +:class:`~matplotlib.figure.Figure` instance, and ``subfigure`` is a +:class:`~matplotlib.figure.SubFigure` instance. + + ++----------------+-----------------------------------+---------------------------------------------------+ +|Coordinate |Description |Transformation object | +|system | |from system to display | ++================+===================================+===================================================+ +|"data" |The coordinate system of the data |``ax.transData`` | +| |in the Axes. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"axes" |The coordinate system of the |``ax.transAxes`` | +| |`~matplotlib.axes.Axes`; (0, 0) | | +| |is bottom left of the axes, and | | +| |(1, 1) is top right of the axes. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"subfigure" |The coordinate system of the |``subfigure.transSubfigure`` | +| |`.SubFigure`; (0, 0) is bottom left| | +| |of the subfigure, and (1, 1) is top| | +| |right of the subfigure. If a | | +| |figure has no subfigures, this is | | +| |the same as ``transFigure``. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"figure" |The coordinate system of the |``fig.transFigure`` | +| |`.Figure`; (0, 0) is bottom left | | +| |of the figure, and (1, 1) is top | | +| |right of the figure. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"figure-inches" |The coordinate system of the |``fig.dpi_scale_trans`` | +| |`.Figure` in inches; (0, 0) is | | +| |bottom left of the figure, and | | +| |(width, height) is the top right | | +| |of the figure in inches. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"xaxis", |Blended coordinate systems, using |``ax.get_xaxis_transform()``, | +|"yaxis" |data coordinates on one direction |``ax.get_yaxis_transform()`` | +| |and axes coordinates on the other. | | ++----------------+-----------------------------------+---------------------------------------------------+ +|"display" |The native coordinate system of the|`None`, or | +| |output ; (0, 0) is the bottom left |:class:`~matplotlib.transforms.IdentityTransform()`| +| |of the window, and (width, height) | | +| |is top right of the output in | | +| |"display units". | | +| | | | +| |The exact interpretation of the | | +| |units depends on the back end. For | | +| |example it is pixels for Agg and | | +| |points for svg/pdf. | | ++----------------+-----------------------------------+---------------------------------------------------+ + + + + + +The `~matplotlib.transforms.Transform` objects are naive to the source and +destination coordinate systems, however the objects referred to in the table +above are constructed to take inputs in their coordinate system, and transform +the input to the *display* coordinate system. That is why the *display* +coordinate system has `None` for the "Transformation Object" column -- it +already is in *display* coordinates. The naming and destination conventions +are an aid to keeping track of the available "standard" coordinate systems and +transforms. + +The transformations also know how to invert themselves (via +`.Transform.inverted`) to generate a transform from output coordinate system +back to the input coordinate system. For example, ``ax.transData`` converts +values in data coordinates to display coordinates and +``ax.transData.inversed()`` is a :class:`matplotlib.transforms.Transform` that +goes from display coordinates to data coordinates. This is particularly useful +when processing events from the user interface, which typically occur in +display space, and you want to know where the mouse click or key-press occurred +in your *data* coordinate system. + +Note that specifying the position of Artists in *display* coordinates may +change their relative location if the ``dpi`` or size of the figure changes. +This can cause confusion when printing or changing screen resolution, because +the object can change location and size. Therefore, it is most common for +artists placed in an Axes or figure to have their transform set to something +*other* than the `~.transforms.IdentityTransform()`; the default when an artist +is added to an Axes using `~.axes.Axes.add_artist` is for the transform to be +``ax.transData`` so that you can work and think in *data* coordinates and let +Matplotlib take care of the transformation to *display*. + +.. _data-coords: + +Data coordinates +================ + +Let's start with the most commonly used coordinate, the *data* coordinate +system. Whenever you add data to the axes, Matplotlib updates the datalimits, +most commonly updated with the :meth:`~matplotlib.axes.Axes.set_xlim` and +:meth:`~matplotlib.axes.Axes.set_ylim` methods. For example, in the figure +below, the data limits stretch from 0 to 10 on the x-axis, and -1 to 1 on the +y-axis. + +""" + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib.patches as mpatches + +x = np.arange(0, 10, 0.005) +y = np.exp(-x/2.) * np.sin(2*np.pi*x) + +fig, ax = plt.subplots() +ax.plot(x, y) +ax.set_xlim(0, 10) +ax.set_ylim(-1, 1) + +plt.show() + +# %% +# You can use the ``ax.transData`` instance to transform from your +# *data* to your *display* coordinate system, either a single point or a +# sequence of points as shown below: +# +# .. sourcecode:: ipython +# +# In [14]: type(ax.transData) +# Out[14]: +# +# In [15]: ax.transData.transform((5, 0)) +# Out[15]: array([ 335.175, 247. ]) +# +# In [16]: ax.transData.transform([(5, 0), (1, 2)]) +# Out[16]: +# array([[ 335.175, 247. ], +# [ 132.435, 642.2 ]]) +# +# You can use the :meth:`~matplotlib.transforms.Transform.inverted` +# method to create a transform which will take you from *display* to *data* +# coordinates: +# +# .. sourcecode:: ipython +# +# In [41]: inv = ax.transData.inverted() +# +# In [42]: type(inv) +# Out[42]: +# +# In [43]: inv.transform((335.175, 247.)) +# Out[43]: array([ 5., 0.]) +# +# If your are typing along with this tutorial, the exact values of the +# *display* coordinates may differ if you have a different window size or +# dpi setting. Likewise, in the figure below, the display labeled +# points are probably not the same as in the ipython session because the +# documentation figure size defaults are different. + +x = np.arange(0, 10, 0.005) +y = np.exp(-x/2.) * np.sin(2*np.pi*x) + +fig, ax = plt.subplots() +ax.plot(x, y) +ax.set_xlim(0, 10) +ax.set_ylim(-1, 1) + +xdata, ydata = 5, 0 +# This computing the transform now, if anything +# (figure size, dpi, axes placement, data limits, scales..) +# changes re-calling transform will get a different value. +xdisplay, ydisplay = ax.transData.transform((xdata, ydata)) + +bbox = dict(boxstyle="round", fc="0.8") +arrowprops = dict( + arrowstyle="->", + connectionstyle="angle,angleA=0,angleB=90,rad=10") + +offset = 72 +ax.annotate(f'data = ({xdata:.1f}, {ydata:.1f})', + (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points', + bbox=bbox, arrowprops=arrowprops) + +disp = ax.annotate(f'display = ({xdisplay:.1f}, {ydisplay:.1f})', + (xdisplay, ydisplay), xytext=(0.5*offset, -offset), + xycoords='figure pixels', + textcoords='offset points', + bbox=bbox, arrowprops=arrowprops) + +plt.show() + +# %% +# .. warning:: +# +# If you run the source code in the example above in a GUI backend, +# you may also find that the two arrows for the *data* and *display* +# annotations do not point to exactly the same point. This is because +# the display point was computed before the figure was displayed, and +# the GUI backend may slightly resize the figure when it is created. +# The effect is more pronounced if you resize the figure yourself. +# This is one good reason why you rarely want to work in *display* +# space, but you can connect to the ``'on_draw'`` +# :class:`~matplotlib.backend_bases.Event` to update *figure* +# coordinates on figure draws; see :ref:`event-handling`. +# +# When you change the x or y limits of your axes, the data limits are +# updated so the transformation yields a new display point. Note that +# when we just change the ylim, only the y-display coordinate is +# altered, and when we change the xlim too, both are altered. More on +# this later when we talk about the +# :class:`~matplotlib.transforms.Bbox`. +# +# .. sourcecode:: ipython +# +# In [54]: ax.transData.transform((5, 0)) +# Out[54]: array([ 335.175, 247. ]) +# +# In [55]: ax.set_ylim(-1, 2) +# Out[55]: (-1, 2) +# +# In [56]: ax.transData.transform((5, 0)) +# Out[56]: array([ 335.175 , 181.13333333]) +# +# In [57]: ax.set_xlim(10, 20) +# Out[57]: (10, 20) +# +# In [58]: ax.transData.transform((5, 0)) +# Out[58]: array([-171.675 , 181.13333333]) +# +# +# .. _axes-coords: +# +# Axes coordinates +# ================ +# +# After the *data* coordinate system, *axes* is probably the second most +# useful coordinate system. Here the point (0, 0) is the bottom left of +# your axes or subplot, (0.5, 0.5) is the center, and (1.0, 1.0) is the +# top right. You can also refer to points outside the range, so (-0.1, +# 1.1) is to the left and above your axes. This coordinate system is +# extremely useful when placing text in your axes, because you often +# want a text bubble in a fixed, location, e.g., the upper left of the axes +# pane, and have that location remain fixed when you pan or zoom. Here +# is a simple example that creates four panels and labels them 'A', 'B', +# 'C', 'D' as you often see in journals. + +fig = plt.figure() +for i, label in enumerate(('A', 'B', 'C', 'D')): + ax = fig.add_subplot(2, 2, i+1) + ax.text(0.05, 0.95, label, transform=ax.transAxes, + fontsize=16, fontweight='bold', va='top') + +plt.show() + +# %% +# You can also make lines or patches in the *axes* coordinate system, but +# this is less useful in my experience than using ``ax.transAxes`` for +# placing text. Nonetheless, here is a silly example which plots some +# random dots in data space, and overlays a semi-transparent +# :class:`~matplotlib.patches.Circle` centered in the middle of the axes +# with a radius one quarter of the axes -- if your axes does not +# preserve aspect ratio (see :meth:`~matplotlib.axes.Axes.set_aspect`), +# this will look like an ellipse. Use the pan/zoom tool to move around, +# or manually change the data xlim and ylim, and you will see the data +# move, but the circle will remain fixed because it is not in *data* +# coordinates and will always remain at the center of the axes. + +fig, ax = plt.subplots() +x, y = 10*np.random.rand(2, 1000) +ax.plot(x, y, 'go', alpha=0.2) # plot some data in data coordinates + +circ = mpatches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes, + facecolor='blue', alpha=0.75) +ax.add_patch(circ) +plt.show() + +# %% +# .. _blended_transformations: +# +# Blended transformations +# ======================= +# +# Drawing in *blended* coordinate spaces which mix *axes* with *data* +# coordinates is extremely useful, for example to create a horizontal +# span which highlights some region of the y-data but spans across the +# x-axis regardless of the data limits, pan or zoom level, etc. In fact +# these blended lines and spans are so useful, we have built-in +# functions to make them easy to plot (see +# :meth:`~matplotlib.axes.Axes.axhline`, +# :meth:`~matplotlib.axes.Axes.axvline`, +# :meth:`~matplotlib.axes.Axes.axhspan`, +# :meth:`~matplotlib.axes.Axes.axvspan`) but for didactic purposes we +# will implement the horizontal span here using a blended +# transformation. This trick only works for separable transformations, +# like you see in normal Cartesian coordinate systems, but not on +# inseparable transformations like the +# :class:`~matplotlib.projections.polar.PolarAxes.PolarTransform`. + +import matplotlib.transforms as transforms + +fig, ax = plt.subplots() +x = np.random.randn(1000) + +ax.hist(x, 30) +ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16) + +# the x coords of this transformation are data, and the y coord are axes +trans = transforms.blended_transform_factory( + ax.transData, ax.transAxes) +# highlight the 1..2 stddev region with a span. +# We want x to be in data coordinates and y to span from 0..1 in axes coords. +rect = mpatches.Rectangle((1, 0), width=1, height=1, transform=trans, + color='yellow', alpha=0.5) +ax.add_patch(rect) + +plt.show() + +# %% +# .. note:: +# +# The blended transformations where x is in *data* coords and y in *axes* +# coordinates is so useful that we have helper methods to return the +# versions Matplotlib uses internally for drawing ticks, ticklabels, etc. +# The methods are :meth:`matplotlib.axes.Axes.get_xaxis_transform` and +# :meth:`matplotlib.axes.Axes.get_yaxis_transform`. So in the example +# above, the call to +# :meth:`~matplotlib.transforms.blended_transform_factory` can be +# replaced by ``get_xaxis_transform``:: +# +# trans = ax.get_xaxis_transform() +# +# .. _transforms-fig-scale-dpi: +# +# Plotting in physical coordinates +# ================================ +# +# Sometimes we want an object to be a certain physical size on the plot. +# Here we draw the same circle as above, but in physical coordinates. If done +# interactively, you can see that changing the size of the figure does +# not change the offset of the circle from the lower-left corner, +# does not change its size, and the circle remains a circle regardless of +# the aspect ratio of the axes. + +fig, ax = plt.subplots(figsize=(5, 4)) +x, y = 10*np.random.rand(2, 1000) +ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates +# add a circle in fixed-coordinates +circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, + facecolor='blue', alpha=0.75) +ax.add_patch(circ) +plt.show() + +# %% +# If we change the figure size, the circle does not change its absolute +# position and is cropped. + +fig, ax = plt.subplots(figsize=(7, 2)) +x, y = 10*np.random.rand(2, 1000) +ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates +# add a circle in fixed-coordinates +circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, + facecolor='blue', alpha=0.75) +ax.add_patch(circ) +plt.show() + +# %% +# Another use is putting a patch with a set physical dimension around a +# data point on the axes. Here we add together two transforms. The +# first sets the scaling of how large the ellipse should be and the second +# sets its position. The ellipse is then placed at the origin, and then +# we use the helper transform :class:`~matplotlib.transforms.ScaledTranslation` +# to move it +# to the right place in the ``ax.transData`` coordinate system. +# This helper is instantiated with:: +# +# trans = ScaledTranslation(xt, yt, scale_trans) +# +# where *xt* and *yt* are the translation offsets, and *scale_trans* is +# a transformation which scales *xt* and *yt* at transformation time +# before applying the offsets. +# +# Note the use of the plus operator on the transforms below. +# This code says: first apply the scale transformation ``fig.dpi_scale_trans`` +# to make the ellipse the proper size, but still centered at (0, 0), +# and then translate the data to ``xdata[0]`` and ``ydata[0]`` in data space. +# +# In interactive use, the ellipse stays the same size even if the +# axes limits are changed via zoom. +# + +fig, ax = plt.subplots() +xdata, ydata = (0.2, 0.7), (0.5, 0.5) +ax.plot(xdata, ydata, "o") +ax.set_xlim((0, 1)) + +trans = (fig.dpi_scale_trans + + transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData)) + +# plot an ellipse around the point that is 150 x 130 points in diameter... +circle = mpatches.Ellipse((0, 0), 150/72, 130/72, angle=40, + fill=None, transform=trans) +ax.add_patch(circle) +plt.show() + +# %% +# .. note:: +# +# The order of transformation matters. Here the ellipse +# is given the right dimensions in display space *first* and then moved +# in data space to the correct spot. +# If we had done the ``ScaledTranslation`` first, then +# ``xdata[0]`` and ``ydata[0]`` would +# first be transformed to *display* coordinates (``[ 358.4 475.2]`` on +# a 200-dpi monitor) and then those coordinates +# would be scaled by ``fig.dpi_scale_trans`` pushing the center of +# the ellipse well off the screen (i.e. ``[ 71680. 95040.]``). +# +# .. _offset-transforms-shadow: +# +# Using offset transforms to create a shadow effect +# ================================================= +# +# Another use of :class:`~matplotlib.transforms.ScaledTranslation` is to create +# a new transformation that is +# offset from another transformation, e.g., to place one object shifted a +# bit relative to another object. Typically, you want the shift to be in +# some physical dimension, like points or inches rather than in *data* +# coordinates, so that the shift effect is constant at different zoom +# levels and dpi settings. +# +# One use for an offset is to create a shadow effect, where you draw one +# object identical to the first just to the right of it, and just below +# it, adjusting the zorder to make sure the shadow is drawn first and +# then the object it is shadowing above it. +# +# Here we apply the transforms in the *opposite* order to the use of +# :class:`~matplotlib.transforms.ScaledTranslation` above. The plot is +# first made in data coordinates (``ax.transData``) and then shifted by +# ``dx`` and ``dy`` points using ``fig.dpi_scale_trans``. (In typography, +# a `point `_ is +# 1/72 inches, and by specifying your offsets in points, your figure +# will look the same regardless of the dpi resolution it is saved in.) + +fig, ax = plt.subplots() + +# make a simple sine wave +x = np.arange(0., 2., 0.01) +y = np.sin(2*np.pi*x) +line, = ax.plot(x, y, lw=3, color='blue') + +# shift the object over 2 points, and down 2 points +dx, dy = 2/72., -2/72. +offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) +shadow_transform = ax.transData + offset + +# now plot the same data with our offset transform; +# use the zorder to make sure we are below the line +ax.plot(x, y, lw=3, color='gray', + transform=shadow_transform, + zorder=0.5*line.get_zorder()) + +ax.set_title('creating a shadow effect with an offset transform') +plt.show() + + +# %% +# .. note:: +# +# The dpi and inches offset is a +# common-enough use case that we have a special helper function to +# create it in :func:`matplotlib.transforms.offset_copy`, which returns +# a new transform with an added offset. So above we could have done:: +# +# shadow_transform = transforms.offset_copy(ax.transData, +# fig, dx, dy, units='inches') +# +# +# .. _transformation-pipeline: +# +# The transformation pipeline +# =========================== +# +# The ``ax.transData`` transform we have been working with in this +# tutorial is a composite of three different transformations that +# comprise the transformation pipeline from *data* -> *display* +# coordinates. Michael Droettboom implemented the transformations +# framework, taking care to provide a clean API that segregated the +# nonlinear projections and scales that happen in polar and logarithmic +# plots, from the linear affine transformations that happen when you pan +# and zoom. There is an efficiency here, because you can pan and zoom +# in your axes which affects the affine transformation, but you may not +# need to compute the potentially expensive nonlinear scales or +# projections on simple navigation events. It is also possible to +# multiply affine transformation matrices together, and then apply them +# to coordinates in one step. This is not true of all possible +# transformations. +# +# +# Here is how the ``ax.transData`` instance is defined in the basic +# separable axis :class:`~matplotlib.axes.Axes` class:: +# +# self.transData = self.transScale + (self.transLimits + self.transAxes) +# +# We've been introduced to the ``transAxes`` instance above in +# :ref:`axes-coords`, which maps the (0, 0), (1, 1) corners of the +# axes or subplot bounding box to *display* space, so let's look at +# these other two pieces. +# +# ``self.transLimits`` is the transformation that takes you from +# *data* to *axes* coordinates; i.e., it maps your view xlim and ylim +# to the unit space of the axes (and ``transAxes`` then takes that unit +# space to display space). We can see this in action here +# +# .. sourcecode:: ipython +# +# In [80]: ax = plt.subplot() +# +# In [81]: ax.set_xlim(0, 10) +# Out[81]: (0, 10) +# +# In [82]: ax.set_ylim(-1, 1) +# Out[82]: (-1, 1) +# +# In [84]: ax.transLimits.transform((0, -1)) +# Out[84]: array([ 0., 0.]) +# +# In [85]: ax.transLimits.transform((10, -1)) +# Out[85]: array([ 1., 0.]) +# +# In [86]: ax.transLimits.transform((10, 1)) +# Out[86]: array([ 1., 1.]) +# +# In [87]: ax.transLimits.transform((5, 0)) +# Out[87]: array([ 0.5, 0.5]) +# +# and we can use this same inverted transformation to go from the unit +# *axes* coordinates back to *data* coordinates. +# +# .. sourcecode:: ipython +# +# In [90]: inv.transform((0.25, 0.25)) +# Out[90]: array([ 2.5, -0.5]) +# +# The final piece is the ``self.transScale`` attribute, which is +# responsible for the optional non-linear scaling of the data, e.g., for +# logarithmic axes. When an Axes is initially setup, this is just set to +# the identity transform, since the basic Matplotlib axes has linear +# scale, but when you call a logarithmic scaling function like +# :meth:`~matplotlib.axes.Axes.semilogx` or explicitly set the scale to +# logarithmic with :meth:`~matplotlib.axes.Axes.set_xscale`, then the +# ``ax.transScale`` attribute is set to handle the nonlinear projection. +# The scales transforms are properties of the respective ``xaxis`` and +# ``yaxis`` :class:`~matplotlib.axis.Axis` instances. For example, when +# you call ``ax.set_xscale('log')``, the xaxis updates its scale to a +# :class:`matplotlib.scale.LogScale` instance. +# +# For non-separable axes the PolarAxes, there is one more piece to +# consider, the projection transformation. The ``transData`` +# :class:`matplotlib.projections.polar.PolarAxes` is similar to that for +# the typical separable matplotlib Axes, with one additional piece +# ``transProjection``:: +# +# self.transData = ( +# self.transScale + self.transShift + self.transProjection + +# (self.transProjectionAffine + self.transWedge + self.transAxes)) +# +# ``transProjection`` handles the projection from the space, +# e.g., latitude and longitude for map data, or radius and theta for polar +# data, to a separable Cartesian coordinate system. There are several +# projection examples in the :mod:`matplotlib.projections` package, and the +# best way to learn more is to open the source for those packages and +# see how to make your own, since Matplotlib supports extensible axes +# and projections. Michael Droettboom has provided a nice tutorial +# example of creating a Hammer projection axes; see +# :doc:`/gallery/misc/custom_projection`. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/autoscale.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/autoscale.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d6b728866ce3e511c676d2aa417a1d8222ccf5 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/autoscale.py @@ -0,0 +1,180 @@ +""" +.. redirect-from:: /tutorials/intermediate/autoscale + +.. _autoscale: + +Autoscaling +=========== + +The limits on an axis can be set manually (e.g. ``ax.set_xlim(xmin, xmax)``) +or Matplotlib can set them automatically based on the data already on the axes. +There are a number of options to this autoscaling behaviour, discussed below. +""" + +# %% +# We will start with a simple line plot showing that autoscaling +# extends the axis limits 5% beyond the data limits (-2π, 2π). + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib as mpl + +x = np.linspace(-2 * np.pi, 2 * np.pi, 100) +y = np.sinc(x) + +fig, ax = plt.subplots() +ax.plot(x, y) + +# %% +# Margins +# ------- +# The default margin around the data limits is 5%, which is based on the +# default configuration setting of :rc:`axes.xmargin`, :rc:`axes.ymargin`, +# and :rc:`axes.zmargin`: + +print(ax.margins()) + +# %% +# The margin size can be overridden to make them smaller or larger using +# `~matplotlib.axes.Axes.margins`: + +fig, ax = plt.subplots() +ax.plot(x, y) +ax.margins(0.2, 0.2) + +# %% +# In general, margins can be in the range (-0.5, ∞), where negative margins set +# the axes limits to a subrange of the data range, i.e. they clip data. +# Using a single number for margins affects both axes, a single margin can be +# customized using keyword arguments ``x`` or ``y``, but positional and keyword +# interface cannot be combined. + +fig, ax = plt.subplots() +ax.plot(x, y) +ax.margins(y=-0.2) + +# %% +# Sticky edges +# ------------ +# There are plot elements (`.Artist`\s) that are usually used without margins. +# For example false-color images (e.g. created with `.Axes.imshow`) are not +# considered in the margins calculation. +# + +xx, yy = np.meshgrid(x, x) +zz = np.sinc(np.sqrt((xx - 1)**2 + (yy - 1)**2)) + +fig, ax = plt.subplots(ncols=2, figsize=(12, 8)) +ax[0].imshow(zz) +ax[0].set_title("default margins") +ax[1].imshow(zz) +ax[1].margins(0.2) +ax[1].set_title("margins(0.2)") + +# %% +# This override of margins is determined by "sticky edges", a +# property of `.Artist` class that can suppress adding margins to axis +# limits. The effect of sticky edges can be disabled on an Axes by changing +# `~matplotlib.axes.Axes.use_sticky_edges`. +# Artists have a property `.Artist.sticky_edges`, and the values of +# sticky edges can be changed by writing to ``Artist.sticky_edges.x`` or +# ``Artist.sticky_edges.y``. +# +# The following example shows how overriding works and when it is needed. + +fig, ax = plt.subplots(ncols=3, figsize=(16, 10)) +ax[0].imshow(zz) +ax[0].margins(0.2) +ax[0].set_title("default use_sticky_edges\nmargins(0.2)") +ax[1].imshow(zz) +ax[1].margins(0.2) +ax[1].use_sticky_edges = False +ax[1].set_title("use_sticky_edges=False\nmargins(0.2)") +ax[2].imshow(zz) +ax[2].margins(-0.2) +ax[2].set_title("default use_sticky_edges\nmargins(-0.2)") + +# %% +# We can see that setting ``use_sticky_edges`` to *False* renders the image +# with requested margins. +# +# While sticky edges don't increase the axis limits through extra margins, +# negative margins are still taken into account. This can be seen in +# the reduced limits of the third image. +# +# Controlling autoscale +# --------------------- +# +# By default, the limits are +# recalculated every time you add a new curve to the plot: + +fig, ax = plt.subplots(ncols=2, figsize=(12, 8)) +ax[0].plot(x, y) +ax[0].set_title("Single curve") +ax[1].plot(x, y) +ax[1].plot(x * 2.0, y) +ax[1].set_title("Two curves") + +# %% +# However, there are cases when you don't want to automatically adjust the +# viewport to new data. +# +# One way to disable autoscaling is to manually set the +# axis limit. Let's say that we want to see only a part of the data in +# greater detail. Setting the ``xlim`` persists even if we add more curves to +# the data. To recalculate the new limits calling `.Axes.autoscale` will +# toggle the functionality manually. + +fig, ax = plt.subplots(ncols=2, figsize=(12, 8)) +ax[0].plot(x, y) +ax[0].set_xlim(left=-1, right=1) +ax[0].plot(x + np.pi * 0.5, y) +ax[0].set_title("set_xlim(left=-1, right=1)\n") +ax[1].plot(x, y) +ax[1].set_xlim(left=-1, right=1) +ax[1].plot(x + np.pi * 0.5, y) +ax[1].autoscale() +ax[1].set_title("set_xlim(left=-1, right=1)\nautoscale()") + +# %% +# We can check that the first plot has autoscale disabled and that the second +# plot has it enabled again by using `.Axes.get_autoscale_on()`: + +print(ax[0].get_autoscale_on()) # False means disabled +print(ax[1].get_autoscale_on()) # True means enabled -> recalculated + +# %% +# Arguments of the autoscale function give us precise control over the process +# of autoscaling. A combination of arguments ``enable``, and ``axis`` sets the +# autoscaling feature for the selected axis (or both). The argument ``tight`` +# sets the margin of the selected axis to zero. To preserve settings of either +# ``enable`` or ``tight`` you can set the opposite one to *None*, that way +# it should not be modified. However, setting ``enable`` to *None* and tight +# to *True* affects both axes regardless of the ``axis`` argument. + +fig, ax = plt.subplots() +ax.plot(x, y) +ax.margins(0.2, 0.2) +ax.autoscale(enable=None, axis="x", tight=True) + +print(ax.margins()) + +# %% +# Working with collections +# ------------------------ +# +# Autoscale works out of the box for all lines, patches, and images added to +# the axes. One of the artists that it won't work with is a `.Collection`. +# After adding a collection to the axes, one has to manually trigger the +# `~matplotlib.axes.Axes.autoscale_view()` to recalculate +# axes limits. + +fig, ax = plt.subplots() +collection = mpl.collections.StarPolygonCollection( + 5, rotation=0, sizes=(250,), # five point star, zero angle, size 250px + offsets=np.column_stack([x, y]), # Set the positions + offset_transform=ax.transData, # Propagate transformations of the Axes +) +ax.add_collection(collection) +ax.autoscale_view() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_intro.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..948dd51c8b1e0f778ec2c63d0768ebdbbc87c672 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_intro.rst @@ -0,0 +1,180 @@ +################################## +Introduction to Axes (or Subplots) +################################## + + +Matplotlib `~.axes.Axes` are the gateway to creating your data visualizations. +Once an Axes is placed on a figure there are many methods that can be used to +add data to the Axes. An Axes typically has a pair of `~.axis.Axis` +Artists that define the data coordinate system, and include methods to add +annotations like x- and y-labels, titles, and legends. + +.. _anatomy_local: + +.. figure:: /_static/anatomy.png + :width: 80% + + Anatomy of a Figure + +In the picture above, the Axes object was created with ``ax = fig.subplots()``. +Everything else on the figure was created with methods on this ``ax`` object, +or can be accessed from it. If we want to change the label on the x-axis, we +call ``ax.set_xlabel('New Label')``, if we want to plot some data we call +``ax.plot(x, y)``. Indeed, in the figure above, the only Artist that is not +part of the Axes is the Figure itself, so the `.axes.Axes` class is really the +gateway to much of Matplotlib's functionality. + +Note that Axes are so fundamental to the operation of Matplotlib that a lot of +material here is duplicate of that in :ref:`quick_start`. + +Creating Axes +------------- + +.. plot:: + :include-source: + + import matplotlib.pyplot as plt + import numpy as np + + fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(3.5, 2.5), + layout="constrained") + # for each Axes, add an artist, in this case a nice label in the middle... + for row in range(2): + for col in range(2): + axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5), + transform=axs[row, col].transAxes, + ha='center', va='center', fontsize=18, + color='darkgrey') + fig.suptitle('plt.subplots()') + + +Axes are added using methods on `~.Figure` objects, or via the `~.pyplot` interface. These methods are discussed in more detail in :ref:`creating_figures` and :doc:`arranging_axes`. However, for instance `~.Figure.add_axes` will manually position an Axes on the page. In the example above `~.pyplot.subplots` put a grid of subplots on the figure, and ``axs`` is a (2, 2) array of Axes, each of which can have data added to them. + +There are a number of other methods for adding Axes to a Figure: + +* `.Figure.add_axes`: manually position an Axes. ``fig.add_axes([0, 0, 1, + 1])`` makes an Axes that fills the whole figure. +* `.pyplot.subplots` and `.Figure.subplots`: add a grid of Axes as in the example + above. The pyplot version returns both the Figure object and an array of + Axes. Note that ``fig, ax = plt.subplots()`` adds a single Axes to a Figure. +* `.pyplot.subplot_mosaic` and `.Figure.subplot_mosaic`: add a grid of named + Axes and return a dictionary of axes. For ``fig, axs = + plt.subplot_mosaic([['left', 'right'], ['bottom', 'bottom']])``, + ``axs['left']`` is an Axes in the top row on the left, and ``axs['bottom']`` + is an Axes that spans both columns on the bottom. + +See :doc:`arranging_axes` for more detail on how to arrange grids of Axes on a +Figure. + + +Axes plotting methods +--------------------- + +Most of the high-level plotting methods are accessed from the `.axes.Axes` +class. See the API documentation for a full curated list, and +:ref:`plot_types` for examples. A basic example is `.axes.Axes.plot`: + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(4, 3)) + np.random.seed(19680801) + t = np.arange(100) + x = np.cumsum(np.random.randn(100)) + lines = ax.plot(t, x) + +Note that ``plot`` returns a list of *lines* Artists which can subsequently be +manipulated, as discussed in :ref:`users_artists`. + +A very incomplete list of plotting methods is below. Again, see :ref:`plot_types` +for more examples, and `.axes.Axes` for the full list of methods. + +========================= ================================================== +:ref:`basic_plots` `~.axes.Axes.plot`, `~.axes.Axes.scatter`, + `~.axes.Axes.bar`, `~.axes.Axes.step`, +:ref:`arrays` `~.axes.Axes.pcolormesh`, `~.axes.Axes.contour`, + `~.axes.Axes.quiver`, `~.axes.Axes.streamplot`, + `~.axes.Axes.imshow` +:ref:`stats_plots` `~.axes.Axes.hist`, `~.axes.Axes.errorbar`, + `~.axes.Axes.hist2d`, `~.axes.Axes.pie`, + `~.axes.Axes.boxplot`, `~.axes.Axes.violinplot` +:ref:`unstructured_plots` `~.axes.Axes.tricontour`, `~.axes.Axes.tripcolor` +========================= ================================================== + +Axes labelling and annotation +----------------------------- + +Usually we want to label the Axes with an xlabel, ylabel, and title, and often we want to have a legend to differentiate plot elements. The `~.axes.Axes` class has a number of methods to create these annotations. + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(5, 3), layout='constrained') + np.random.seed(19680801) + t = np.arange(200) + x = np.cumsum(np.random.randn(200)) + y = np.cumsum(np.random.randn(200)) + linesx = ax.plot(t, x, label='Random walk x') + linesy = ax.plot(t, y, label='Random walk y') + + ax.set_xlabel('Time [s]') + ax.set_ylabel('Distance [km]') + ax.set_title('Random walk example') + ax.legend() + +These methods are relatively straight-forward, though there are a number of :ref:`text_props` that can be set on the text objects, like *fontsize*, *fontname*, *horizontalalignment*. Legends can be much more complicated; see :ref:`legend_guide` for more details. + +Note that text can also be added to axes using `~.axes.Axes.text`, and `~.axes.Axes.annotate`. This can be quite sophisticated: see :ref:`text_props` and :ref:`annotations` for more information. + + +Axes limits, scales, and ticking +-------------------------------- + +Each Axes has two (or more) `~.axis.Axis` objects, that can be accessed via :attr:`~matplotlib.axes.Axes.xaxis` and :attr:`~matplotlib.axes.Axes.yaxis` properties. These have substantial number of methods on them, and for highly customizable Axis-es it is useful to read the API at `~.axis.Axis`. However, the Axes class offers a number of helpers for the most common of these methods. Indeed, the `~.axes.Axes.set_xlabel`, discussed above, is a helper for the `~.Axis.set_label_text`. + +Other important methods set the extent on the axes (`~.axes.Axes.set_xlim`, `~.axes.Axes.set_ylim`), or more fundamentally the scale of the axes. So for instance, we can make an Axis have a logarithmic scale, and zoom in on a sub-portion of the data: + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(4, 2.5), layout='constrained') + np.random.seed(19680801) + t = np.arange(200) + x = 2**np.cumsum(np.random.randn(200)) + linesx = ax.plot(t, x) + ax.set_yscale('log') + ax.set_xlim([20, 180]) + +The Axes class also has helpers to deal with Axis ticks and their labels. Most straight-forward is `~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks` which manually set the tick locations and optionally their labels. Minor ticks can be toggled with `~.axes.Axes.minorticks_on` or `~.axes.Axes.minorticks_off`. + +Many aspects of Axes ticks and tick labeling can be adjusted using `~.axes.Axes.tick_params`. For instance, to label the top of the axes instead of the bottom,color the ticks red, and color the ticklabels green: + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(4, 2.5)) + ax.plot(np.arange(10)) + ax.tick_params(top=True, labeltop=True, color='red', axis='x', + labelcolor='green') + + +More fine-grained control on ticks, setting scales, and controlling the Axis can be highly customized beyond these Axes-level helpers. + +Axes layout +----------- + +Sometimes it is important to set the aspect ratio of a plot in data space, which we can do with `~.axes.Axes.set_aspect`: + +.. plot:: + :include-source: + + fig, axs = plt.subplots(ncols=2, figsize=(7, 2.5), layout='constrained') + np.random.seed(19680801) + t = np.arange(200) + x = np.cumsum(np.random.randn(200)) + axs[0].plot(t, x) + axs[0].set_title('aspect="auto"') + + axs[1].plot(t, x) + axs[1].set_aspect(3) + axs[1].set_title('aspect=3') diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_ticks.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_ticks.py new file mode 100644 index 0000000000000000000000000000000000000000..aaec87c6a239321dbf0c746bfe920134fbf67cff --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_ticks.py @@ -0,0 +1,275 @@ +""" +.. _user_axes_ticks: + +========== +Axis Ticks +========== + +The x and y Axis on each Axes have default tick "locators" and "formatters" +that depend on the scale being used (see :ref:`user_axes_scales`). It is +possible to customize the ticks and tick labels with either high-level methods +like `~.axes.Axes.set_xticks` or set the locators and formatters directly on +the axis. + +Manual location and formats +=========================== + +The simplest method to customize the tick locations and formats is to use +`~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks`. These can be used on +either the major or the minor ticks. +""" +import numpy as np +import matplotlib.pyplot as plt + +import matplotlib.ticker as ticker + + +fig, axs = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained') +x = np.arange(100) +for nn, ax in enumerate(axs): + ax.plot(x, x) + if nn == 1: + ax.set_title('Manual ticks') + ax.set_yticks(np.arange(0, 100.1, 100/3)) + xticks = np.arange(0.50, 101, 20) + xlabels = [f'\\${x:1.2f}' for x in xticks] + ax.set_xticks(xticks, labels=xlabels) + else: + ax.set_title('Automatic ticks') + +# %% +# +# Note that the length of the ``labels`` argument must have the same length as +# the array used to specify the ticks. +# +# By default `~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks` act on the +# major ticks of an Axis, however it is possible to add minor ticks: + +fig, axs = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained') +x = np.arange(100) +for nn, ax in enumerate(axs): + ax.plot(x, x) + if nn == 1: + ax.set_title('Manual ticks') + ax.set_yticks(np.arange(0, 100.1, 100/3)) + ax.set_yticks(np.arange(0, 100.1, 100/30), minor=True) + else: + ax.set_title('Automatic ticks') + + +# %% +# +# Locators and Formatters +# ======================= +# +# Manually setting the ticks as above works well for specific final plots, but +# does not adapt as the user interacts with the axes. At a lower level, +# Matplotlib has ``Locators`` that are meant to automatically choose ticks +# depending on the current view limits of the axis, and ``Formatters`` that are +# meant to format the tick labels automatically. +# +# The full list of locators provided by Matplotlib are listed at +# :ref:`locators`, and the formatters at :ref:`formatters`. + + +# %% + +def setup(ax, title): + """Set up common parameters for the Axes in the example.""" + # only show the bottom spine + ax.yaxis.set_major_locator(ticker.NullLocator()) + ax.spines[['left', 'right', 'top']].set_visible(False) + + ax.xaxis.set_ticks_position('bottom') + ax.tick_params(which='major', width=1.00, length=5) + ax.tick_params(which='minor', width=0.75, length=2.5) + ax.set_xlim(0, 5) + ax.set_ylim(0, 1) + ax.text(0.0, 0.2, title, transform=ax.transAxes, + fontsize=14, fontname='Monospace', color='tab:blue') + + +fig, axs = plt.subplots(8, 1, layout='constrained') + +# Null Locator +setup(axs[0], title="NullLocator()") +axs[0].xaxis.set_major_locator(ticker.NullLocator()) +axs[0].xaxis.set_minor_locator(ticker.NullLocator()) + +# Multiple Locator +setup(axs[1], title="MultipleLocator(0.5)") +axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5)) +axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) + +# Fixed Locator +setup(axs[2], title="FixedLocator([0, 1, 5])") +axs[2].xaxis.set_major_locator(ticker.FixedLocator([0, 1, 5])) +axs[2].xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) + +# Linear Locator +setup(axs[3], title="LinearLocator(numticks=3)") +axs[3].xaxis.set_major_locator(ticker.LinearLocator(3)) +axs[3].xaxis.set_minor_locator(ticker.LinearLocator(31)) + +# Index Locator +setup(axs[4], title="IndexLocator(base=0.5, offset=0.25)") +axs[4].plot(range(0, 5), [0]*5, color='white') +axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) + +# Auto Locator +setup(axs[5], title="AutoLocator()") +axs[5].xaxis.set_major_locator(ticker.AutoLocator()) +axs[5].xaxis.set_minor_locator(ticker.AutoMinorLocator()) + +# MaxN Locator +setup(axs[6], title="MaxNLocator(n=4)") +axs[6].xaxis.set_major_locator(ticker.MaxNLocator(4)) +axs[6].xaxis.set_minor_locator(ticker.MaxNLocator(40)) + +# Log Locator +setup(axs[7], title="LogLocator(base=10, numticks=15)") +axs[7].set_xlim(10**3, 10**10) +axs[7].set_xscale('log') +axs[7].xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) +plt.show() + +# %% +# +# Similarly, we can specify "Formatters" for the major and minor ticks on each +# axis. +# +# The tick format is configured via the function `~.Axis.set_major_formatter` +# or `~.Axis.set_minor_formatter`. It accepts: +# +# - a format string, which implicitly creates a `.StrMethodFormatter`. +# - a function, implicitly creates a `.FuncFormatter`. +# - an instance of a `.Formatter` subclass. The most common are +# +# - `.NullFormatter`: No labels on the ticks. +# - `.StrMethodFormatter`: Use string `str.format` method. +# - `.FormatStrFormatter`: Use %-style formatting. +# - `.FuncFormatter`: Define labels through a function. +# - `.FixedFormatter`: Set the label strings explicitly. +# - `.ScalarFormatter`: Default formatter for scalars: auto-pick the format string. +# - `.PercentFormatter`: Format labels as a percentage. +# +# See :ref:`formatters` for the complete list. + + +def setup(ax, title): + """Set up common parameters for the Axes in the example.""" + # only show the bottom spine + ax.yaxis.set_major_locator(ticker.NullLocator()) + ax.spines[['left', 'right', 'top']].set_visible(False) + + # define tick positions + ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00)) + ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25)) + + ax.xaxis.set_ticks_position('bottom') + ax.tick_params(which='major', width=1.00, length=5) + ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10) + ax.set_xlim(0, 5) + ax.set_ylim(0, 1) + ax.text(0.0, 0.2, title, transform=ax.transAxes, + fontsize=14, fontname='Monospace', color='tab:blue') + + +fig = plt.figure(figsize=(8, 8), layout='constrained') +fig0, fig1, fig2 = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5]) + +fig0.suptitle('String Formatting', fontsize=16, x=0, ha='left') +ax0 = fig0.subplots() + +setup(ax0, title="'{x} km'") +ax0.xaxis.set_major_formatter('{x} km') + +fig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left') +ax1 = fig1.subplots() + +setup(ax1, title="def(x, pos): return str(x-5)") +ax1.xaxis.set_major_formatter(lambda x, pos: str(x-5)) + +fig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left') +axs2 = fig2.subplots(7, 1) + +setup(axs2[0], title="NullFormatter()") +axs2[0].xaxis.set_major_formatter(ticker.NullFormatter()) + +setup(axs2[1], title="StrMethodFormatter('{x:.3f}')") +axs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}")) + +setup(axs2[2], title="FormatStrFormatter('#%d')") +axs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d")) + + +def fmt_two_digits(x, pos): + return f'[{x:.2f}]' + + +setup(axs2[3], title='FuncFormatter("[{:.2f}]".format)') +axs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits)) + +setup(axs2[4], title="FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])") +# FixedFormatter should only be used together with FixedLocator. +# Otherwise, one cannot be sure where the labels will end up. +positions = [0, 1, 2, 3, 4, 5] +labels = ['A', 'B', 'C', 'D', 'E', 'F'] +axs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions)) +axs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels)) + +setup(axs2[5], title="ScalarFormatter()") +axs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) + +setup(axs2[6], title="PercentFormatter(xmax=5)") +axs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5)) + + +# %% +# +# Styling ticks (tick parameters) +# =============================== +# +# The appearance of ticks can be controlled at a low level by finding the +# individual `~.axis.Tick` on the axis. However, usually it is simplest to +# use `~.axes.Axes.tick_params` to change all the objects at once. +# +# The ``tick_params`` method can change the properties of ticks: +# +# - length +# - direction (in or out of the frame) +# - colors +# - width and length +# - and whether the ticks are drawn at the bottom, top, left, or right of the +# Axes. +# +# It also can control the tick labels: +# +# - labelsize (fontsize) +# - labelcolor (color of the label) +# - labelrotation +# - labelbottom, labeltop, labelleft, labelright +# +# In addition there is a *pad* keyword argument that specifies how far the tick +# label is from the tick. +# +# Finally, the grid linestyles can be set: +# +# - grid_color +# - grid_alpha +# - grid_linewidth +# - grid_linestyle +# +# All these properties can be restricted to one axis, and can be applied to +# just the major or minor ticks + +fig, axs = plt.subplots(1, 2, figsize=(6.4, 3.2), layout='constrained') + +for nn, ax in enumerate(axs): + ax.plot(np.arange(100)) + if nn == 1: + ax.grid('on') + ax.tick_params(right=True, left=False, axis='y', color='r', length=16, + grid_color='none') + ax.tick_params(axis='x', color='m', length=4, direction='in', width=4, + labelcolor='g', grid_color='b') diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/colorbar_placement.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/colorbar_placement.py new file mode 100644 index 0000000000000000000000000000000000000000..de767a4fa130e175f3ffe7a7f8bc300a225da116 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/colorbar_placement.py @@ -0,0 +1,99 @@ +""" +.. _colorbar_placement: + +.. redirect-from:: /gallery/subplots_axes_and_figures/colorbar_placement + +================= +Placing Colorbars +================= + +Colorbars indicate the quantitative extent of image data. Placing in +a figure is non-trivial because room needs to be made for them. + +The simplest case is just attaching a colorbar to each axes: +""" +import matplotlib.pyplot as plt +import numpy as np + +# Fixing random state for reproducibility +np.random.seed(19680801) + +fig, axs = plt.subplots(2, 2) +cmaps = ['RdBu_r', 'viridis'] +for col in range(2): + for row in range(2): + ax = axs[row, col] + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), + cmap=cmaps[col]) + fig.colorbar(pcm, ax=ax) + +# %% +# The first column has the same type of data in both rows, so it may +# be desirable to combine the colorbar which we do by calling +# `.Figure.colorbar` with a list of axes instead of a single axes. + +fig, axs = plt.subplots(2, 2) +cmaps = ['RdBu_r', 'viridis'] +for col in range(2): + for row in range(2): + ax = axs[row, col] + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), + cmap=cmaps[col]) + fig.colorbar(pcm, ax=axs[:, col], shrink=0.6) + +# %% +# Relatively complicated colorbar layouts are possible using this +# paradigm. Note that this example works far better with +# ``layout='constrained'`` + +fig, axs = plt.subplots(3, 3, layout='constrained') +for ax in axs.flat: + pcm = ax.pcolormesh(np.random.random((20, 20))) + +fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom') +fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom') +fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) +fig.colorbar(pcm, ax=[axs[2, 1]], location='left') + +# %% +# Colorbars with fixed-aspect-ratio axes +# ====================================== +# +# Placing colorbars for axes with a fixed aspect ratio pose a particular +# challenge as the parent axes changes size depending on the data view. + +fig, axs = plt.subplots(2, 2, layout='constrained') +cmaps = ['RdBu_r', 'viridis'] +for col in range(2): + for row in range(2): + ax = axs[row, col] + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), + cmap=cmaps[col]) + if col == 0: + ax.set_aspect(2) + else: + ax.set_aspect(1/2) + if row == 1: + fig.colorbar(pcm, ax=ax, shrink=0.6) + +# %% +# One way around this issue is to use an `.Axes.inset_axes` to locate the +# axes in axes coordinates. Note that if you zoom in on the axes, and +# change the shape of the axes, the colorbar will also change position. + +fig, axs = plt.subplots(2, 2, layout='constrained') +cmaps = ['RdBu_r', 'viridis'] +for col in range(2): + for row in range(2): + ax = axs[row, col] + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), + cmap=cmaps[col]) + if col == 0: + ax.set_aspect(2) + else: + ax.set_aspect(1/2) + if row == 1: + cax = ax.inset_axes([1.04, 0.2, 0.05, 0.6]) + fig.colorbar(pcm, ax=ax, cax=cax) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/constrainedlayout_guide.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/constrainedlayout_guide.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2752674c6affea173fe6667b694dbe213fb379 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/constrainedlayout_guide.py @@ -0,0 +1,734 @@ +""" + +.. redirect-from:: /tutorials/intermediate/constrainedlayout_guide + +.. _constrainedlayout_guide: + +================================ +Constrained Layout Guide +================================ + +Use *constrained layout* to fit plots within your figure cleanly. + +*Constrained layout* automatically adjusts subplots so that decorations like tick +labels, legends, and colorbars do not overlap, while still preserving the +logical layout requested by the user. + +*Constrained layout* is similar to :ref:`Tight +layout`, but is substantially more +flexible. It handles colorbars placed on multiple Axes +(:ref:`colorbar_placement`) nested layouts (`~.Figure.subfigures`) and Axes that +span rows or columns (`~.pyplot.subplot_mosaic`), striving to align spines from +Axes in the same row or column. In addition, :ref:`Compressed layout +` will try and move fixed aspect-ratio Axes closer together. +These features are described in this document, as well as some +:ref:`implementation details ` discussed at the end. + +*Constrained layout* typically needs to be activated before any Axes are added to +a figure. Two ways of doing so are + +* using the respective argument to `~.pyplot.subplots`, + `~.pyplot.figure`, `~.pyplot.subplot_mosaic` e.g.:: + + plt.subplots(layout="constrained") + +* activate it via :ref:`rcParams`, like:: + + plt.rcParams['figure.constrained_layout.use'] = True + +Those are described in detail throughout the following sections. + +.. warning:: + + Calling ``plt.tight_layout()`` will turn off *constrained layout*! + +Simple example +============== + +In Matplotlib, the location of Axes (including subplots) are specified in +normalized figure coordinates. It can happen that your axis labels or titles +(or sometimes even ticklabels) go outside the figure area, and are thus +clipped. +""" + +# sphinx_gallery_thumbnail_number = 18 + + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib.colors as mcolors +import matplotlib.gridspec as gridspec + +plt.rcParams['savefig.facecolor'] = "0.8" +plt.rcParams['figure.figsize'] = 4.5, 4. +plt.rcParams['figure.max_open_warning'] = 50 + + +def example_plot(ax, fontsize=12, hide_labels=False): + ax.plot([1, 2]) + + ax.locator_params(nbins=3) + if hide_labels: + ax.set_xticklabels([]) + ax.set_yticklabels([]) + else: + ax.set_xlabel('x-label', fontsize=fontsize) + ax.set_ylabel('y-label', fontsize=fontsize) + ax.set_title('Title', fontsize=fontsize) + +fig, ax = plt.subplots(layout=None) +example_plot(ax, fontsize=24) + +# %% +# To prevent this, the location of Axes needs to be adjusted. For +# subplots, this can be done manually by adjusting the subplot parameters +# using `.Figure.subplots_adjust`. However, specifying your figure with the +# ``layout="constrained"`` keyword argument will do the adjusting +# automatically. + +fig, ax = plt.subplots(layout="constrained") +example_plot(ax, fontsize=24) + +# %% +# When you have multiple subplots, often you see labels of different +# Axes overlapping each other. + +fig, axs = plt.subplots(2, 2, layout=None) +for ax in axs.flat: + example_plot(ax) + +# %% +# Specifying ``layout="constrained"`` in the call to ``plt.subplots`` +# causes the layout to be properly constrained. + +fig, axs = plt.subplots(2, 2, layout="constrained") +for ax in axs.flat: + example_plot(ax) + +# %% +# +# Colorbars +# ========= +# +# If you create a colorbar with `.Figure.colorbar`, you need to make room for +# it. *Constrained layout* does this automatically. Note that if you +# specify ``use_gridspec=True`` it will be ignored because this option is made +# for improving the layout via ``tight_layout``. +# +# .. note:: +# +# For the `~.axes.Axes.pcolormesh` keyword arguments (``pc_kwargs``) we use a +# dictionary to keep the calls consistent across this document. + +arr = np.arange(100).reshape((10, 10)) +norm = mcolors.Normalize(vmin=0., vmax=100.) +# see note above: this makes all pcolormesh calls consistent: +pc_kwargs = {'rasterized': True, 'cmap': 'viridis', 'norm': norm} +fig, ax = plt.subplots(figsize=(4, 4), layout="constrained") +im = ax.pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=ax, shrink=0.6) + +# %% +# If you specify a list of Axes (or other iterable container) to the +# ``ax`` argument of ``colorbar``, *constrained layout* will take space from +# the specified Axes. + +fig, axs = plt.subplots(2, 2, figsize=(4, 4), layout="constrained") +for ax in axs.flat: + im = ax.pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=axs, shrink=0.6) + +# %% +# If you specify a list of Axes from inside a grid of Axes, the colorbar +# will steal space appropriately, and leave a gap, but all subplots will +# still be the same size. + +fig, axs = plt.subplots(3, 3, figsize=(4, 4), layout="constrained") +for ax in axs.flat: + im = ax.pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=axs[1:, 1], shrink=0.8) +fig.colorbar(im, ax=axs[:, -1], shrink=0.6) + +# %% +# Suptitle +# ========= +# +# *Constrained layout* can also make room for `~.Figure.suptitle`. + +fig, axs = plt.subplots(2, 2, figsize=(4, 4), layout="constrained") +for ax in axs.flat: + im = ax.pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=axs, shrink=0.6) +fig.suptitle('Big Suptitle') + +# %% +# Legends +# ======= +# +# Legends can be placed outside of their parent axis. +# *Constrained layout* is designed to handle this for :meth:`.Axes.legend`. +# However, *constrained layout* does *not* handle legends being created via +# :meth:`.Figure.legend` (yet). + +fig, ax = plt.subplots(layout="constrained") +ax.plot(np.arange(10), label='This is a plot') +ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) + +# %% +# However, this will steal space from a subplot layout: + +fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained") +axs[0].plot(np.arange(10)) +axs[1].plot(np.arange(10), label='This is a plot') +axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) + +# %% +# In order for a legend or other artist to *not* steal space +# from the subplot layout, we can ``leg.set_in_layout(False)``. +# Of course this can mean the legend ends up +# cropped, but can be useful if the plot is subsequently called +# with ``fig.savefig('outname.png', bbox_inches='tight')``. Note, +# however, that the legend's ``get_in_layout`` status will have to be +# toggled again to make the saved file work, and we must manually +# trigger a draw if we want *constrained layout* to adjust the size +# of the Axes before printing. + +fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained") + +axs[0].plot(np.arange(10)) +axs[1].plot(np.arange(10), label='This is a plot') +leg = axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) +leg.set_in_layout(False) +# trigger a draw so that constrained layout is executed once +# before we turn it off when printing.... +fig.canvas.draw() +# we want the legend included in the bbox_inches='tight' calcs. +leg.set_in_layout(True) +# we don't want the layout to change at this point. +fig.set_layout_engine('none') +try: + fig.savefig('../../../doc/_static/constrained_layout_1b.png', + bbox_inches='tight', dpi=100) +except FileNotFoundError: + # this allows the script to keep going if run interactively and + # the directory above doesn't exist + pass + +# %% +# The saved file looks like: +# +# .. image:: /_static/constrained_layout_1b.png +# :align: center +# +# A better way to get around this awkwardness is to simply +# use the legend method provided by `.Figure.legend`: +fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained") +axs[0].plot(np.arange(10)) +lines = axs[1].plot(np.arange(10), label='This is a plot') +labels = [l.get_label() for l in lines] +leg = fig.legend(lines, labels, loc='center left', + bbox_to_anchor=(0.8, 0.5), bbox_transform=axs[1].transAxes) +try: + fig.savefig('../../../doc/_static/constrained_layout_2b.png', + bbox_inches='tight', dpi=100) +except FileNotFoundError: + # this allows the script to keep going if run interactively and + # the directory above doesn't exist + pass + + +# %% +# The saved file looks like: +# +# .. image:: /_static/constrained_layout_2b.png +# :align: center +# + +# %% +# Padding and spacing +# =================== +# +# Padding between Axes is controlled in the horizontal by *w_pad* and +# *wspace*, and vertical by *h_pad* and *hspace*. These can be edited +# via `~.layout_engine.ConstrainedLayoutEngine.set`. *w/h_pad* are +# the minimum space around the Axes in units of inches: + +fig, axs = plt.subplots(2, 2, layout="constrained") +for ax in axs.flat: + example_plot(ax, hide_labels=True) +fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0, + wspace=0) + +# %% +# Spacing between subplots is further set by *wspace* and *hspace*. These +# are specified as a fraction of the size of the subplot group as a whole. +# If these values are smaller than *w_pad* or *h_pad*, then the fixed pads are +# used instead. Note in the below how the space at the edges doesn't change +# from the above, but the space between subplots does. + +fig, axs = plt.subplots(2, 2, layout="constrained") +for ax in axs.flat: + example_plot(ax, hide_labels=True) +fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, + wspace=0.2) + +# %% +# If there are more than two columns, the *wspace* is shared between them, +# so here the wspace is divided in two, with a *wspace* of 0.1 between each +# column: + +fig, axs = plt.subplots(2, 3, layout="constrained") +for ax in axs.flat: + example_plot(ax, hide_labels=True) +fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, + wspace=0.2) + +# %% +# GridSpecs also have optional *hspace* and *wspace* keyword arguments, +# that will be used instead of the pads set by *constrained layout*: + +fig, axs = plt.subplots(2, 2, layout="constrained", + gridspec_kw={'wspace': 0.3, 'hspace': 0.2}) +for ax in axs.flat: + example_plot(ax, hide_labels=True) +# this has no effect because the space set in the gridspec trumps the +# space set in *constrained layout*. +fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.0, + wspace=0.0) + +# %% +# Spacing with colorbars +# ----------------------- +# +# Colorbars are placed a distance *pad* from their parent, where *pad* +# is a fraction of the width of the parent(s). The spacing to the +# next subplot is then given by *w/hspace*. + +fig, axs = plt.subplots(2, 2, layout="constrained") +pads = [0, 0.05, 0.1, 0.2] +for pad, ax in zip(pads, axs.flat): + pc = ax.pcolormesh(arr, **pc_kwargs) + fig.colorbar(pc, ax=ax, shrink=0.6, pad=pad) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + ax.set_title(f'pad: {pad}') +fig.get_layout_engine().set(w_pad=2 / 72, h_pad=2 / 72, hspace=0.2, + wspace=0.2) + +# %% +# rcParams +# ======== +# +# There are five :ref:`rcParams` +# that can be set, either in a script or in the :file:`matplotlibrc` +# file. They all have the prefix ``figure.constrained_layout``: +# +# - *use*: Whether to use *constrained layout*. Default is False +# - *w_pad*, *h_pad*: Padding around Axes objects. +# Float representing inches. Default is 3./72. inches (3 pts) +# - *wspace*, *hspace*: Space between subplot groups. +# Float representing a fraction of the subplot widths being separated. +# Default is 0.02. + +plt.rcParams['figure.constrained_layout.use'] = True +fig, axs = plt.subplots(2, 2, figsize=(3, 3)) +for ax in axs.flat: + example_plot(ax) + +# %% +# Use with GridSpec +# ================= +# +# *Constrained layout* is meant to be used +# with :func:`~matplotlib.figure.Figure.subplots`, +# :func:`~matplotlib.figure.Figure.subplot_mosaic`, or +# :func:`~matplotlib.gridspec.GridSpec` with +# :func:`~matplotlib.figure.Figure.add_subplot`. +# +# Note that in what follows ``layout="constrained"`` + +plt.rcParams['figure.constrained_layout.use'] = False +fig = plt.figure(layout="constrained") + +gs1 = gridspec.GridSpec(2, 1, figure=fig) +ax1 = fig.add_subplot(gs1[0]) +ax2 = fig.add_subplot(gs1[1]) + +example_plot(ax1) +example_plot(ax2) + +# %% +# More complicated gridspec layouts are possible. Note here we use the +# convenience functions `~.Figure.add_gridspec` and +# `~.SubplotSpec.subgridspec`. + +fig = plt.figure(layout="constrained") + +gs0 = fig.add_gridspec(1, 2) + +gs1 = gs0[0].subgridspec(2, 1) +ax1 = fig.add_subplot(gs1[0]) +ax2 = fig.add_subplot(gs1[1]) + +example_plot(ax1) +example_plot(ax2) + +gs2 = gs0[1].subgridspec(3, 1) + +for ss in gs2: + ax = fig.add_subplot(ss) + example_plot(ax) + ax.set_title("") + ax.set_xlabel("") + +ax.set_xlabel("x-label", fontsize=12) + +# %% +# Note that in the above the left and right columns don't have the same +# vertical extent. If we want the top and bottom of the two grids to line up +# then they need to be in the same gridspec. We need to make this figure +# larger as well in order for the Axes not to collapse to zero height: + +fig = plt.figure(figsize=(4, 6), layout="constrained") + +gs0 = fig.add_gridspec(6, 2) + +ax1 = fig.add_subplot(gs0[:3, 0]) +ax2 = fig.add_subplot(gs0[3:, 0]) + +example_plot(ax1) +example_plot(ax2) + +ax = fig.add_subplot(gs0[0:2, 1]) +example_plot(ax, hide_labels=True) +ax = fig.add_subplot(gs0[2:4, 1]) +example_plot(ax, hide_labels=True) +ax = fig.add_subplot(gs0[4:, 1]) +example_plot(ax, hide_labels=True) +fig.suptitle('Overlapping Gridspecs') + +# %% +# This example uses two gridspecs to have the colorbar only pertain to +# one set of pcolors. Note how the left column is wider than the +# two right-hand columns because of this. Of course, if you wanted the +# subplots to be the same size you only needed one gridspec. Note that +# the same effect can be achieved using `~.Figure.subfigures`. + +fig = plt.figure(layout="constrained") +gs0 = fig.add_gridspec(1, 2, figure=fig, width_ratios=[1, 2]) +gs_left = gs0[0].subgridspec(2, 1) +gs_right = gs0[1].subgridspec(2, 2) + +for gs in gs_left: + ax = fig.add_subplot(gs) + example_plot(ax) +axs = [] +for gs in gs_right: + ax = fig.add_subplot(gs) + pcm = ax.pcolormesh(arr, **pc_kwargs) + ax.set_xlabel('x-label') + ax.set_ylabel('y-label') + ax.set_title('title') + axs += [ax] +fig.suptitle('Nested plots using subgridspec') +fig.colorbar(pcm, ax=axs) + +# %% +# Rather than using subgridspecs, Matplotlib now provides `~.Figure.subfigures` +# which also work with *constrained layout*: + +fig = plt.figure(layout="constrained") +sfigs = fig.subfigures(1, 2, width_ratios=[1, 2]) + +axs_left = sfigs[0].subplots(2, 1) +for ax in axs_left.flat: + example_plot(ax) + +axs_right = sfigs[1].subplots(2, 2) +for ax in axs_right.flat: + pcm = ax.pcolormesh(arr, **pc_kwargs) + ax.set_xlabel('x-label') + ax.set_ylabel('y-label') + ax.set_title('title') +fig.colorbar(pcm, ax=axs_right) +fig.suptitle('Nested plots using subfigures') + +# %% +# Manually setting Axes positions +# ================================ +# +# There can be good reasons to manually set an Axes position. A manual call +# to `~.axes.Axes.set_position` will set the Axes so *constrained layout* has +# no effect on it anymore. (Note that *constrained layout* still leaves the +# space for the Axes that is moved). + +fig, axs = plt.subplots(1, 2, layout="constrained") +example_plot(axs[0], fontsize=12) +axs[1].set_position([0.2, 0.2, 0.4, 0.4]) + +# %% +# .. _compressed_layout: +# +# Grids of fixed aspect-ratio Axes: "compressed" layout +# ===================================================== +# +# *Constrained layout* operates on the grid of "original" positions for +# Axes. However, when Axes have fixed aspect ratios, one side is usually made +# shorter, and leaves large gaps in the shortened direction. In the following, +# the Axes are square, but the figure quite wide so there is a horizontal gap: + +fig, axs = plt.subplots(2, 2, figsize=(5, 3), + sharex=True, sharey=True, layout="constrained") +for ax in axs.flat: + ax.imshow(arr) +fig.suptitle("fixed-aspect plots, layout='constrained'") + +# %% +# One obvious way of fixing this is to make the figure size more square, +# however, closing the gaps exactly requires trial and error. For simple grids +# of Axes we can use ``layout="compressed"`` to do the job for us: + +fig, axs = plt.subplots(2, 2, figsize=(5, 3), + sharex=True, sharey=True, layout='compressed') +for ax in axs.flat: + ax.imshow(arr) +fig.suptitle("fixed-aspect plots, layout='compressed'") + + +# %% +# Manually turning off *constrained layout* +# =========================================== +# +# *Constrained layout* usually adjusts the Axes positions on each draw +# of the figure. If you want to get the spacing provided by +# *constrained layout* but not have it update, then do the initial +# draw and then call ``fig.set_layout_engine('none')``. +# This is potentially useful for animations where the tick labels may +# change length. +# +# Note that *constrained layout* is turned off for ``ZOOM`` and ``PAN`` +# GUI events for the backends that use the toolbar. This prevents the +# Axes from changing position during zooming and panning. +# +# +# Limitations +# =========== +# +# Incompatible functions +# ---------------------- +# +# *Constrained layout* will work with `.pyplot.subplot`, but only if the +# number of rows and columns is the same for each call. +# The reason is that each call to `.pyplot.subplot` will create a new +# `.GridSpec` instance if the geometry is not the same, and +# *constrained layout*. So the following works fine: + +fig = plt.figure(layout="constrained") + +ax1 = plt.subplot(2, 2, 1) +ax2 = plt.subplot(2, 2, 3) +# third Axes that spans both rows in second column: +ax3 = plt.subplot(2, 2, (2, 4)) + +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +plt.suptitle('Homogenous nrows, ncols') + +# %% +# but the following leads to a poor layout: + +fig = plt.figure(layout="constrained") + +ax1 = plt.subplot(2, 2, 1) +ax2 = plt.subplot(2, 2, 3) +ax3 = plt.subplot(1, 2, 2) + +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +plt.suptitle('Mixed nrows, ncols') + +# %% +# Similarly, +# `~matplotlib.pyplot.subplot2grid` works with the same limitation +# that nrows and ncols cannot change for the layout to look good. + +fig = plt.figure(layout="constrained") + +ax1 = plt.subplot2grid((3, 3), (0, 0)) +ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) +ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) +ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) + +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) +fig.suptitle('subplot2grid') + +# %% +# Other caveats +# ------------- +# +# * *Constrained layout* only considers ticklabels, axis labels, titles, and +# legends. Thus, other artists may be clipped and also may overlap. +# +# * It assumes that the extra space needed for ticklabels, axis labels, +# and titles is independent of original location of Axes. This is +# often true, but there are rare cases where it is not. +# +# * There are small differences in how the backends handle rendering fonts, +# so the results will not be pixel-identical. +# +# * An artist using Axes coordinates that extend beyond the Axes +# boundary will result in unusual layouts when added to an +# Axes. This can be avoided by adding the artist directly to the +# :class:`~matplotlib.figure.Figure` using +# :meth:`~matplotlib.figure.Figure.add_artist`. See +# :class:`~matplotlib.patches.ConnectionPatch` for an example. + +# %% +# Debugging +# ========= +# +# *Constrained layout* can fail in somewhat unexpected ways. Because it uses +# a constraint solver the solver can find solutions that are mathematically +# correct, but that aren't at all what the user wants. The usual failure +# mode is for all sizes to collapse to their smallest allowable value. If +# this happens, it is for one of two reasons: +# +# 1. There was not enough room for the elements you were requesting to draw. +# 2. There is a bug - in which case open an issue at +# https://github.com/matplotlib/matplotlib/issues. +# +# If there is a bug, please report with a self-contained example that does +# not require outside data or dependencies (other than numpy). + +# %% +# .. _cl_notes_on_algorithm: +# +# Notes on the algorithm +# ====================== +# +# The algorithm for the constraint is relatively straightforward, but +# has some complexity due to the complex ways we can lay out a figure. +# +# Layout in Matplotlib is carried out with gridspecs +# via the `.GridSpec` class. A gridspec is a logical division of the figure +# into rows and columns, with the relative width of the Axes in those +# rows and columns set by *width_ratios* and *height_ratios*. +# +# In *constrained layout*, each gridspec gets a *layoutgrid* associated with +# it. The *layoutgrid* has a series of ``left`` and ``right`` variables +# for each column, and ``bottom`` and ``top`` variables for each row, and +# further it has a margin for each of left, right, bottom and top. In each +# row, the bottom/top margins are widened until all the decorators +# in that row are accommodated. Similarly, for columns and the left/right +# margins. +# +# +# Simple case: one Axes +# --------------------- +# +# For a single Axes the layout is straight forward. There is one parent +# layoutgrid for the figure consisting of one column and row, and +# a child layoutgrid for the gridspec that contains the Axes, again +# consisting of one row and column. Space is made for the "decorations" on +# each side of the Axes. In the code, this is accomplished by the entries in +# ``do_constrained_layout()`` like:: +# +# gridspec._layoutgrid[0, 0].edit_margin_min('left', +# -bbox.x0 + pos.x0 + w_pad) +# +# where ``bbox`` is the tight bounding box of the Axes, and ``pos`` its +# position. Note how the four margins encompass the Axes decorations. + +from matplotlib._layoutgrid import plot_children + +fig, ax = plt.subplots(layout="constrained") +example_plot(ax, fontsize=24) +plot_children(fig) + +# %% +# Simple case: two Axes +# --------------------- +# When there are multiple Axes they have their layouts bound in +# simple ways. In this example the left Axes has much larger decorations +# than the right, but they share a bottom margin, which is made large +# enough to accommodate the larger xlabel. Same with the shared top +# margin. The left and right margins are not shared, and hence are +# allowed to be different. + +fig, ax = plt.subplots(1, 2, layout="constrained") +example_plot(ax[0], fontsize=32) +example_plot(ax[1], fontsize=8) +plot_children(fig) + +# %% +# Two Axes and colorbar +# --------------------- +# +# A colorbar is simply another item that expands the margin of the parent +# layoutgrid cell: + +fig, ax = plt.subplots(1, 2, layout="constrained") +im = ax[0].pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=ax[0], shrink=0.6) +im = ax[1].pcolormesh(arr, **pc_kwargs) +plot_children(fig) + +# %% +# Colorbar associated with a Gridspec +# ----------------------------------- +# +# If a colorbar belongs to more than one cell of the grid, then +# it makes a larger margin for each: + +fig, axs = plt.subplots(2, 2, layout="constrained") +for ax in axs.flat: + im = ax.pcolormesh(arr, **pc_kwargs) +fig.colorbar(im, ax=axs, shrink=0.6) +plot_children(fig) + +# %% +# Uneven sized Axes +# ----------------- +# +# There are two ways to make Axes have an uneven size in a +# Gridspec layout, either by specifying them to cross Gridspecs rows +# or columns, or by specifying width and height ratios. +# +# The first method is used here. Note that the middle ``top`` and +# ``bottom`` margins are not affected by the left-hand column. This +# is a conscious decision of the algorithm, and leads to the case where +# the two right-hand Axes have the same height, but it is not 1/2 the height +# of the left-hand Axes. This is consistent with how ``gridspec`` works +# without *constrained layout*. + +fig = plt.figure(layout="constrained") +gs = gridspec.GridSpec(2, 2, figure=fig) +ax = fig.add_subplot(gs[:, 0]) +im = ax.pcolormesh(arr, **pc_kwargs) +ax = fig.add_subplot(gs[0, 1]) +im = ax.pcolormesh(arr, **pc_kwargs) +ax = fig.add_subplot(gs[1, 1]) +im = ax.pcolormesh(arr, **pc_kwargs) +plot_children(fig) + +# %% +# One case that requires finessing is if margins do not have any artists +# constraining their width. In the case below, the right margin for column 0 +# and the left margin for column 3 have no margin artists to set their width, +# so we take the maximum width of the margin widths that do have artists. +# This makes all the Axes have the same size: + +fig = plt.figure(layout="constrained") +gs = fig.add_gridspec(2, 4) +ax00 = fig.add_subplot(gs[0, 0:2]) +ax01 = fig.add_subplot(gs[0, 2:]) +ax10 = fig.add_subplot(gs[1, 1:3]) +example_plot(ax10, fontsize=14) +plot_children(fig) +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/index.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..3d0a67ca14e7953fa7ed9cd99f1e4f547d58d9fd --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/index.rst @@ -0,0 +1,54 @@ ++++++++++++++++++ +Axes and subplots ++++++++++++++++++ + +Matplotlib `~.axes.Axes` are the gateway to creating your data visualizations. +Once an Axes is placed on a figure there are many methods that can be used to +add data to the Axes. An Axes typically has a pair of `~.axis.Axis` +Artists that define the data coordinate system, and include methods to add +annotations like x- and y-labels, titles, and legends. + +.. plot:: + + import matplotlib.pyplot as plt + import numpy as np + + fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(3.5, 2.5), + layout="constrained") + # for each Axes, add an artist, in this case a nice label in the middle... + for row in range(2): + for col in range(2): + axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5), + transform=axs[row, col].transAxes, + ha='center', va='center', fontsize=18, + color='darkgrey') + fig.suptitle('plt.subplots()') + + +.. toctree:: + :maxdepth: 2 + + axes_intro + +.. toctree:: + :maxdepth: 1 + + arranging_axes + colorbar_placement + Autoscaling axes + +.. toctree:: + :maxdepth: 2 + :includehidden: + + axes_scales + axes_ticks + Legends + Subplot mosaic + +.. toctree:: + :maxdepth: 1 + :includehidden: + + Constrained layout guide + Tight layout guide (mildly discouraged) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/legend_guide.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/legend_guide.py new file mode 100644 index 0000000000000000000000000000000000000000..9900b0aa4bdd3c54c80ee55dc7285ab973232a23 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/legend_guide.py @@ -0,0 +1,355 @@ +""" +.. redirect-from:: /tutorials/intermediate/legend_guide + +.. _legend_guide: + +============ +Legend guide +============ + +Generating legends flexibly in Matplotlib. + +.. currentmodule:: matplotlib.pyplot + +This legend guide is an extension of the documentation available at +:func:`~matplotlib.pyplot.legend` - please ensure you are familiar with +contents of that documentation before proceeding with this guide. + +This guide makes use of some common terms, which are documented here for +clarity: + +.. glossary:: + + legend entry + A legend is made up of one or more legend entries. An entry is made up + of exactly one key and one label. + + legend key + The colored/patterned marker to the left of each legend label. + + legend label + The text which describes the handle represented by the key. + + legend handle + The original object which is used to generate an appropriate entry in + the legend. + + +Controlling the legend entries +============================== + +Calling :func:`legend` with no arguments automatically fetches the legend +handles and their associated labels. This functionality is equivalent to:: + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles, labels) + +The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns +a list of handles/artists which exist on the Axes which can be used to +generate entries for the resulting legend - it is worth noting however that +not all artists can be added to a legend, at which point a "proxy" will have +to be created (see :ref:`proxy_legend_handles` for further details). + +.. note:: + Artists with an empty string as label or with a label starting with an + underscore, "_", will be ignored. + +For full control of what is being added to the legend, it is common to pass +the appropriate handles directly to :func:`legend`:: + + fig, ax = plt.subplots() + line_up, = ax.plot([1, 2, 3], label='Line 2') + line_down, = ax.plot([3, 2, 1], label='Line 1') + ax.legend(handles=[line_up, line_down]) + +In some cases, it is not possible to set the label of the handle, so it is +possible to pass through the list of labels to :func:`legend`:: + + fig, ax = plt.subplots() + line_up, = ax.plot([1, 2, 3], label='Line 2') + line_down, = ax.plot([3, 2, 1], label='Line 1') + ax.legend([line_up, line_down], ['Line Up', 'Line Down']) + + +.. _proxy_legend_handles: + +Creating artists specifically for adding to the legend (aka. Proxy artists) +=========================================================================== + +Not all handles can be turned into legend entries automatically, +so it is often necessary to create an artist which *can*. Legend handles +don't have to exist on the Figure or Axes in order to be used. + +Suppose we wanted to create a legend which has an entry for some data which +is represented by a red color: +""" + +import matplotlib.pyplot as plt + +import matplotlib.patches as mpatches + +fig, ax = plt.subplots() +red_patch = mpatches.Patch(color='red', label='The red data') +ax.legend(handles=[red_patch]) + +plt.show() + +# %% +# There are many supported legend handles. Instead of creating a patch of color +# we could have created a line with a marker: + +import matplotlib.lines as mlines + +fig, ax = plt.subplots() +blue_line = mlines.Line2D([], [], color='blue', marker='*', + markersize=15, label='Blue stars') +ax.legend(handles=[blue_line]) + +plt.show() + +# %% +# Legend location +# =============== +# +# The location of the legend can be specified by the keyword argument +# *loc*. Please see the documentation at :func:`legend` for more details. +# +# The ``bbox_to_anchor`` keyword gives a great degree of control for manual +# legend placement. For example, if you want your axes legend located at the +# figure's top right-hand corner instead of the axes' corner, simply specify +# the corner's location and the coordinate system of that location:: +# +# ax.legend(bbox_to_anchor=(1, 1), +# bbox_transform=fig.transFigure) +# +# More examples of custom legend placement: + +fig, ax_dict = plt.subplot_mosaic([['top', 'top'], ['bottom', 'BLANK']], + empty_sentinel="BLANK") +ax_dict['top'].plot([1, 2, 3], label="test1") +ax_dict['top'].plot([3, 2, 1], label="test2") +# Place a legend above this subplot, expanding itself to +# fully use the given bounding box. +ax_dict['top'].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', + ncols=2, mode="expand", borderaxespad=0.) + +ax_dict['bottom'].plot([1, 2, 3], label="test1") +ax_dict['bottom'].plot([3, 2, 1], label="test2") +# Place a legend to the right of this smaller subplot. +ax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1), + loc='upper left', borderaxespad=0.) + +# %% +# Figure legends +# -------------- +# +# Sometimes it makes more sense to place a legend relative to the (sub)figure +# rather than individual Axes. By using *constrained layout* and +# specifying "outside" at the beginning of the *loc* keyword argument, +# the legend is drawn outside the Axes on the (sub)figure. + +fig, axs = plt.subplot_mosaic([['left', 'right']], layout='constrained') + +axs['left'].plot([1, 2, 3], label="test1") +axs['left'].plot([3, 2, 1], label="test2") + +axs['right'].plot([1, 2, 3], 'C2', label="test3") +axs['right'].plot([3, 2, 1], 'C3', label="test4") +# Place a legend to the right of this smaller subplot. +fig.legend(loc='outside upper right') + +# %% +# This accepts a slightly different grammar than the normal *loc* keyword, +# where "outside right upper" is different from "outside upper right". +# +ucl = ['upper', 'center', 'lower'] +lcr = ['left', 'center', 'right'] +fig, ax = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7') + +ax.plot([1, 2], [1, 2], label='TEST') +# Place a legend to the right of this smaller subplot. +for loc in [ + 'outside upper left', + 'outside upper center', + 'outside upper right', + 'outside lower left', + 'outside lower center', + 'outside lower right']: + fig.legend(loc=loc, title=loc) + +fig, ax = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7') +ax.plot([1, 2], [1, 2], label='test') + +for loc in [ + 'outside left upper', + 'outside right upper', + 'outside left lower', + 'outside right lower']: + fig.legend(loc=loc, title=loc) + + +# %% +# Multiple legends on the same Axes +# ================================= +# +# Sometimes it is more clear to split legend entries across multiple +# legends. Whilst the instinctive approach to doing this might be to call +# the :func:`legend` function multiple times, you will find that only one +# legend ever exists on the Axes. This has been done so that it is possible +# to call :func:`legend` repeatedly to update the legend to the latest +# handles on the Axes. To keep old legend instances, we must add them +# manually to the Axes: + +fig, ax = plt.subplots() +line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--') +line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4) + +# Create a legend for the first line. +first_legend = ax.legend(handles=[line1], loc='upper right') + +# Add the legend manually to the Axes. +ax.add_artist(first_legend) + +# Create another legend for the second line. +ax.legend(handles=[line2], loc='lower right') + +plt.show() + +# %% +# Legend Handlers +# =============== +# +# In order to create legend entries, handles are given as an argument to an +# appropriate :class:`~matplotlib.legend_handler.HandlerBase` subclass. +# The choice of handler subclass is determined by the following rules: +# +# 1. Update :func:`~matplotlib.legend.Legend.get_legend_handler_map` +# with the value in the ``handler_map`` keyword. +# 2. Check if the ``handle`` is in the newly created ``handler_map``. +# 3. Check if the type of ``handle`` is in the newly created ``handler_map``. +# 4. Check if any of the types in the ``handle``'s mro is in the newly +# created ``handler_map``. +# +# For completeness, this logic is mostly implemented in +# :func:`~matplotlib.legend.Legend.get_legend_handler`. +# +# All of this flexibility means that we have the necessary hooks to implement +# custom handlers for our own type of legend key. +# +# The simplest example of using custom handlers is to instantiate one of the +# existing `.legend_handler.HandlerBase` subclasses. For the +# sake of simplicity, let's choose `.legend_handler.HandlerLine2D` +# which accepts a *numpoints* argument (numpoints is also a keyword +# on the :func:`legend` function for convenience). We can then pass the mapping +# of instance to Handler as a keyword to legend. + +from matplotlib.legend_handler import HandlerLine2D + +fig, ax = plt.subplots() +line1, = ax.plot([3, 2, 1], marker='o', label='Line 1') +line2, = ax.plot([1, 2, 3], marker='o', label='Line 2') + +ax.legend(handler_map={line1: HandlerLine2D(numpoints=4)}) + +# %% +# As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the +# default). Try the above code, only change the map's key from ``line1`` to +# ``type(line1)``. Notice how now both `.Line2D` instances get 4 markers. +# +# Along with handlers for complex plot types such as errorbars, stem plots +# and histograms, the default ``handler_map`` has a special ``tuple`` handler +# (`.legend_handler.HandlerTuple`) which simply plots the handles on top of one +# another for each item in the given tuple. The following example demonstrates +# combining two legend keys on top of one another: + +from numpy.random import randn + +z = randn(10) + +fig, ax = plt.subplots() +red_dot, = ax.plot(z, "ro", markersize=15) +# Put a white cross over some of the data. +white_cross, = ax.plot(z[:5], "w+", markeredgewidth=3, markersize=15) + +ax.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"]) + +# %% +# The `.legend_handler.HandlerTuple` class can also be used to +# assign several legend keys to the same entry: + +from matplotlib.legend_handler import HandlerLine2D, HandlerTuple + +fig, ax = plt.subplots() +p1, = ax.plot([1, 2.5, 3], 'r-d') +p2, = ax.plot([3, 2, 1], 'k-o') + +l = ax.legend([(p1, p2)], ['Two keys'], numpoints=1, + handler_map={tuple: HandlerTuple(ndivide=None)}) + +# %% +# Implementing a custom legend handler +# ------------------------------------ +# +# A custom handler can be implemented to turn any handle into a legend key +# (handles don't necessarily need to be matplotlib artists). The handler must +# implement a ``legend_artist`` method which returns a single artist for the +# legend to use. The required signature for ``legend_artist`` is documented at +# `~.legend_handler.HandlerBase.legend_artist`. + +import matplotlib.patches as mpatches + + +class AnyObject: + pass + + +class AnyObjectHandler: + def legend_artist(self, legend, orig_handle, fontsize, handlebox): + x0, y0 = handlebox.xdescent, handlebox.ydescent + width, height = handlebox.width, handlebox.height + patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red', + edgecolor='black', hatch='xx', lw=3, + transform=handlebox.get_transform()) + handlebox.add_artist(patch) + return patch + +fig, ax = plt.subplots() + +ax.legend([AnyObject()], ['My first handler'], + handler_map={AnyObject: AnyObjectHandler()}) + +# %% +# Alternatively, had we wanted to globally accept ``AnyObject`` instances +# without needing to manually set the *handler_map* keyword all the time, we +# could have registered the new handler with:: +# +# from matplotlib.legend import Legend +# Legend.update_default_handler_map({AnyObject: AnyObjectHandler()}) +# +# Whilst the power here is clear, remember that there are already many handlers +# implemented and what you want to achieve may already be easily possible with +# existing classes. For example, to produce elliptical legend keys, rather than +# rectangular ones: + +from matplotlib.legend_handler import HandlerPatch + + +class HandlerEllipse(HandlerPatch): + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent + p = mpatches.Ellipse(xy=center, width=width + xdescent, + height=height + ydescent) + self.update_prop(p, orig_handle, legend) + p.set_transform(trans) + return [p] + + +c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green", + edgecolor="red", linewidth=3) + +fig, ax = plt.subplots() + +ax.add_patch(c) +ax.legend([c], ["An ellipse, not a rectangle"], + handler_map={mpatches.Circle: HandlerEllipse()}) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/mosaic.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/mosaic.py new file mode 100644 index 0000000000000000000000000000000000000000..88d4562c7af6f3bce2987e002f99374ce2ed31c4 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/mosaic.py @@ -0,0 +1,392 @@ +""" +.. redirect-from:: /tutorials/provisional/mosaic +.. redirect-from:: /gallery/subplots_axes_and_figures/mosaic + +.. _mosaic: + +======================================================== +Complex and semantic figure composition (subplot_mosaic) +======================================================== + +Laying out Axes in a Figure in a non-uniform grid can be both tedious +and verbose. For dense, even grids we have `.Figure.subplots` but for +more complex layouts, such as Axes that span multiple columns / rows +of the layout or leave some areas of the Figure blank, you can use +`.gridspec.GridSpec` (see :ref:`arranging_axes`) or +manually place your axes. `.Figure.subplot_mosaic` aims to provide an +interface to visually lay out your axes (as either ASCII art or nested +lists) to streamline this process. + +This interface naturally supports naming your axes. +`.Figure.subplot_mosaic` returns a dictionary keyed on the +labels used to lay out the Figure. By returning data structures with +names, it is easier to write plotting code that is independent of the +Figure layout. + + +This is inspired by a `proposed MEP +`__ and the +`patchwork `__ library for R. +While we do not implement the operator overloading style, we do +provide a Pythonic API for specifying (nested) Axes layouts. + +""" +import matplotlib.pyplot as plt +import numpy as np + + +# Helper function used for visualization in the following examples +def identify_axes(ax_dict, fontsize=48): + """ + Helper to identify the Axes in the examples below. + + Draws the label in a large font in the center of the Axes. + + Parameters + ---------- + ax_dict : dict[str, Axes] + Mapping between the title / label and the Axes. + fontsize : int, optional + How big the label should be. + """ + kw = dict(ha="center", va="center", fontsize=fontsize, color="darkgrey") + for k, ax in ax_dict.items(): + ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw) + + +# %% +# If we want a 2x2 grid we can use `.Figure.subplots` which returns a 2D array +# of `.axes.Axes` which we can index into to do our plotting. +np.random.seed(19680801) +hist_data = np.random.randn(1_500) + + +fig = plt.figure(layout="constrained") +ax_array = fig.subplots(2, 2, squeeze=False) + +ax_array[0, 0].bar(["a", "b", "c"], [5, 7, 9]) +ax_array[0, 1].plot([1, 2, 3]) +ax_array[1, 0].hist(hist_data, bins="auto") +ax_array[1, 1].imshow([[1, 2], [2, 1]]) + +identify_axes( + {(j, k): a for j, r in enumerate(ax_array) for k, a in enumerate(r)}, +) + +# %% +# Using `.Figure.subplot_mosaic` we can produce the same mosaic but give the +# axes semantic names + +fig = plt.figure(layout="constrained") +ax_dict = fig.subplot_mosaic( + [ + ["bar", "plot"], + ["hist", "image"], + ], +) +ax_dict["bar"].bar(["a", "b", "c"], [5, 7, 9]) +ax_dict["plot"].plot([1, 2, 3]) +ax_dict["hist"].hist(hist_data) +ax_dict["image"].imshow([[1, 2], [2, 1]]) +identify_axes(ax_dict) + +# %% +# A key difference between `.Figure.subplots` and +# `.Figure.subplot_mosaic` is the return value. While the former +# returns an array for index access, the latter returns a dictionary +# mapping the labels to the `.axes.Axes` instances created + +print(ax_dict) + + +# %% +# String short-hand +# ================= +# +# By restricting our axes labels to single characters we can +# "draw" the Axes we want as "ASCII art". The following + + +mosaic = """ + AB + CD + """ + +# %% +# will give us 4 Axes laid out in a 2x2 grid and generates the same +# figure mosaic as above (but now labeled with ``{"A", "B", "C", +# "D"}`` rather than ``{"bar", "plot", "hist", "image"}``). + +fig = plt.figure(layout="constrained") +ax_dict = fig.subplot_mosaic(mosaic) +identify_axes(ax_dict) + +# %% +# Alternatively, you can use the more compact string notation +mosaic = "AB;CD" + +# %% +# will give you the same composition, where the ``";"`` is used +# as the row separator instead of newline. + +fig = plt.figure(layout="constrained") +ax_dict = fig.subplot_mosaic(mosaic) +identify_axes(ax_dict) + +# %% +# Axes spanning multiple rows/columns +# =================================== +# +# Something we can do with `.Figure.subplot_mosaic`, that we cannot +# do with `.Figure.subplots`, is to specify that an Axes should span +# several rows or columns. + + +# %% +# If we want to re-arrange our four Axes to have ``"C"`` be a horizontal +# span on the bottom and ``"D"`` be a vertical span on the right we would do + +axd = plt.figure(layout="constrained").subplot_mosaic( + """ + ABD + CCD + """ +) +identify_axes(axd) + +# %% +# If we do not want to fill in all the spaces in the Figure with Axes, +# we can specify some spaces in the grid to be blank + + +axd = plt.figure(layout="constrained").subplot_mosaic( + """ + A.C + BBB + .D. + """ +) +identify_axes(axd) + + +# %% +# If we prefer to use another character (rather than a period ``"."``) +# to mark the empty space, we can use *empty_sentinel* to specify the +# character to use. + +axd = plt.figure(layout="constrained").subplot_mosaic( + """ + aX + Xb + """, + empty_sentinel="X", +) +identify_axes(axd) + + +# %% +# +# Internally there is no meaning attached to the letters we use, any +# Unicode code point is valid! + +axd = plt.figure(layout="constrained").subplot_mosaic( + """αб + ℝ☢""" +) +identify_axes(axd) + +# %% +# It is not recommended to use white space as either a label or an +# empty sentinel with the string shorthand because it may be stripped +# while processing the input. +# +# Controlling mosaic creation +# =========================== +# +# This feature is built on top of `.gridspec` and you can pass the +# keyword arguments through to the underlying `.gridspec.GridSpec` +# (the same as `.Figure.subplots`). +# +# In this case we want to use the input to specify the arrangement, +# but set the relative widths of the rows / columns. For convenience, +# `.gridspec.GridSpec`'s *height_ratios* and *width_ratios* are exposed in the +# `.Figure.subplot_mosaic` calling sequence. + + +axd = plt.figure(layout="constrained").subplot_mosaic( + """ + .a. + bAc + .d. + """, + # set the height ratios between the rows + height_ratios=[1, 3.5, 1], + # set the width ratios between the columns + width_ratios=[1, 3.5, 1], +) +identify_axes(axd) + +# %% +# Other `.gridspec.GridSpec` keywords can be passed via *gridspec_kw*. For +# example, use the {*left*, *right*, *bottom*, *top*} keyword arguments to +# position the overall mosaic to put multiple versions of the same +# mosaic in a figure. + +mosaic = """AA + BC""" +fig = plt.figure() +axd = fig.subplot_mosaic( + mosaic, + gridspec_kw={ + "bottom": 0.25, + "top": 0.95, + "left": 0.1, + "right": 0.5, + "wspace": 0.5, + "hspace": 0.5, + }, +) +identify_axes(axd) + +axd = fig.subplot_mosaic( + mosaic, + gridspec_kw={ + "bottom": 0.05, + "top": 0.75, + "left": 0.6, + "right": 0.95, + "wspace": 0.5, + "hspace": 0.5, + }, +) +identify_axes(axd) + +# %% +# Alternatively, you can use the sub-Figure functionality: + +mosaic = """AA + BC""" +fig = plt.figure(layout="constrained") +left, right = fig.subfigures(nrows=1, ncols=2) +axd = left.subplot_mosaic(mosaic) +identify_axes(axd) + +axd = right.subplot_mosaic(mosaic) +identify_axes(axd) + + +# %% +# Controlling subplot creation +# ============================ +# +# We can also pass through arguments used to create the subplots +# (again, the same as `.Figure.subplots`) which will apply to all +# of the Axes created. + + +axd = plt.figure(layout="constrained").subplot_mosaic( + "AB", subplot_kw={"projection": "polar"} +) +identify_axes(axd) + +# %% +# Per-Axes subplot keyword arguments +# ---------------------------------- +# +# If you need to control the parameters passed to each subplot individually use +# *per_subplot_kw* to pass a mapping between the Axes identifiers (or +# tuples of Axes identifiers) to dictionaries of keywords to be passed. +# +# .. versionadded:: 3.7 +# + + +fig, axd = plt.subplot_mosaic( + "AB;CD", + per_subplot_kw={ + "A": {"projection": "polar"}, + ("C", "D"): {"xscale": "log"} + }, +) +identify_axes(axd) + +# %% +# If the layout is specified with the string short-hand, then we know the +# Axes labels will be one character and can unambiguously interpret longer +# strings in *per_subplot_kw* to specify a set of Axes to apply the +# keywords to: + + +fig, axd = plt.subplot_mosaic( + "AB;CD", + per_subplot_kw={ + "AD": {"projection": "polar"}, + "BC": {"facecolor": ".9"} + }, +) +identify_axes(axd) + +# %% +# If *subplot_kw* and *per_subplot_kw* are used together, then they are +# merged with *per_subplot_kw* taking priority: + + +axd = plt.figure(layout="constrained").subplot_mosaic( + "AB;CD", + subplot_kw={"facecolor": "xkcd:tangerine"}, + per_subplot_kw={ + "B": {"facecolor": "xkcd:water blue"}, + "D": {"projection": "polar", "facecolor": "w"}, + } +) +identify_axes(axd) + + +# %% +# Nested list input +# ================= +# +# Everything we can do with the string shorthand we can also do when +# passing in a list (internally we convert the string shorthand to a nested +# list), for example using spans, blanks, and *gridspec_kw*: + +axd = plt.figure(layout="constrained").subplot_mosaic( + [ + ["main", "zoom"], + ["main", "BLANK"], + ], + empty_sentinel="BLANK", + width_ratios=[2, 1], +) +identify_axes(axd) + + +# %% +# In addition, using the list input we can specify nested mosaics. Any element +# of the inner list can be another set of nested lists: + +inner = [ + ["inner A"], + ["inner B"], +] + +outer_nested_mosaic = [ + ["main", inner], + ["bottom", "bottom"], +] +axd = plt.figure(layout="constrained").subplot_mosaic( + outer_nested_mosaic, empty_sentinel=None +) +identify_axes(axd, fontsize=36) + + +# %% +# We can also pass in a 2D NumPy array to do things like +mosaic = np.zeros((4, 4), dtype=int) +for j in range(4): + mosaic[j, j] = j + 1 +axd = plt.figure(layout="constrained").subplot_mosaic( + mosaic, + empty_sentinel=0, +) +identify_axes(axd) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/axes/tight_layout_guide.py b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/tight_layout_guide.py new file mode 100644 index 0000000000000000000000000000000000000000..42c227b2e3608e497aae70321c143040d1e209f8 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/axes/tight_layout_guide.py @@ -0,0 +1,296 @@ +""" +.. redirect-from:: /tutorial/intermediate/tight_layout_guide + +.. _tight_layout_guide: + +================== +Tight Layout guide +================== + +How to use tight-layout to fit plots within your figure cleanly. + +*tight_layout* automatically adjusts subplot params so that the +subplot(s) fits in to the figure area. This is an experimental +feature and may not work for some cases. It only checks the extents +of ticklabels, axis labels, and titles. + +An alternative to *tight_layout* is :ref:`constrained_layout +`. + + +Simple Example +============== + +In matplotlib, the location of axes (including subplots) are specified in +normalized figure coordinates. It can happen that your axis labels or +titles (or sometimes even ticklabels) go outside the figure area, and are thus +clipped. + +""" + +# sphinx_gallery_thumbnail_number = 7 + +import matplotlib.pyplot as plt +import numpy as np + +plt.rcParams['savefig.facecolor'] = "0.8" + + +def example_plot(ax, fontsize=12): + ax.plot([1, 2]) + + ax.locator_params(nbins=3) + ax.set_xlabel('x-label', fontsize=fontsize) + ax.set_ylabel('y-label', fontsize=fontsize) + ax.set_title('Title', fontsize=fontsize) + +plt.close('all') +fig, ax = plt.subplots() +example_plot(ax, fontsize=24) + +# %% +# To prevent this, the location of axes needs to be adjusted. For +# subplots, this can be done manually by adjusting the subplot parameters +# using `.Figure.subplots_adjust`. `.Figure.tight_layout` does this +# automatically. + +fig, ax = plt.subplots() +example_plot(ax, fontsize=24) +plt.tight_layout() + +# %% +# Note that :func:`matplotlib.pyplot.tight_layout` will only adjust the +# subplot params when it is called. In order to perform this adjustment each +# time the figure is redrawn, you can call ``fig.set_tight_layout(True)``, or, +# equivalently, set :rc:`figure.autolayout` to ``True``. +# +# When you have multiple subplots, often you see labels of different +# axes overlapping each other. + +plt.close('all') + +fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) + +# %% +# :func:`~matplotlib.pyplot.tight_layout` will also adjust spacing between +# subplots to minimize the overlaps. + +fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) +plt.tight_layout() + +# %% +# :func:`~matplotlib.pyplot.tight_layout` can take keyword arguments of +# *pad*, *w_pad* and *h_pad*. These control the extra padding around the +# figure border and between subplots. The pads are specified in fraction +# of fontsize. + +fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) +plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) + +# %% +# :func:`~matplotlib.pyplot.tight_layout` will work even if the sizes of +# subplots are different as far as their grid specification is +# compatible. In the example below, *ax1* and *ax2* are subplots of a 2x2 +# grid, while *ax3* is of a 1x2 grid. + +plt.close('all') +fig = plt.figure() + +ax1 = plt.subplot(221) +ax2 = plt.subplot(223) +ax3 = plt.subplot(122) + +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) + +plt.tight_layout() + +# %% +# It works with subplots created with +# :func:`~matplotlib.pyplot.subplot2grid`. In general, subplots created +# from the gridspec (:ref:`arranging_axes`) will work. + +plt.close('all') +fig = plt.figure() + +ax1 = plt.subplot2grid((3, 3), (0, 0)) +ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) +ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) +ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) + +example_plot(ax1) +example_plot(ax2) +example_plot(ax3) +example_plot(ax4) + +plt.tight_layout() + +# %% +# Although not thoroughly tested, it seems to work for subplots with +# aspect != "auto" (e.g., axes with images). + +arr = np.arange(100).reshape((10, 10)) + +plt.close('all') +fig = plt.figure(figsize=(5, 4)) + +ax = plt.subplot() +im = ax.imshow(arr, interpolation="none") + +plt.tight_layout() + +# %% +# Caveats +# ======= +# +# * `~matplotlib.pyplot.tight_layout` considers all artists on the axes by +# default. To remove an artist from the layout calculation you can call +# `.Artist.set_in_layout`. +# +# * ``tight_layout`` assumes that the extra space needed for artists is +# independent of the original location of axes. This is often true, but there +# are rare cases where it is not. +# +# * ``pad=0`` can clip some texts by a few pixels. This may be a bug or +# a limitation of the current algorithm, and it is not clear why it +# happens. Meanwhile, use of pad larger than 0.3 is recommended. +# +# Use with GridSpec +# ================= +# +# GridSpec has its own `.GridSpec.tight_layout` method (the pyplot api +# `.pyplot.tight_layout` also works). + +import matplotlib.gridspec as gridspec + +plt.close('all') +fig = plt.figure() + +gs1 = gridspec.GridSpec(2, 1) +ax1 = fig.add_subplot(gs1[0]) +ax2 = fig.add_subplot(gs1[1]) + +example_plot(ax1) +example_plot(ax2) + +gs1.tight_layout(fig) + +# %% +# You may provide an optional *rect* parameter, which specifies the bounding +# box that the subplots will be fit inside. The coordinates must be in +# normalized figure coordinates and the default is (0, 0, 1, 1). + +fig = plt.figure() + +gs1 = gridspec.GridSpec(2, 1) +ax1 = fig.add_subplot(gs1[0]) +ax2 = fig.add_subplot(gs1[1]) + +example_plot(ax1) +example_plot(ax2) + +gs1.tight_layout(fig, rect=[0, 0, 0.5, 1.0]) + +# %% +# However, we do not recommend that this be used to manually construct more +# complicated layouts, like having one GridSpec in the left and one in the +# right side of the figure. For these use cases, one should instead take +# advantage of :doc:`/gallery/subplots_axes_and_figures/gridspec_nested`, or +# the :doc:`/gallery/subplots_axes_and_figures/subfigures`. + + +# %% +# Legends and Annotations +# ======================= +# +# Pre Matplotlib 2.2, legends and annotations were excluded from the bounding +# box calculations that decide the layout. Subsequently, these artists were +# added to the calculation, but sometimes it is undesirable to include them. +# For instance in this case it might be good to have the axes shrink a bit +# to make room for the legend: + +fig, ax = plt.subplots(figsize=(4, 3)) +lines = ax.plot(range(10), label='A simple plot') +ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) +fig.tight_layout() +plt.show() + +# %% +# However, sometimes this is not desired (quite often when using +# ``fig.savefig('outname.png', bbox_inches='tight')``). In order to +# remove the legend from the bounding box calculation, we simply set its +# bounding ``leg.set_in_layout(False)`` and the legend will be ignored. + +fig, ax = plt.subplots(figsize=(4, 3)) +lines = ax.plot(range(10), label='B simple plot') +leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) +leg.set_in_layout(False) +fig.tight_layout() +plt.show() + +# %% +# Use with AxesGrid1 +# ================== +# +# While limited, :mod:`mpl_toolkits.axes_grid1` is also supported. + +from mpl_toolkits.axes_grid1 import Grid + +plt.close('all') +fig = plt.figure() +grid = Grid(fig, rect=111, nrows_ncols=(2, 2), + axes_pad=0.25, label_mode='L', + ) + +for ax in grid: + example_plot(ax) +ax.title.set_visible(False) + +plt.tight_layout() + +# %% +# Colorbar +# ======== +# +# If you create a colorbar with `.Figure.colorbar`, the created colorbar is +# drawn in a Subplot as long as the parent axes is also a Subplot, so +# `.Figure.tight_layout` will work. + +plt.close('all') +arr = np.arange(100).reshape((10, 10)) +fig = plt.figure(figsize=(4, 4)) +im = plt.imshow(arr, interpolation="none") + +plt.colorbar(im) + +plt.tight_layout() + +# %% +# Another option is to use the AxesGrid1 toolkit to +# explicitly create an Axes for the colorbar. + +from mpl_toolkits.axes_grid1 import make_axes_locatable + +plt.close('all') +arr = np.arange(100).reshape((10, 10)) +fig = plt.figure(figsize=(4, 4)) +im = plt.imshow(arr, interpolation="none") + +divider = make_axes_locatable(plt.gca()) +cax = divider.append_axes("right", "5%", pad="3%") +plt.colorbar(im, cax=cax) + +plt.tight_layout() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/README.txt b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..79f49c523f560316ea39c1552c59ca5c7d690063 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/README.txt @@ -0,0 +1,13 @@ +.. _tutorials-colors: + +.. redirect-from:: /tutorials/colors/index + +Colors +------ + +Matplotlib has support for visualizing information with a wide array +of colors and colormaps. These tutorials cover the basics of how +these colormaps look, how you can create your own, and how you can +customize colormaps for your use case. + +For even more information see the :ref:`examples page `. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colorbar_only.py b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colorbar_only.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f126533a16dcc97f6b40f987e71853a1aa72c6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colorbar_only.py @@ -0,0 +1,133 @@ +""" +.. redirect-from:: /tutorials/colors/colorbar_only + +============================= +Customized Colorbars Tutorial +============================= + +This tutorial shows how to build and customize standalone colorbars, i.e. +without an attached plot. + +Customized Colorbars +==================== + +A `~.Figure.colorbar` needs a "mappable" (`matplotlib.cm.ScalarMappable`) +object (typically, an image) which indicates the colormap and the norm to be +used. In order to create a colorbar without an attached image, one can instead +use a `.ScalarMappable` with no associated data. + +Basic continuous colorbar +------------------------- + +Here we create a basic continuous colorbar with ticks and labels. + +The arguments to the `~.Figure.colorbar` call are the `.ScalarMappable` +(constructed using the *norm* and *cmap* arguments), the axes where the +colorbar should be drawn, and the colorbar's orientation. + +For more information see the :mod:`~matplotlib.colorbar` API. +""" + +import matplotlib.pyplot as plt + +import matplotlib as mpl + +fig, ax = plt.subplots(figsize=(6, 1)) +fig.subplots_adjust(bottom=0.5) + +cmap = mpl.cm.cool +norm = mpl.colors.Normalize(vmin=5, vmax=10) + +fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), + cax=ax, orientation='horizontal', label='Some Units') + + +# %% +# Extended colorbar with continuous colorscale +# -------------------------------------------- +# +# The second example shows how to make a discrete colorbar based on a +# continuous cmap. With the "extend" keyword argument the appropriate colors +# are chosen to fill the colorspace, including the extensions: +fig, ax = plt.subplots(figsize=(6, 1)) +fig.subplots_adjust(bottom=0.5) + +cmap = mpl.cm.viridis +bounds = [-1, 2, 5, 7, 12, 15] +norm = mpl.colors.BoundaryNorm(bounds, cmap.N, extend='both') + +fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), + cax=ax, orientation='horizontal', + label="Discrete intervals with extend='both' keyword") + +# %% +# Discrete intervals colorbar +# --------------------------- +# +# The third example illustrates the use of a +# :class:`~matplotlib.colors.ListedColormap` which generates a colormap from a +# set of listed colors, `.colors.BoundaryNorm` which generates a colormap +# index based on discrete intervals and extended ends to show the "over" and +# "under" value colors. Over and under are used to display data outside of the +# normalized [0, 1] range. Here we pass colors as gray shades as a string +# encoding a float in the 0-1 range. +# +# If a :class:`~matplotlib.colors.ListedColormap` is used, the length of the +# bounds array must be one greater than the length of the color list. The +# bounds must be monotonically increasing. +# +# This time we pass additional arguments to +# `~.Figure.colorbar`. For the out-of-range values to display on the colorbar +# without using the *extend* keyword with +# `.colors.BoundaryNorm`, we have to use the *extend* keyword argument directly +# in the colorbar call. Here we also +# use the spacing argument to make +# the length of each colorbar segment proportional to its corresponding +# interval. + +fig, ax = plt.subplots(figsize=(6, 1)) +fig.subplots_adjust(bottom=0.5) + +cmap = (mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan']) + .with_extremes(over='0.25', under='0.75')) + +bounds = [1, 2, 4, 7, 8] +norm = mpl.colors.BoundaryNorm(bounds, cmap.N) +fig.colorbar( + mpl.cm.ScalarMappable(cmap=cmap, norm=norm), + cax=ax, + extend='both', + ticks=bounds, + spacing='proportional', + orientation='horizontal', + label='Discrete intervals, some other units', +) + +# %% +# Colorbar with custom extension lengths +# -------------------------------------- +# +# Here we illustrate the use of custom length colorbar extensions, on a +# colorbar with discrete intervals. To make the length of each extension the +# same as the length of the interior colors, use ``extendfrac='auto'``. + +fig, ax = plt.subplots(figsize=(6, 1)) +fig.subplots_adjust(bottom=0.5) + +cmap = (mpl.colors.ListedColormap(['royalblue', 'cyan', 'yellow', 'orange']) + .with_extremes(over='red', under='blue')) + +bounds = [-1.0, -0.5, 0.0, 0.5, 1.0] +norm = mpl.colors.BoundaryNorm(bounds, cmap.N) +fig.colorbar( + mpl.cm.ScalarMappable(cmap=cmap, norm=norm), + cax=ax, + extend='both', + extendfrac='auto', + ticks=bounds, + spacing='uniform', + orientation='horizontal', + label='Custom extension lengths, some other units', +) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormap-manipulation.py b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormap-manipulation.py new file mode 100644 index 0000000000000000000000000000000000000000..88e4c5befaf0d0161e5972152a5edbc01136d258 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormap-manipulation.py @@ -0,0 +1,318 @@ +""" +.. redirect-from:: /tutorials/colors/colormap-manipulation + +.. _colormap-manipulation: + +******************************** +Creating Colormaps in Matplotlib +******************************** + +Matplotlib has a number of built-in colormaps accessible via +`.matplotlib.colormaps`. There are also external libraries like +palettable_ that have many extra colormaps. + +.. _palettable: https://jiffyclub.github.io/palettable/ + +However, we often want to create or manipulate colormaps in Matplotlib. +This can be done using the class `.ListedColormap` or +`.LinearSegmentedColormap`. +Seen from the outside, both colormap classes map values between 0 and 1 to +a bunch of colors. There are, however, slight differences, some of which are +shown in the following. + +Before manually creating or manipulating colormaps, let us first see how we +can obtain colormaps and their colors from existing colormap classes. + + +Getting colormaps and accessing their values +============================================ + +First, getting a named colormap, most of which are listed in +:ref:`colormaps`, may be done using `.matplotlib.colormaps`, +which returns a colormap object. The length of the list of colors used +internally to define the colormap can be adjusted via `.Colormap.resampled`. +Below we use a modest value of 8 so there are not a lot of values to look at. + +""" + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib as mpl +from matplotlib.colors import LinearSegmentedColormap, ListedColormap + +viridis = mpl.colormaps['viridis'].resampled(8) + +# %% +# The object ``viridis`` is a callable, that when passed a float between +# 0 and 1 returns an RGBA value from the colormap: + +print(viridis(0.56)) + +# %% +# ListedColormap +# -------------- +# +# `.ListedColormap`\s store their color values in a ``.colors`` attribute. +# The list of colors that comprise the colormap can be directly accessed using +# the ``colors`` property, +# or it can be accessed indirectly by calling ``viridis`` with an array of +# values matching the length of the colormap. Note that the returned list is +# in the form of an RGBA (N, 4) array, where N is the length of the colormap. + +print('viridis.colors', viridis.colors) +print('viridis(range(8))', viridis(range(8))) +print('viridis(np.linspace(0, 1, 8))', viridis(np.linspace(0, 1, 8))) + +# %% +# The colormap is a lookup table, so "oversampling" the colormap returns +# nearest-neighbor interpolation (note the repeated colors in the list below) + +print('viridis(np.linspace(0, 1, 12))', viridis(np.linspace(0, 1, 12))) + +# %% +# LinearSegmentedColormap +# ----------------------- +# `.LinearSegmentedColormap`\s do not have a ``.colors`` attribute. +# However, one may still call the colormap with an integer array, or with a +# float array between 0 and 1. + +copper = mpl.colormaps['copper'].resampled(8) + +print('copper(range(8))', copper(range(8))) +print('copper(np.linspace(0, 1, 8))', copper(np.linspace(0, 1, 8))) + +# %% +# Creating listed colormaps +# ========================= +# +# Creating a colormap is essentially the inverse operation of the above where +# we supply a list or array of color specifications to `.ListedColormap` to +# make a new colormap. +# +# Before continuing with the tutorial, let us define a helper function that +# takes one of more colormaps as input, creates some random data and applies +# the colormap(s) to an image plot of that dataset. + + +def plot_examples(colormaps): + """ + Helper function to plot data with associated colormap. + """ + np.random.seed(19680801) + data = np.random.randn(30, 30) + n = len(colormaps) + fig, axs = plt.subplots(1, n, figsize=(n * 2 + 2, 3), + layout='constrained', squeeze=False) + for [ax, cmap] in zip(axs.flat, colormaps): + psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4) + fig.colorbar(psm, ax=ax) + plt.show() + + +# %% +# In the simplest case we might type in a list of color names to create a +# colormap from those. + +cmap = ListedColormap(["darkorange", "gold", "lawngreen", "lightseagreen"]) +plot_examples([cmap]) + +# %% +# In fact, that list may contain any valid +# :ref:`Matplotlib color specification `. +# Particularly useful for creating custom colormaps are (N, 4)-shaped arrays. +# Because with the variety of numpy operations that we can do on a such an +# array, carpentry of new colormaps from existing colormaps become quite +# straight forward. +# +# For example, suppose we want to make the first 25 entries of a 256-length +# "viridis" colormap pink for some reason: + +viridis = mpl.colormaps['viridis'].resampled(256) +newcolors = viridis(np.linspace(0, 1, 256)) +pink = np.array([248/256, 24/256, 148/256, 1]) +newcolors[:25, :] = pink +newcmp = ListedColormap(newcolors) + +plot_examples([viridis, newcmp]) + +# %% +# We can reduce the dynamic range of a colormap; here we choose the +# middle half of the colormap. Note, however, that because viridis is a +# listed colormap, we will end up with 128 discrete values instead of the 256 +# values that were in the original colormap. This method does not interpolate +# in color-space to add new colors. + +viridis_big = mpl.colormaps['viridis'] +newcmp = ListedColormap(viridis_big(np.linspace(0.25, 0.75, 128))) +plot_examples([viridis, newcmp]) + +# %% +# and we can easily concatenate two colormaps: + +top = mpl.colormaps['Oranges_r'].resampled(128) +bottom = mpl.colormaps['Blues'].resampled(128) + +newcolors = np.vstack((top(np.linspace(0, 1, 128)), + bottom(np.linspace(0, 1, 128)))) +newcmp = ListedColormap(newcolors, name='OrangeBlue') +plot_examples([viridis, newcmp]) + +# %% +# Of course we need not start from a named colormap, we just need to create +# the (N, 4) array to pass to `.ListedColormap`. Here we create a colormap that +# goes from brown (RGB: 90, 40, 40) to white (RGB: 255, 255, 255). + +N = 256 +vals = np.ones((N, 4)) +vals[:, 0] = np.linspace(90/256, 1, N) +vals[:, 1] = np.linspace(40/256, 1, N) +vals[:, 2] = np.linspace(40/256, 1, N) +newcmp = ListedColormap(vals) +plot_examples([viridis, newcmp]) + +# %% +# Creating linear segmented colormaps +# =================================== +# +# The `.LinearSegmentedColormap` class specifies colormaps using anchor points +# between which RGB(A) values are interpolated. +# +# The format to specify these colormaps allows discontinuities at the anchor +# points. Each anchor point is specified as a row in a matrix of the +# form ``[x[i] yleft[i] yright[i]]``, where ``x[i]`` is the anchor, and +# ``yleft[i]`` and ``yright[i]`` are the values of the color on either +# side of the anchor point. +# +# If there are no discontinuities, then ``yleft[i] == yright[i]``: + +cdict = {'red': [[0.0, 0.0, 0.0], + [0.5, 1.0, 1.0], + [1.0, 1.0, 1.0]], + 'green': [[0.0, 0.0, 0.0], + [0.25, 0.0, 0.0], + [0.75, 1.0, 1.0], + [1.0, 1.0, 1.0]], + 'blue': [[0.0, 0.0, 0.0], + [0.5, 0.0, 0.0], + [1.0, 1.0, 1.0]]} + + +def plot_linearmap(cdict): + newcmp = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256) + rgba = newcmp(np.linspace(0, 1, 256)) + fig, ax = plt.subplots(figsize=(4, 3), layout='constrained') + col = ['r', 'g', 'b'] + for xx in [0.25, 0.5, 0.75]: + ax.axvline(xx, color='0.7', linestyle='--') + for i in range(3): + ax.plot(np.arange(256)/256, rgba[:, i], color=col[i]) + ax.set_xlabel('index') + ax.set_ylabel('RGB') + plt.show() + +plot_linearmap(cdict) + +# %% +# In order to make a discontinuity at an anchor point, the third column is +# different than the second. The matrix for each of "red", "green", "blue", +# and optionally "alpha" is set up as:: +# +# cdict['red'] = [... +# [x[i] yleft[i] yright[i]], +# [x[i+1] yleft[i+1] yright[i+1]], +# ...] +# +# and for values passed to the colormap between ``x[i]`` and ``x[i+1]``, +# the interpolation is between ``yright[i]`` and ``yleft[i+1]``. +# +# In the example below there is a discontinuity in red at 0.5. The +# interpolation between 0 and 0.5 goes from 0.3 to 1, and between 0.5 and 1 +# it goes from 0.9 to 1. Note that ``red[0, 1]``, and ``red[2, 2]`` are both +# superfluous to the interpolation because ``red[0, 1]`` (i.e., ``yleft[0]``) +# is the value to the left of 0, and ``red[2, 2]`` (i.e., ``yright[2]``) is the +# value to the right of 1, which are outside the color mapping domain. + +cdict['red'] = [[0.0, 0.0, 0.3], + [0.5, 1.0, 0.9], + [1.0, 1.0, 1.0]] +plot_linearmap(cdict) + +# %% +# Directly creating a segmented colormap from a list +# -------------------------------------------------- +# +# The approach described above is very versatile, but admittedly a bit +# cumbersome to implement. For some basic cases, the use of +# `.LinearSegmentedColormap.from_list` may be easier. This creates a segmented +# colormap with equal spacings from a supplied list of colors. + +colors = ["darkorange", "gold", "lawngreen", "lightseagreen"] +cmap1 = LinearSegmentedColormap.from_list("mycmap", colors) + +# %% +# If desired, the nodes of the colormap can be given as numbers between 0 and +# 1. For example, one could have the reddish part take more space in the +# colormap. + +nodes = [0.0, 0.4, 0.8, 1.0] +cmap2 = LinearSegmentedColormap.from_list("mycmap", list(zip(nodes, colors))) + +plot_examples([cmap1, cmap2]) + +# %% +# .. _reversing-colormap: +# +# Reversing a colormap +# ==================== +# +# `.Colormap.reversed` creates a new colormap that is a reversed version of +# the original colormap. + +colors = ["#ffffcc", "#a1dab4", "#41b6c4", "#2c7fb8", "#253494"] +my_cmap = ListedColormap(colors, name="my_cmap") + +my_cmap_r = my_cmap.reversed() + +plot_examples([my_cmap, my_cmap_r]) +# %% +# If no name is passed in, ``.reversed`` also names the copy by +# :ref:`appending '_r' ` to the original colormap's +# name. + +# %% +# .. _registering-colormap: +# +# Registering a colormap +# ====================== +# +# Colormaps can be added to the `matplotlib.colormaps` list of named colormaps. +# This allows the colormaps to be accessed by name in plotting functions: + +# my_cmap, my_cmap_r from reversing a colormap +mpl.colormaps.register(cmap=my_cmap) +mpl.colormaps.register(cmap=my_cmap_r) + +data = [[1, 2, 3, 4, 5]] + +fig, (ax1, ax2) = plt.subplots(nrows=2) + +ax1.imshow(data, cmap='my_cmap') +ax2.imshow(data, cmap='my_cmap_r') + +plt.show() + +# %% +# +# .. admonition:: References +# +# The use of the following functions, methods, classes and modules is shown +# in this example: +# +# - `matplotlib.axes.Axes.pcolormesh` +# - `matplotlib.figure.Figure.colorbar` +# - `matplotlib.colors` +# - `matplotlib.colors.LinearSegmentedColormap` +# - `matplotlib.colors.ListedColormap` +# - `matplotlib.cm` +# - `matplotlib.colormaps` diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormapnorms.py b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormapnorms.py new file mode 100644 index 0000000000000000000000000000000000000000..f375b3af805bec00d46623453c0797a1ab3e551e --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormapnorms.py @@ -0,0 +1,349 @@ +""" + +.. redirect-from:: /tutorials/colors/colormapnorms + +.. _colormapnorms: + +Colormap Normalization +====================== + +Objects that use colormaps by default linearly map the colors in the +colormap from data values *vmin* to *vmax*. For example:: + + pcm = ax.pcolormesh(x, y, Z, vmin=-1., vmax=1., cmap='RdBu_r') + +will map the data in *Z* linearly from -1 to +1, so *Z=0* will +give a color at the center of the colormap *RdBu_r* (white in this +case). + +Matplotlib does this mapping in two steps, with a normalization from +the input data to [0, 1] occurring first, and then mapping onto the +indices in the colormap. Normalizations are classes defined in the +:func:`matplotlib.colors` module. The default, linear normalization +is :func:`matplotlib.colors.Normalize`. + +Artists that map data to color pass the arguments *vmin* and *vmax* to +construct a :func:`matplotlib.colors.Normalize` instance, then call it: + +.. code-block:: pycon + + >>> import matplotlib as mpl + >>> norm = mpl.colors.Normalize(vmin=-1, vmax=1) + >>> norm(0) + 0.5 + +However, there are sometimes cases where it is useful to map data to +colormaps in a non-linear fashion. + +Logarithmic +----------- + +One of the most common transformations is to plot data by taking its logarithm +(to the base-10). This transformation is useful to display changes across +disparate scales. Using `.colors.LogNorm` normalizes the data via +:math:`log_{10}`. In the example below, there are two bumps, one much smaller +than the other. Using `.colors.LogNorm`, the shape and location of each bump +can clearly be seen: + +""" +import matplotlib.pyplot as plt +import numpy as np + +from matplotlib import cm +import matplotlib.cbook as cbook +import matplotlib.colors as colors + +N = 100 +X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] + +# A low hump with a spike coming out of the top right. Needs to have +# z/colour axis on a log scale, so we see both hump and spike. A linear +# scale only shows the spike. +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) +Z = Z1 + 50 * Z2 + +fig, ax = plt.subplots(2, 1) + +pcm = ax[0].pcolor(X, Y, Z, + norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()), + cmap='PuBu_r', shading='auto') +fig.colorbar(pcm, ax=ax[0], extend='max') + +pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='auto') +fig.colorbar(pcm, ax=ax[1], extend='max') +plt.show() + +# %% +# Centered +# -------- +# +# In many cases, data is symmetrical around a center, for example, positive and +# negative anomalies around a center 0. In this case, we would like the center +# to be mapped to 0.5 and the datapoint with the largest deviation from the +# center to be mapped to 1.0, if its value is greater than the center, or 0.0 +# otherwise. The norm `.colors.CenteredNorm` creates such a mapping +# automatically. It is well suited to be combined with a divergent colormap +# which uses different colors edges that meet in the center at an unsaturated +# color. +# +# If the center of symmetry is different from 0, it can be set with the +# *vcenter* argument. For logarithmic scaling on both sides of the center, see +# `.colors.SymLogNorm` below; to apply a different mapping above and below the +# center, use `.colors.TwoSlopeNorm` below. + +delta = 0.1 +x = np.arange(-3.0, 4.001, delta) +y = np.arange(-4.0, 3.001, delta) +X, Y = np.meshgrid(x, y) +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (0.9*Z1 - 0.5*Z2) * 2 + +# select a divergent colormap +cmap = cm.coolwarm + +fig, (ax1, ax2) = plt.subplots(ncols=2) +pc = ax1.pcolormesh(Z, cmap=cmap) +fig.colorbar(pc, ax=ax1) +ax1.set_title('Normalize()') + +pc = ax2.pcolormesh(Z, norm=colors.CenteredNorm(), cmap=cmap) +fig.colorbar(pc, ax=ax2) +ax2.set_title('CenteredNorm()') + +plt.show() + +# %% +# Symmetric logarithmic +# --------------------- +# +# Similarly, it sometimes happens that there is data that is positive +# and negative, but we would still like a logarithmic scaling applied to +# both. In this case, the negative numbers are also scaled +# logarithmically, and mapped to smaller numbers; e.g., if ``vmin=-vmax``, +# then the negative numbers are mapped from 0 to 0.5 and the +# positive from 0.5 to 1. +# +# Since the logarithm of values close to zero tends toward infinity, a +# small range around zero needs to be mapped linearly. The parameter +# *linthresh* allows the user to specify the size of this range +# (-*linthresh*, *linthresh*). The size of this range in the colormap is +# set by *linscale*. When *linscale* == 1.0 (the default), the space used +# for the positive and negative halves of the linear range will be equal +# to one decade in the logarithmic range. + +N = 100 +X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 + +fig, ax = plt.subplots(2, 1) + +pcm = ax[0].pcolormesh(X, Y, Z, + norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, + vmin=-1.0, vmax=1.0, base=10), + cmap='RdBu_r', shading='auto') +fig.colorbar(pcm, ax=ax[0], extend='both') + +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z), shading='auto') +fig.colorbar(pcm, ax=ax[1], extend='both') +plt.show() + +# %% +# Power-law +# --------- +# +# Sometimes it is useful to remap the colors onto a power-law +# relationship (i.e. :math:`y=x^{\gamma}`, where :math:`\gamma` is the +# power). For this we use the `.colors.PowerNorm`. It takes as an +# argument *gamma* (*gamma* == 1.0 will just yield the default linear +# normalization): +# +# .. note:: +# +# There should probably be a good reason for plotting the data using +# this type of transformation. Technical viewers are used to linear +# and logarithmic axes and data transformations. Power laws are less +# common, and viewers should explicitly be made aware that they have +# been used. + +N = 100 +X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] +Z1 = (1 + np.sin(Y * 10.)) * X**2 + +fig, ax = plt.subplots(2, 1, layout='constrained') + +pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=0.5), + cmap='PuBu_r', shading='auto') +fig.colorbar(pcm, ax=ax[0], extend='max') +ax[0].set_title('PowerNorm()') + +pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r', shading='auto') +fig.colorbar(pcm, ax=ax[1], extend='max') +ax[1].set_title('Normalize()') +plt.show() + +# %% +# Discrete bounds +# --------------- +# +# Another normalization that comes with Matplotlib is `.colors.BoundaryNorm`. +# In addition to *vmin* and *vmax*, this takes as arguments boundaries between +# which data is to be mapped. The colors are then linearly distributed between +# these "bounds". It can also take an *extend* argument to add upper and/or +# lower out-of-bounds values to the range over which the colors are +# distributed. For instance: +# +# .. code-block:: pycon +# +# >>> import matplotlib.colors as colors +# >>> bounds = np.array([-0.25, -0.125, 0, 0.5, 1]) +# >>> norm = colors.BoundaryNorm(boundaries=bounds, ncolors=4) +# >>> print(norm([-0.2, -0.15, -0.02, 0.3, 0.8, 0.99])) +# [0 0 1 2 3 3] +# +# Note: Unlike the other norms, this norm returns values from 0 to *ncolors*-1. + +N = 100 +X, Y = np.meshgrid(np.linspace(-3, 3, N), np.linspace(-2, 2, N)) +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = ((Z1 - Z2) * 2)[:-1, :-1] + +fig, ax = plt.subplots(2, 2, figsize=(8, 6), layout='constrained') +ax = ax.flatten() + +# Default norm: +pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r') +fig.colorbar(pcm, ax=ax[0], orientation='vertical') +ax[0].set_title('Default norm') + +# Even bounds give a contour-like effect: +bounds = np.linspace(-1.5, 1.5, 7) +norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) +pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') +fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') +ax[1].set_title('BoundaryNorm: 7 boundaries') + +# Bounds may be unevenly spaced: +bounds = np.array([-0.2, -0.1, 0, 0.5, 1]) +norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) +pcm = ax[2].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') +fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') +ax[2].set_title('BoundaryNorm: nonuniform') + +# With out-of-bounds colors: +bounds = np.linspace(-1.5, 1.5, 7) +norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256, extend='both') +pcm = ax[3].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') +# The colorbar inherits the "extend" argument from BoundaryNorm. +fig.colorbar(pcm, ax=ax[3], orientation='vertical') +ax[3].set_title('BoundaryNorm: extend="both"') +plt.show() + +# %% +# TwoSlopeNorm: Different mapping on either side of a center +# ---------------------------------------------------------- +# +# Sometimes we want to have a different colormap on either side of a +# conceptual center point, and we want those two colormaps to have +# different linear scales. An example is a topographic map where the land +# and ocean have a center at zero, but land typically has a greater +# elevation range than the water has depth range, and they are often +# represented by a different colormap. + +dem = cbook.get_sample_data('topobathy.npz') +topo = dem['topo'] +longitude = dem['longitude'] +latitude = dem['latitude'] + +fig, ax = plt.subplots() +# make a colormap that has land and ocean clearly delineated and of the +# same length (256 + 256) +colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256)) +colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256)) +all_colors = np.vstack((colors_undersea, colors_land)) +terrain_map = colors.LinearSegmentedColormap.from_list( + 'terrain_map', all_colors) + +# make the norm: Note the center is offset so that the land has more +# dynamic range: +divnorm = colors.TwoSlopeNorm(vmin=-500., vcenter=0, vmax=4000) + +pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=divnorm, + cmap=terrain_map, shading='auto') +# Simple geographic plot, set aspect ratio because distance between lines of +# longitude depends on latitude. +ax.set_aspect(1 / np.cos(np.deg2rad(49))) +ax.set_title('TwoSlopeNorm(x)') +cb = fig.colorbar(pcm, shrink=0.6) +cb.set_ticks([-500, 0, 1000, 2000, 3000, 4000]) +plt.show() + + +# %% +# FuncNorm: Arbitrary function normalization +# ------------------------------------------ +# +# If the above norms do not provide the normalization you want, you can use +# `~.colors.FuncNorm` to define your own. Note that this example is the same +# as `~.colors.PowerNorm` with a power of 0.5: + +def _forward(x): + return np.sqrt(x) + + +def _inverse(x): + return x**2 + +N = 100 +X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] +Z1 = (1 + np.sin(Y * 10.)) * X**2 +fig, ax = plt.subplots() + +norm = colors.FuncNorm((_forward, _inverse), vmin=0, vmax=20) +pcm = ax.pcolormesh(X, Y, Z1, norm=norm, cmap='PuBu_r', shading='auto') +ax.set_title('FuncNorm(x)') +fig.colorbar(pcm, shrink=0.6) +plt.show() + +# %% +# Custom normalization: Manually implement two linear ranges +# ---------------------------------------------------------- +# +# The `.TwoSlopeNorm` described above makes a useful example for +# defining your own norm. Note for the colorbar to work, you must +# define an inverse for your norm: + + +class MidpointNormalize(colors.Normalize): + def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False): + self.vcenter = vcenter + super().__init__(vmin, vmax, clip) + + def __call__(self, value, clip=None): + # I'm ignoring masked values and all kinds of edge cases to make a + # simple example... + # Note also that we must extrapolate beyond vmin/vmax + x, y = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1.] + return np.ma.masked_array(np.interp(value, x, y, + left=-np.inf, right=np.inf)) + + def inverse(self, value): + y, x = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1] + return np.interp(value, x, y, left=-np.inf, right=np.inf) + + +fig, ax = plt.subplots() +midnorm = MidpointNormalize(vmin=-500., vcenter=0, vmax=4000) + +pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=midnorm, + cmap=terrain_map, shading='auto') +ax.set_aspect(1 / np.cos(np.deg2rad(49))) +ax.set_title('Custom norm') +cb = fig.colorbar(pcm, shrink=0.6, extend='both') +cb.set_ticks([-500, 0, 1000, 2000, 3000, 4000]) + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormaps.py b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormaps.py new file mode 100644 index 0000000000000000000000000000000000000000..a38dd2af0fc962f5db87b40a605c56b35ec11fab --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colormaps.py @@ -0,0 +1,438 @@ +""" +.. redirect-from:: /tutorials/colors/colormaps + +.. _colormaps: + +******************************** +Choosing Colormaps in Matplotlib +******************************** + +Matplotlib has a number of built-in colormaps accessible via +`.matplotlib.colormaps`. There are also external libraries that +have many extra colormaps, which can be viewed in the +`Third-party colormaps`_ section of the Matplotlib documentation. +Here we briefly discuss how to choose between the many options. For +help on creating your own colormaps, see +:ref:`colormap-manipulation`. + +Overview +======== + +The idea behind choosing a good colormap is to find a good representation in 3D +colorspace for your data set. The best colormap for any given data set depends +on many things including: + +- Whether representing form or metric data ([Ware]_) + +- Your knowledge of the data set (*e.g.*, is there a critical value + from which the other values deviate?) + +- If there is an intuitive color scheme for the parameter you are plotting + +- If there is a standard in the field the audience may be expecting + +For many applications, a perceptually uniform colormap is the best choice; +i.e. a colormap in which equal steps in data are perceived as equal +steps in the color space. Researchers have found that the human brain +perceives changes in the lightness parameter as changes in the data +much better than, for example, changes in hue. Therefore, colormaps +which have monotonically increasing lightness through the colormap +will be better interpreted by the viewer. Wonderful examples of +perceptually uniform colormaps can be found in the +`Third-party colormaps`_ section as well. + +Color can be represented in 3D space in various ways. One way to represent color +is using CIELAB. In CIELAB, color space is represented by lightness, +:math:`L^*`; red-green, :math:`a^*`; and yellow-blue, :math:`b^*`. The lightness +parameter :math:`L^*` can then be used to learn more about how the matplotlib +colormaps will be perceived by viewers. + +An excellent starting resource for learning about human perception of colormaps +is from [IBM]_. + + +.. _color-colormaps_reference: + +Classes of colormaps +==================== + +Colormaps are often split into several categories based on their function (see, +*e.g.*, [Moreland]_): + +1. Sequential: change in lightness and often saturation of color + incrementally, often using a single hue; should be used for + representing information that has ordering. + +2. Diverging: change in lightness and possibly saturation of two + different colors that meet in the middle at an unsaturated color; + should be used when the information being plotted has a critical + middle value, such as topography or when the data deviates around + zero. + +3. Cyclic: change in lightness of two different colors that meet in + the middle and beginning/end at an unsaturated color; should be + used for values that wrap around at the endpoints, such as phase + angle, wind direction, or time of day. + +4. Qualitative: often are miscellaneous colors; should be used to + represent information which does not have ordering or + relationships. +""" + +# sphinx_gallery_thumbnail_number = 2 + +from colorspacious import cspace_converter + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib as mpl + +# %% +# +# First, we'll show the range of each colormap. Note that some seem +# to change more "quickly" than others. + +cmaps = {} + +gradient = np.linspace(0, 1, 256) +gradient = np.vstack((gradient, gradient)) + + +def plot_color_gradients(category, cmap_list): + # Create figure and adjust figure height to number of colormaps + nrows = len(cmap_list) + figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22 + fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh)) + fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, + left=0.2, right=0.99) + axs[0].set_title(f'{category} colormaps', fontsize=14) + + for ax, name in zip(axs, cmap_list): + ax.imshow(gradient, aspect='auto', cmap=mpl.colormaps[name]) + ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10, + transform=ax.transAxes) + + # Turn off *all* ticks & spines, not just the ones with colormaps. + for ax in axs: + ax.set_axis_off() + + # Save colormap list for later. + cmaps[category] = cmap_list + + +# %% +# Sequential +# ---------- +# +# For the Sequential plots, the lightness value increases monotonically through +# the colormaps. This is good. Some of the :math:`L^*` values in the colormaps +# span from 0 to 100 (binary and the other grayscale), and others start around +# :math:`L^*=20`. Those that have a smaller range of :math:`L^*` will accordingly +# have a smaller perceptual range. Note also that the :math:`L^*` function varies +# amongst the colormaps: some are approximately linear in :math:`L^*` and others +# are more curved. + +plot_color_gradients('Perceptually Uniform Sequential', + ['viridis', 'plasma', 'inferno', 'magma', 'cividis']) + +# %% + +plot_color_gradients('Sequential', + ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', + 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', + 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']) + +# %% +# Sequential2 +# ----------- +# +# Many of the :math:`L^*` values from the Sequential2 plots are monotonically +# increasing, but some (autumn, cool, spring, and winter) plateau or even go both +# up and down in :math:`L^*` space. Others (afmhot, copper, gist_heat, and hot) +# have kinks in the :math:`L^*` functions. Data that is being represented in a +# region of the colormap that is at a plateau or kink will lead to a perception of +# banding of the data in those values in the colormap (see [mycarta-banding]_ for +# an excellent example of this). + +plot_color_gradients('Sequential (2)', + ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', + 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', + 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']) + +# %% +# Diverging +# --------- +# +# For the Diverging maps, we want to have monotonically increasing :math:`L^*` +# values up to a maximum, which should be close to :math:`L^*=100`, followed by +# monotonically decreasing :math:`L^*` values. We are looking for approximately +# equal minimum :math:`L^*` values at opposite ends of the colormap. By these +# measures, BrBG and RdBu are good options. coolwarm is a good option, but it +# doesn't span a wide range of :math:`L^*` values (see grayscale section below). + +plot_color_gradients('Diverging', + ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', + 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']) + +# %% +# Cyclic +# ------ +# +# For Cyclic maps, we want to start and end on the same color, and meet a +# symmetric center point in the middle. :math:`L^*` should change monotonically +# from start to middle, and inversely from middle to end. It should be symmetric +# on the increasing and decreasing side, and only differ in hue. At the ends and +# middle, :math:`L^*` will reverse direction, which should be smoothed in +# :math:`L^*` space to reduce artifacts. See [kovesi-colormaps]_ for more +# information on the design of cyclic maps. +# +# The often-used HSV colormap is included in this set of colormaps, although it +# is not symmetric to a center point. Additionally, the :math:`L^*` values vary +# widely throughout the colormap, making it a poor choice for representing data +# for viewers to see perceptually. See an extension on this idea at +# [mycarta-jet]_. + +plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv']) + +# %% +# Qualitative +# ----------- +# +# Qualitative colormaps are not aimed at being perceptual maps, but looking at the +# lightness parameter can verify that for us. The :math:`L^*` values move all over +# the place throughout the colormap, and are clearly not monotonically increasing. +# These would not be good options for use as perceptual colormaps. + +plot_color_gradients('Qualitative', + ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', + 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', + 'tab20c']) + +# %% +# Miscellaneous +# ------------- +# +# Some of the miscellaneous colormaps have particular uses for which +# they have been created. For example, gist_earth, ocean, and terrain +# all seem to be created for plotting topography (green/brown) and water +# depths (blue) together. We would expect to see a divergence in these +# colormaps, then, but multiple kinks may not be ideal, such as in +# gist_earth and terrain. CMRmap was created to convert well to +# grayscale, though it does appear to have some small kinks in +# :math:`L^*`. cubehelix was created to vary smoothly in both lightness +# and hue, but appears to have a small hump in the green hue area. turbo +# was created to display depth and disparity data. +# +# The often-used jet colormap is included in this set of colormaps. We can see +# that the :math:`L^*` values vary widely throughout the colormap, making it a +# poor choice for representing data for viewers to see perceptually. See an +# extension on this idea at [mycarta-jet]_ and [turbo]_. + + +plot_color_gradients('Miscellaneous', + ['flag', 'prism', 'ocean', 'gist_earth', 'terrain', + 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', + 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', + 'turbo', 'nipy_spectral', 'gist_ncar']) + +plt.show() + +# %% +# Lightness of Matplotlib colormaps +# ================================= +# +# Here we examine the lightness values of the matplotlib colormaps. +# Note that some documentation on the colormaps is available +# ([list-colormaps]_). + +mpl.rcParams.update({'font.size': 12}) + +# Number of colormap per subplot for particular cmap categories +_DSUBS = {'Perceptually Uniform Sequential': 5, 'Sequential': 6, + 'Sequential (2)': 6, 'Diverging': 6, 'Cyclic': 3, + 'Qualitative': 4, 'Miscellaneous': 6} + +# Spacing between the colormaps of a subplot +_DC = {'Perceptually Uniform Sequential': 1.4, 'Sequential': 0.7, + 'Sequential (2)': 1.4, 'Diverging': 1.4, 'Cyclic': 1.4, + 'Qualitative': 1.4, 'Miscellaneous': 1.4} + +# Indices to step through colormap +x = np.linspace(0.0, 1.0, 100) + +# Do plot +for cmap_category, cmap_list in cmaps.items(): + + # Do subplots so that colormaps have enough space. + # Default is 6 colormaps per subplot. + dsub = _DSUBS.get(cmap_category, 6) + nsubplots = int(np.ceil(len(cmap_list) / dsub)) + + # squeeze=False to handle similarly the case of a single subplot + fig, axs = plt.subplots(nrows=nsubplots, squeeze=False, + figsize=(7, 2.6*nsubplots)) + + for i, ax in enumerate(axs.flat): + + locs = [] # locations for text labels + + for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]): + + # Get RGB values for colormap and convert the colormap in + # CAM02-UCS colorspace. lab[0, :, 0] is the lightness. + rgb = mpl.colormaps[cmap](x)[np.newaxis, :, :3] + lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb) + + # Plot colormap L values. Do separately for each category + # so each plot can be pretty. To make scatter markers change + # color along plot: + # https://stackoverflow.com/q/8202605/ + + if cmap_category == 'Sequential': + # These colormaps all start at high lightness, but we want them + # reversed to look nice in the plot, so reverse the order. + y_ = lab[0, ::-1, 0] + c_ = x[::-1] + else: + y_ = lab[0, :, 0] + c_ = x + + dc = _DC.get(cmap_category, 1.4) # cmaps horizontal spacing + ax.scatter(x + j*dc, y_, c=c_, cmap=cmap, s=300, linewidths=0.0) + + # Store locations for colormap labels + if cmap_category in ('Perceptually Uniform Sequential', + 'Sequential'): + locs.append(x[-1] + j*dc) + elif cmap_category in ('Diverging', 'Qualitative', 'Cyclic', + 'Miscellaneous', 'Sequential (2)'): + locs.append(x[int(x.size/2.)] + j*dc) + + # Set up the axis limits: + # * the 1st subplot is used as a reference for the x-axis limits + # * lightness values goes from 0 to 100 (y-axis limits) + ax.set_xlim(axs[0, 0].get_xlim()) + ax.set_ylim(0.0, 100.0) + + # Set up labels for colormaps + ax.xaxis.set_ticks_position('top') + ticker = mpl.ticker.FixedLocator(locs) + ax.xaxis.set_major_locator(ticker) + formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub]) + ax.xaxis.set_major_formatter(formatter) + ax.xaxis.set_tick_params(rotation=50) + ax.set_ylabel('Lightness $L^*$', fontsize=12) + + ax.set_xlabel(cmap_category + ' colormaps', fontsize=14) + + fig.tight_layout(h_pad=0.0, pad=1.5) + plt.show() + + +# %% +# Grayscale conversion +# ==================== +# +# It is important to pay attention to conversion to grayscale for color +# plots, since they may be printed on black and white printers. If not +# carefully considered, your readers may end up with indecipherable +# plots because the grayscale changes unpredictably through the +# colormap. +# +# Conversion to grayscale is done in many different ways [bw]_. Some of the +# better ones use a linear combination of the rgb values of a pixel, but +# weighted according to how we perceive color intensity. A nonlinear method of +# conversion to grayscale is to use the :math:`L^*` values of the pixels. In +# general, similar principles apply for this question as they do for presenting +# one's information perceptually; that is, if a colormap is chosen that is +# monotonically increasing in :math:`L^*` values, it will print in a reasonable +# manner to grayscale. +# +# With this in mind, we see that the Sequential colormaps have reasonable +# representations in grayscale. Some of the Sequential2 colormaps have decent +# enough grayscale representations, though some (autumn, spring, summer, +# winter) have very little grayscale change. If a colormap like this was used +# in a plot and then the plot was printed to grayscale, a lot of the +# information may map to the same gray values. The Diverging colormaps mostly +# vary from darker gray on the outer edges to white in the middle. Some +# (PuOr and seismic) have noticeably darker gray on one side than the other +# and therefore are not very symmetric. coolwarm has little range of gray scale +# and would print to a more uniform plot, losing a lot of detail. Note that +# overlaid, labeled contours could help differentiate between one side of the +# colormap vs. the other since color cannot be used once a plot is printed to +# grayscale. Many of the Qualitative and Miscellaneous colormaps, such as +# Accent, hsv, jet and turbo, change from darker to lighter and back to darker +# grey throughout the colormap. This would make it impossible for a viewer to +# interpret the information in a plot once it is printed in grayscale. + +mpl.rcParams.update({'font.size': 14}) + +# Indices to step through colormap. +x = np.linspace(0.0, 1.0, 100) + +gradient = np.linspace(0, 1, 256) +gradient = np.vstack((gradient, gradient)) + + +def plot_color_gradients(cmap_category, cmap_list): + fig, axs = plt.subplots(nrows=len(cmap_list), ncols=2) + fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, + wspace=0.05) + fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6) + + for ax, name in zip(axs, cmap_list): + + # Get RGB values for colormap. + rgb = mpl.colormaps[name](x)[np.newaxis, :, :3] + + # Get colormap in CAM02-UCS colorspace. We want the lightness. + lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb) + L = lab[0, :, 0] + L = np.float32(np.vstack((L, L, L))) + + ax[0].imshow(gradient, aspect='auto', cmap=mpl.colormaps[name]) + ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.) + pos = list(ax[0].get_position().bounds) + x_text = pos[0] - 0.01 + y_text = pos[1] + pos[3]/2. + fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) + + # Turn off *all* ticks & spines, not just the ones with colormaps. + for ax in axs.flat: + ax.set_axis_off() + + plt.show() + + +for cmap_category, cmap_list in cmaps.items(): + + plot_color_gradients(cmap_category, cmap_list) + +# %% +# Color vision deficiencies +# ========================= +# +# There is a lot of information available about color blindness (*e.g.*, +# [colorblindness]_). Additionally, there are tools available to convert images +# to how they look for different types of color vision deficiencies. +# +# The most common form of color vision deficiency involves differentiating +# between red and green. Thus, avoiding colormaps with both red and green will +# avoid many problems in general. +# +# +# References +# ========== +# +# .. _Third-party colormaps: https://matplotlib.org/mpl-third-party/#colormaps-and-styles +# .. [Ware] http://ccom.unh.edu/sites/default/files/publications/Ware_1988_CGA_Color_sequences_univariate_maps.pdf +# .. [Moreland] http://www.kennethmoreland.com/color-maps/ColorMapsExpanded.pdf +# .. [list-colormaps] https://gist.github.com/endolith/2719900#id7 +# .. [mycarta-banding] https://mycarta.wordpress.com/2012/10/14/the-rainbow-is-deadlong-live-the-rainbow-part-4-cie-lab-heated-body/ +# .. [mycarta-jet] https://mycarta.wordpress.com/2012/10/06/the-rainbow-is-deadlong-live-the-rainbow-part-3/ +# .. [kovesi-colormaps] https://arxiv.org/abs/1509.03700 +# .. [bw] https://tannerhelland.com/3643/grayscale-image-algorithm-vb6/ +# .. [colorblindness] http://www.color-blindness.com/ +# .. [IBM] https://doi.org/10.1109/VISUAL.1995.480803 +# .. [turbo] https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colors.py b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6a3832b75c6d51f276ef8280695d1d4e08f3e8 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/colors/colors.py @@ -0,0 +1,231 @@ +""" +.. redirect-from:: /tutorials/colors/colors + +.. _colors_def: + +***************** +Specifying colors +***************** + +Color formats +============= + +Matplotlib recognizes the following formats to specify a color. + ++--------------------------------------+--------------------------------------+ +| Format | Example | ++======================================+======================================+ +| RGB or RGBA (red, green, blue, alpha)| - ``(0.1, 0.2, 0.5)`` | +| tuple of float values in a closed | - ``(0.1, 0.2, 0.5, 0.3)`` | +| interval [0, 1]. | | ++--------------------------------------+--------------------------------------+ +| Case-insensitive hex RGB or RGBA | - ``'#0f0f0f'`` | +| string. | - ``'#0f0f0f80'`` | ++--------------------------------------+--------------------------------------+ +| Case-insensitive RGB or RGBA string | - ``'#abc'`` as ``'#aabbcc'`` | +| equivalent hex shorthand of | - ``'#fb1'`` as ``'#ffbb11'`` | +| duplicated characters. | | ++--------------------------------------+--------------------------------------+ +| String representation of float value | - ``'0'`` as black | +| in closed interval ``[0, 1]`` for | - ``'1'`` as white | +| grayscale values. | - ``'0.8'`` as light gray | ++--------------------------------------+--------------------------------------+ +| Single character shorthand notation | - ``'b'`` as blue | +| for some basic colors. | - ``'g'`` as green | +| | - ``'r'`` as red | +| .. note:: | - ``'c'`` as cyan | +| The colors green, cyan, magenta, | - ``'m'`` as magenta | +| and yellow do not coincide with | - ``'y'`` as yellow | +| X11/CSS4 colors. Their particular | - ``'k'`` as black | +| shades were chosen for better | - ``'w'`` as white | +| visibility of colored lines | | +| against typical backgrounds. | | ++--------------------------------------+--------------------------------------+ +| Case-insensitive X11/CSS4 color name | - ``'aquamarine'`` | +| with no spaces. | - ``'mediumseagreen'`` | ++--------------------------------------+--------------------------------------+ +| Case-insensitive color name from | - ``'xkcd:sky blue'`` | +| `xkcd color survey`_ with ``'xkcd:'``| - ``'xkcd:eggshell'`` | +| prefix. | | ++--------------------------------------+--------------------------------------+ +| Case-insensitive Tableau Colors from | - ``'tab:blue'`` | +| 'T10' categorical palette. | - ``'tab:orange'`` | +| | - ``'tab:green'`` | +| | - ``'tab:red'`` | +| | - ``'tab:purple'`` | +| .. note:: This is the default color | - ``'tab:brown'`` | +| cycle. | - ``'tab:pink'`` | +| | - ``'tab:gray'`` | +| | - ``'tab:olive'`` | +| | - ``'tab:cyan'`` | ++--------------------------------------+--------------------------------------+ +| "CN" color spec where ``'C'`` | - ``'C0'`` | +| precedes a number acting as an index | - ``'C1'`` | +| into the default property cycle. +--------------------------------------+ +| | :rc:`axes.prop_cycle` | +| .. note:: Matplotlib indexes color | | +| at draw time and defaults | | +| to black if cycle does not | | +| include color. | | ++--------------------------------------+--------------------------------------+ +| Tuple of one of the above color | - ``('green', 0.3)`` | +| formats and an alpha float. | - ``('#f00', 0.9)`` | +| | | +| .. versionadded:: 3.8 | | ++--------------------------------------+--------------------------------------+ + +.. _xkcd color survey: https://xkcd.com/color/rgb/ + +.. seealso:: + + The following links provide more information on colors in Matplotlib. + * :doc:`/gallery/color/color_demo` Example + * `matplotlib.colors` API + * :doc:`/gallery/color/named_colors` Example + +"Red", "Green", and "Blue" are the intensities of those colors. In combination, +they represent the colorspace. + +Transparency +============ + +The *alpha* value of a color specifies its transparency, where 0 is fully +transparent and 1 is fully opaque. When a color is semi-transparent, the +background color will show through. + +The *alpha* value determines the resulting color by blending the +foreground color with the background color according to the formula + +.. math:: + + RGB_{result} = RGB_{background} * (1 - \\alpha) + RGB_{foreground} * \\alpha + +The following plot illustrates the effect of transparency. +""" + +import matplotlib.pyplot as plt +import numpy as np + +from matplotlib.patches import Rectangle + +fig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained') +ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8)) +for i, alpha in enumerate(np.linspace(0, 1, 11)): + ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0)) + ax.text(i+0.4, 0.85, f"{alpha:.1f}", ha='center') + ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2)) +ax.set_xlim(-0.2, 13) +ax.set_ylim(-1, 1) +ax.set_title('alpha values') +ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0') +ax.text(11.3, 0, 'zorder=2\nalpha=0.8', va='center', color='C1') +ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0') +ax.axis('off') + + +# %% +# +# The orange rectangle is semi-transparent with *alpha* = 0.8. The top row of +# blue squares is drawn below and the bottom row of blue squares is drawn on +# top of the orange rectangle. +# +# See also :doc:`/gallery/misc/zorder_demo` to learn more on the drawing order. +# +# +# "CN" color selection +# ==================== +# +# Matplotlib converts "CN" colors to RGBA when drawing Artists. The +# :ref:`color_cycle` section contains additional +# information about controlling colors and style properties. + + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib as mpl + +th = np.linspace(0, 2*np.pi, 128) + + +def demo(sty): + mpl.style.use(sty) + fig, ax = plt.subplots(figsize=(3, 3)) + + ax.set_title(f'style: {sty!r}', color='C0') + + ax.plot(th, np.cos(th), 'C1', label='C1') + ax.plot(th, np.sin(th), 'C2', label='C2') + ax.legend() + + +demo('default') +demo('seaborn-v0_8') + +# %% +# The first color ``'C0'`` is the title. Each plot uses the second and third +# colors of each style's :rc:`axes.prop_cycle`. They are ``'C1'`` and ``'C2'``, +# respectively. +# +# .. _xkcd-colors: +# +# Comparison between X11/CSS4 and xkcd colors +# =========================================== +# +# The xkcd colors come from a `user survey conducted by the webcomic xkcd +# `__. +# +# 95 out of the 148 X11/CSS4 color names also appear in the xkcd color survey. +# Almost all of them map to different color values in the X11/CSS4 and in +# the xkcd palette. Only 'black', 'white' and 'cyan' are identical. +# +# For example, ``'blue'`` maps to ``'#0000FF'`` whereas ``'xkcd:blue'`` maps to +# ``'#0343DF'``. Due to these name collisions, all xkcd colors have the +# ``'xkcd:'`` prefix. +# +# The visual below shows name collisions. Color names where color values agree +# are in bold. + +import matplotlib.colors as mcolors +import matplotlib.patches as mpatch + +overlap = {name for name in mcolors.CSS4_COLORS + if f'xkcd:{name}' in mcolors.XKCD_COLORS} + +fig = plt.figure(figsize=[9, 5]) +ax = fig.add_axes([0, 0, 1, 1]) + +n_groups = 3 +n_rows = len(overlap) // n_groups + 1 + +for j, color_name in enumerate(sorted(overlap)): + css4 = mcolors.CSS4_COLORS[color_name] + xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper() + + # Pick text colour based on perceived luminance. + rgba = mcolors.to_rgba_array([css4, xkcd]) + luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] + css4_text_color = 'k' if luma[0] > 0.5 else 'w' + xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' + + col_shift = (j // n_rows) * 3 + y_pos = j % n_rows + text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) + ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) + ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) + ax.text(0.5 + col_shift, y_pos + .7, css4, + color=css4_text_color, ha='center', **text_args) + ax.text(1.5 + col_shift, y_pos + .7, xkcd, + color=xkcd_text_color, ha='center', **text_args) + ax.text(2 + col_shift, y_pos + .7, f' {color_name}', **text_args) + +for g in range(n_groups): + ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1) + ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center') + ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center') + +ax.set_xlim(0, 3 * n_groups) +ax.set_ylim(n_rows, -1) +ax.axis('off') + +plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/customizing.py b/testbed/matplotlib__matplotlib/galleries/users_explain/customizing.py new file mode 100644 index 0000000000000000000000000000000000000000..58eccbcfa960e7426a89b591921482e34f708fcf --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/customizing.py @@ -0,0 +1,269 @@ +""" +.. redirect-from:: /users/customizing +.. redirect-from:: /tutorials/introductory/customizing + +.. _customizing: + +===================================================== +Customizing Matplotlib with style sheets and rcParams +===================================================== + +Tips for customizing the properties and default styles of Matplotlib. + +There are three ways to customize Matplotlib: + +1. :ref:`Setting rcParams at runtime`. +2. :ref:`Using style sheets`. +3. :ref:`Changing your matplotlibrc file`. + +Setting rcParams at runtime takes precedence over style sheets, style +sheets take precedence over :file:`matplotlibrc` files. + +.. _customizing-with-dynamic-rc-settings: + +Runtime rc settings +=================== + +You can dynamically change the default rc (runtime configuration) +settings in a python script or interactively from the python shell. All +rc settings are stored in a dictionary-like variable called +:data:`matplotlib.rcParams`, which is global to the matplotlib package. +See `matplotlib.rcParams` for a full list of configurable rcParams. +rcParams can be modified directly, for example: +""" + +from cycler import cycler + +import matplotlib.pyplot as plt +import numpy as np + +import matplotlib as mpl + +mpl.rcParams['lines.linewidth'] = 2 +mpl.rcParams['lines.linestyle'] = '--' +data = np.random.randn(50) +plt.plot(data) + +# %% +# Note, that in order to change the usual `~.Axes.plot` color you have to +# change the *prop_cycle* property of *axes*: + +mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']) +plt.plot(data) # first color is red + +# %% +# Matplotlib also provides a couple of convenience functions for modifying rc +# settings. `matplotlib.rc` can be used to modify multiple +# settings in a single group at once, using keyword arguments: + +mpl.rc('lines', linewidth=4, linestyle='-.') +plt.plot(data) + +# %% +# Temporary rc settings +# --------------------- +# +# The :data:`matplotlib.rcParams` object can also be changed temporarily using +# the `matplotlib.rc_context` context manager: + +with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}): + plt.plot(data) + +# %% +# `matplotlib.rc_context` can also be used as a decorator to modify the +# defaults within a function: + + +@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'}) +def plotting_function(): + plt.plot(data) + +plotting_function() + +# %% +# `matplotlib.rcdefaults` will restore the standard Matplotlib +# default settings. +# +# There is some degree of validation when setting the values of rcParams, see +# :mod:`matplotlib.rcsetup` for details. + +# %% +# .. _customizing-with-style-sheets: +# +# Using style sheets +# ================== +# +# Another way to change the visual appearance of plots is to set the +# rcParams in a so-called style sheet and import that style sheet with +# `matplotlib.style.use`. In this way you can switch easily between +# different styles by simply changing the imported style sheet. A style +# sheets looks the same as a :ref:`matplotlibrc` +# file, but in a style sheet you can only set rcParams that are related +# to the actual style of a plot. Other rcParams, like *backend*, will be +# ignored. :file:`matplotlibrc` files support all rcParams. The +# rationale behind this is to make style sheets portable between +# different machines without having to worry about dependencies which +# might or might not be installed on another machine. For a full list of +# rcParams see `matplotlib.rcParams`. For a list of rcParams that are +# ignored in style sheets see `matplotlib.style.use`. +# +# There are a number of pre-defined styles :doc:`provided by Matplotlib +# `. For +# example, there's a pre-defined style called "ggplot", which emulates the +# aesthetics of ggplot_ (a popular plotting package for R_). To use this +# style, add: + +plt.style.use('ggplot') + +# %% +# To list all available styles, use: + +print(plt.style.available) + +# %% +# Defining your own style +# ----------------------- +# +# You can create custom styles and use them by calling `.style.use` with +# the path or URL to the style sheet. +# +# For example, you might want to create +# ``./images/presentation.mplstyle`` with the following:: +# +# axes.titlesize : 24 +# axes.labelsize : 20 +# lines.linewidth : 3 +# lines.markersize : 10 +# xtick.labelsize : 16 +# ytick.labelsize : 16 +# +# Then, when you want to adapt a plot designed for a paper to one that looks +# good in a presentation, you can just add:: +# +# >>> import matplotlib.pyplot as plt +# >>> plt.style.use('./images/presentation.mplstyle') +# +# +# Distributing styles +# ------------------- +# +# You can include style sheets into standard importable Python packages (which +# can be e.g. distributed on PyPI). If your package is importable as +# ``import mypackage``, with a ``mypackage/__init__.py`` module, and you add +# a ``mypackage/presentation.mplstyle`` style sheet, then it can be used as +# ``plt.style.use("mypackage.presentation")``. Subpackages (e.g. +# ``dotted.package.name``) are also supported. +# +# Alternatively, you can make your style known to Matplotlib by placing +# your ``.mplstyle`` file into ``mpl_configdir/stylelib``. You +# can then load your custom style sheet with a call to +# ``style.use()``. By default ``mpl_configdir`` should be +# ``~/.config/matplotlib``, but you can check where yours is with +# `matplotlib.get_configdir()`; you may need to create this directory. You +# also can change the directory where Matplotlib looks for the stylelib/ +# folder by setting the :envvar:`MPLCONFIGDIR` environment variable, see +# :ref:`locating-matplotlib-config-dir`. +# +# Note that a custom style sheet in ``mpl_configdir/stylelib`` will override a +# style sheet defined by Matplotlib if the styles have the same name. +# +# Once your ``.mplstyle`` file is in the appropriate +# ``mpl_configdir`` you can specify your style with:: +# +# >>> import matplotlib.pyplot as plt +# >>> plt.style.use() +# +# +# Composing styles +# ---------------- +# +# Style sheets are designed to be composed together. So you can have a style +# sheet that customizes colors and a separate style sheet that alters element +# sizes for presentations. These styles can easily be combined by passing +# a list of styles:: +# +# >>> import matplotlib.pyplot as plt +# >>> plt.style.use(['dark_background', 'presentation']) +# +# Note that styles further to the right will overwrite values that are already +# defined by styles on the left. +# +# +# Temporary styling +# ----------------- +# +# If you only want to use a style for a specific block of code but don't want +# to change the global styling, the style package provides a context manager +# for limiting your changes to a specific scope. To isolate your styling +# changes, you can write something like the following: + +with plt.style.context('dark_background'): + plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') +plt.show() + +# %% +# .. _customizing-with-matplotlibrc-files: +# +# The :file:`matplotlibrc` file +# ============================= +# +# Matplotlib uses :file:`matplotlibrc` configuration files to customize all +# kinds of properties, which we call 'rc settings' or 'rc parameters'. You can +# control the defaults of almost every property in Matplotlib: figure size and +# DPI, line width, color and style, axes, axis and grid properties, text and +# font properties and so on. The :file:`matplotlibrc` is read at startup to +# configure Matplotlib. Matplotlib looks for :file:`matplotlibrc` in four +# locations, in the following order: +# +# 1. :file:`matplotlibrc` in the current working directory, usually used for +# specific customizations that you do not want to apply elsewhere. +# +# 2. :file:`$MATPLOTLIBRC` if it is a file, else +# :file:`$MATPLOTLIBRC/matplotlibrc`. +# +# 3. It next looks in a user-specific place, depending on your platform: +# +# - On Linux and FreeBSD, it looks in +# :file:`.config/matplotlib/matplotlibrc` (or +# :file:`$XDG_CONFIG_HOME/matplotlib/matplotlibrc`) if you've customized +# your environment. +# +# - On other platforms, it looks in :file:`.matplotlib/matplotlibrc`. +# +# See :ref:`locating-matplotlib-config-dir`. +# +# 4. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where +# :file:`{INSTALL}` is something like +# :file:`/usr/lib/python3.9/site-packages` on Linux, and maybe +# :file:`C:\\Python39\\Lib\\site-packages` on Windows. Every time you +# install matplotlib, this file will be overwritten, so if you want +# your customizations to be saved, please move this file to your +# user-specific matplotlib directory. +# +# Once a :file:`matplotlibrc` file has been found, it will *not* search +# any of the other paths. When a +# :ref:`style sheet` is given with +# ``style.use('/.mplstyle')``, settings specified in +# the style sheet take precedence over settings in the +# :file:`matplotlibrc` file. +# +# To display where the currently active :file:`matplotlibrc` file was +# loaded from, one can do the following:: +# +# >>> import matplotlib +# >>> matplotlib.matplotlib_fname() +# '/home/foo/.config/matplotlib/matplotlibrc' +# +# See below for a sample :ref:`matplotlibrc file` +# and see `matplotlib.rcParams` for a full list of configurable rcParams. +# +# .. _matplotlibrc-sample: +# +# The default :file:`matplotlibrc` file +# ------------------------------------- +# +# .. literalinclude:: ../../../lib/matplotlib/mpl-data/matplotlibrc +# +# +# .. _ggplot: https://ggplot2.tidyverse.org/ +# .. _R: https://www.r-project.org/ diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/api_interfaces.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/api_interfaces.rst new file mode 100644 index 0000000000000000000000000000000000000000..473c808794caa6361621227ffb447c852fcffe49 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/api_interfaces.rst @@ -0,0 +1,290 @@ +.. redirect-from:: /gallery/misc/pythonic_matplotlib + +.. _api_interfaces: + +======================================== +Matplotlib Application Interfaces (APIs) +======================================== + +Matplotlib has two major application interfaces, or styles of using the library: + +- An explicit "Axes" interface that uses methods on a Figure or Axes object to + create other Artists, and build a visualization step by step. This has also + been called an "object-oriented" interface. +- An implicit "pyplot" interface that keeps track of the last Figure and Axes + created, and adds Artists to the object it thinks the user wants. + +In addition, a number of downstream libraries (like `pandas` and xarray_) offer +a ``plot`` method implemented directly on their data classes so that users can +call ``data.plot()``. + +.. _xarray: https://xarray.pydata.org + +The difference between these interfaces can be a bit confusing, particularly +given snippets on the web that use one or the other, or sometimes multiple +interfaces in the same example. Here we attempt to point out how the "pyplot" +and downstream interfaces relate to the explicit "Axes" interface to help users +better navigate the library. + + +Native Matplotlib interfaces +---------------------------- + +The explicit "Axes" interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The "Axes" interface is how Matplotlib is implemented, and many customizations +and fine-tuning end up being done at this level. + +This interface works by instantiating an instance of a +`~.matplotlib.figure.Figure` class (``fig`` below), using a +`~.Figure.subplots` method (or similar) on that object to create one or more +`~.matplotlib.axes.Axes` objects (``ax`` below), and then calling drawing +methods on the Axes (``plot`` in this example): + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + fig = plt.figure() + ax = fig.subplots() + ax.plot([1, 2, 3, 4], [0, 0.5, 1, 0.2]) + +We call this an "explicit" interface because each object is explicitly +referenced, and used to make the next object. Keeping references to the objects +is very flexible, and allows us to customize the objects after they are created, +but before they are displayed. + + +The implicit "pyplot" interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The `~.matplotlib.pyplot` module shadows most of the +`~.matplotlib.axes.Axes` plotting methods to give the equivalent of +the above, where the creation of the Figure and Axes is done for the user: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + plt.plot([1, 2, 3, 4], [0, 0.5, 1, 0.2]) + +This can be convenient, particularly when doing interactive work or simple +scripts. A reference to the current Figure can be retrieved using +`~.pyplot.gcf` and to the current Axes by `~.pyplot.gca`. The `~.pyplot` module +retains a list of Figures, and each Figure retains a list of Axes on the figure +for the user so that the following: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + plt.subplot(1, 2, 1) + plt.plot([1, 2, 3], [0, 0.5, 0.2]) + + plt.subplot(1, 2, 2) + plt.plot([3, 2, 1], [0, 0.5, 0.2]) + +is equivalent to: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + plt.subplot(1, 2, 1) + ax = plt.gca() + ax.plot([1, 2, 3], [0, 0.5, 0.2]) + + plt.subplot(1, 2, 2) + ax = plt.gca() + ax.plot([3, 2, 1], [0, 0.5, 0.2]) + +In the explicit interface, this would be: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + fig, axs = plt.subplots(1, 2) + axs[0].plot([1, 2, 3], [0, 0.5, 0.2]) + axs[1].plot([3, 2, 1], [0, 0.5, 0.2]) + +Why be explicit? +^^^^^^^^^^^^^^^^ + +What happens if you have to backtrack, and operate on an old axes that is not +referenced by ``plt.gca()``? One simple way is to call ``subplot`` again with +the same arguments. However, that quickly becomes inelegant. You can also +inspect the Figure object and get its list of Axes objects, however, that can be +misleading (colorbars are Axes too!). The best solution is probably to save a +handle to every Axes you create, but if you do that, why not simply create the +all the Axes objects at the start? + +The first approach is to call ``plt.subplot`` again: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + plt.subplot(1, 2, 1) + plt.plot([1, 2, 3], [0, 0.5, 0.2]) + + plt.subplot(1, 2, 2) + plt.plot([3, 2, 1], [0, 0.5, 0.2]) + + plt.suptitle('Implicit Interface: re-call subplot') + + for i in range(1, 3): + plt.subplot(1, 2, i) + plt.xlabel('Boo') + +The second is to save a handle: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + axs = [] + ax = plt.subplot(1, 2, 1) + axs += [ax] + plt.plot([1, 2, 3], [0, 0.5, 0.2]) + + ax = plt.subplot(1, 2, 2) + axs += [ax] + plt.plot([3, 2, 1], [0, 0.5, 0.2]) + + plt.suptitle('Implicit Interface: save handles') + + for i in range(2): + plt.sca(axs[i]) + plt.xlabel('Boo') + +However, the recommended way would be to be explicit from the outset: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + fig, axs = plt.subplots(1, 2) + axs[0].plot([1, 2, 3], [0, 0.5, 0.2]) + axs[1].plot([3, 2, 1], [0, 0.5, 0.2]) + fig.suptitle('Explicit Interface') + for i in range(2): + axs[i].set_xlabel('Boo') + + +Third-party library "Data-object" interfaces +-------------------------------------------- + +Some third party libraries have chosen to implement plotting for their data +objects, e.g. ``data.plot()``, is seen in `pandas`, xarray_, and other +third-party libraries. For illustrative purposes, a downstream library may +implement a simple data container that has ``x`` and ``y`` data stored together, +and then implements a ``plot`` method: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + # supplied by downstream library: + class DataContainer: + + def __init__(self, x, y): + """ + Proper docstring here! + """ + self._x = x + self._y = y + + def plot(self, ax=None, **kwargs): + if ax is None: + ax = plt.gca() + ax.plot(self._x, self._y, **kwargs) + ax.set_title('Plotted from DataClass!') + return ax + + + # what the user usually calls: + data = DataContainer([0, 1, 2, 3], [0, 0.2, 0.5, 0.3]) + data.plot() + +So the library can hide all the nitty-gritty from the user, and can make a +visualization appropriate to the data type, often with good labels, choices of +colormaps, and other convenient features. + +In the above, however, we may not have liked the title the library provided. +Thankfully, they pass us back the Axes from the ``plot()`` method, and +understanding the explicit Axes interface, we could call: +``ax.set_title('My preferred title')`` to customize the title. + +Many libraries also allow their ``plot`` methods to accept an optional *ax* +argument. This allows us to place the visualization in an Axes that we have +placed and perhaps customized. + +Summary +------- + +Overall, it is useful to understand the explicit "Axes" interface since it is +the most flexible and underlies the other interfaces. A user can usually +figure out how to drop down to the explicit interface and operate on the +underlying objects. While the explicit interface can be a bit more verbose +to setup, complicated plots will often end up simpler than trying to use +the implicit "pyplot" interface. + +.. note:: + + It is sometimes confusing to people that we import ``pyplot`` for both + interfaces. Currently, the ``pyplot`` module implements the "pyplot" + interface, but it also provides top-level Figure and Axes creation + methods, and ultimately spins up the graphical user interface, if one + is being used. So ``pyplot`` is still needed regardless of the + interface chosen. + +Similarly, the declarative interfaces provided by partner libraries use the +objects accessible by the "Axes" interface, and often accept these as arguments +or pass them back from methods. It is usually essential to use the explicit +"Axes" interface to perform any customization of the default visualization, or +to unpack the data into NumPy arrays and pass directly to Matplotlib. + +Appendix: "Axes" interface with data structures +----------------------------------------------- + +Most `~.axes.Axes` methods allow yet another API addressing by passing a +*data* object to the method and specifying the arguments as strings: + +.. plot:: + :include-source: + :align: center + + import matplotlib.pyplot as plt + + data = {'xdat': [0, 1, 2, 3], 'ydat': [0, 0.2, 0.4, 0.1]} + fig, ax = plt.subplots(figsize=(2, 2)) + ax.plot('xdat', 'ydat', data=data) + + +Appendix: "pylab" interface +--------------------------- + +There is one further interface that is highly discouraged, and that is to +basically do ``from matplotlib.pyplot import *``. This allows users to simply +call ``plot(x, y)``. While convenient, this can lead to obvious problems if the +user unwittingly names a variable the same name as a pyplot method. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/backends.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/backends.rst new file mode 100644 index 0000000000000000000000000000000000000000..eba03997fa75c82d11ffa58cbc64e1ad4f528b38 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/backends.rst @@ -0,0 +1,250 @@ +.. redirect-from:: /users/explain/backends + +.. _backends: + +======== +Backends +======== + +.. _what-is-a-backend: + +What is a backend? +------------------ + +A lot of documentation on the website and in the mailing lists refers +to the "backend" and many new users are confused by this term. +Matplotlib targets many different use cases and output formats. Some +people use Matplotlib interactively from the Python shell and have +plotting windows pop up when they type commands. Some people run +`Jupyter `_ notebooks and draw inline plots for +quick data analysis. Others embed Matplotlib into graphical user +interfaces like PyQt or PyGObject to build rich applications. Some +people use Matplotlib in batch scripts to generate postscript images +from numerical simulations, and still others run web application +servers to dynamically serve up graphs. + +To support all of these use cases, Matplotlib can target different +outputs, and each of these capabilities is called a backend; the +"frontend" is the user facing code, i.e., the plotting code, whereas the +"backend" does all the hard work behind-the-scenes to make the figure. +There are two types of backends: user interface backends (for use in +PyQt/PySide, PyGObject, Tkinter, wxPython, or macOS/Cocoa); also referred to +as "interactive backends") and hardcopy backends to make image files +(PNG, SVG, PDF, PS; also referred to as "non-interactive backends"). + +Selecting a backend +------------------- + +There are three ways to configure your backend: + +- The :rc:`backend` parameter in your :file:`matplotlibrc` file +- The :envvar:`MPLBACKEND` environment variable +- The function :func:`matplotlib.use` + +Below is a more detailed description. + +If there is more than one configuration present, the last one from the +list takes precedence; e.g. calling :func:`matplotlib.use()` will override +the setting in your :file:`matplotlibrc`. + +Without a backend explicitly set, Matplotlib automatically detects a usable +backend based on what is available on your system and on whether a GUI event +loop is already running. The first usable backend in the following list is +selected: MacOSX, QtAgg, GTK4Agg, Gtk3Agg, TkAgg, WxAgg, Agg. The last, Agg, +is a non-interactive backend that can only write to files. It is used on +Linux, if Matplotlib cannot connect to either an X display or a Wayland +display. + +Here is a detailed description of the configuration methods: + +#. Setting :rc:`backend` in your :file:`matplotlibrc` file:: + + backend : qtagg # use pyqt with antigrain (agg) rendering + + See also :ref:`customizing`. + +#. Setting the :envvar:`MPLBACKEND` environment variable: + + You can set the environment variable either for your current shell or for + a single script. + + On Unix:: + + > export MPLBACKEND=qtagg + > python simple_plot.py + + > MPLBACKEND=qtagg python simple_plot.py + + On Windows, only the former is possible:: + + > set MPLBACKEND=qtagg + > python simple_plot.py + + Setting this environment variable will override the ``backend`` parameter + in *any* :file:`matplotlibrc`, even if there is a :file:`matplotlibrc` in + your current working directory. Therefore, setting :envvar:`MPLBACKEND` + globally, e.g. in your :file:`.bashrc` or :file:`.profile`, is discouraged + as it might lead to counter-intuitive behavior. + +#. If your script depends on a specific backend you can use the function + :func:`matplotlib.use`:: + + import matplotlib + matplotlib.use('qtagg') + + This should be done before any figure is created, otherwise Matplotlib may + fail to switch the backend and raise an ImportError. + + Using `~matplotlib.use` will require changes in your code if users want to + use a different backend. Therefore, you should avoid explicitly calling + `~matplotlib.use` unless absolutely necessary. + +.. _the-builtin-backends: + +The builtin backends +-------------------- + +By default, Matplotlib should automatically select a default backend which +allows both interactive work and plotting from scripts, with output to the +screen and/or to a file, so at least initially, you will not need to worry +about the backend. The most common exception is if your Python distribution +comes without :mod:`tkinter` and you have no other GUI toolkit installed. +This happens with certain Linux distributions, where you need to install a +Linux package named ``python-tk`` (or similar). + +If, however, you want to write graphical user interfaces, or a web +application server +(:doc:`/gallery/user_interfaces/web_application_server_sgskip`), or need a +better understanding of what is going on, read on. To make things easily +more customizable for graphical user interfaces, Matplotlib separates +the concept of the renderer (the thing that actually does the drawing) +from the canvas (the place where the drawing goes). The canonical +renderer for user interfaces is ``Agg`` which uses the `Anti-Grain +Geometry`_ C++ library to make a raster (pixel) image of the figure; it +is used by the ``QtAgg``, ``GTK4Agg``, ``GTK3Agg``, ``wxAgg``, ``TkAgg``, and +``macosx`` backends. An alternative renderer is based on the Cairo library, +used by ``QtCairo``, etc. + +For the rendering engines, users can also distinguish between `vector +`_ or `raster +`_ renderers. Vector +graphics languages issue drawing commands like "draw a line from this +point to this point" and hence are scale free. Raster backends +generate a pixel representation of the line whose accuracy depends on a +DPI setting. + +Static backends +^^^^^^^^^^^^^^^ + +Here is a summary of the Matplotlib renderers (there is an eponymous +backend for each; these are *non-interactive backends*, capable of +writing to a file): + +======== ========= ======================================================= +Renderer Filetypes Description +======== ========= ======================================================= +AGG png raster_ graphics -- high quality images using the + `Anti-Grain Geometry`_ engine. +PDF pdf vector_ graphics -- `Portable Document Format`_ output. +PS ps, eps vector_ graphics -- PostScript_ output. +SVG svg vector_ graphics -- `Scalable Vector Graphics`_ output. +PGF pgf, pdf vector_ graphics -- using the pgf_ package. +Cairo png, ps, raster_ or vector_ graphics -- using the Cairo_ library + pdf, svg (requires pycairo_ or cairocffi_). +======== ========= ======================================================= + +To save plots using the non-interactive backends, use the +``matplotlib.pyplot.savefig('filename')`` method. + + +Interactive backends +^^^^^^^^^^^^^^^^^^^^ + +These are the user interfaces and renderer combinations supported; +these are *interactive backends*, capable of displaying to the screen +and using appropriate renderers from the table above to write to +a file: + +========= ================================================================ +Backend Description +========= ================================================================ +QtAgg Agg rendering in a Qt_ canvas (requires PyQt_ or `Qt for Python`_, + a.k.a. PySide). This backend can be activated in IPython with + ``%matplotlib qt``. The Qt binding can be selected via the + :envvar:`QT_API` environment variable; see :ref:`QT_bindings` for + more details. +ipympl Agg rendering embedded in a Jupyter widget (requires ipympl_). + This backend can be enabled in a Jupyter notebook with + ``%matplotlib ipympl``. +GTK3Agg Agg rendering to a GTK_ 3.x canvas (requires PyGObject_ and + pycairo_). This backend can be activated in IPython with + ``%matplotlib gtk3``. +GTK4Agg Agg rendering to a GTK_ 4.x canvas (requires PyGObject_ and + pycairo_). This backend can be activated in IPython with + ``%matplotlib gtk4``. +macosx Agg rendering into a Cocoa canvas in OSX. This backend can be + activated in IPython with ``%matplotlib osx``. +TkAgg Agg rendering to a Tk_ canvas (requires TkInter_). This + backend can be activated in IPython with ``%matplotlib tk``. +nbAgg Embed an interactive figure in a Jupyter classic notebook. This + backend can be enabled in Jupyter notebooks via + ``%matplotlib notebook``. +WebAgg On ``show()`` will start a tornado server with an interactive + figure. +GTK3Cairo Cairo rendering to a GTK_ 3.x canvas (requires PyGObject_ and + pycairo_). +GTK4Cairo Cairo rendering to a GTK_ 4.x canvas (requires PyGObject_ and + pycairo_). +wxAgg Agg rendering to a wxWidgets_ canvas (requires wxPython_ 4). + This backend can be activated in IPython with ``%matplotlib wx``. +========= ================================================================ + +.. note:: + The names of builtin backends case-insensitive; e.g., 'QtAgg' and + 'qtagg' are equivalent. + +.. _`Anti-Grain Geometry`: http://agg.sourceforge.net/antigrain.com/ +.. _`Portable Document Format`: https://en.wikipedia.org/wiki/Portable_Document_Format +.. _Postscript: https://en.wikipedia.org/wiki/PostScript +.. _`Scalable Vector Graphics`: https://en.wikipedia.org/wiki/Scalable_Vector_Graphics +.. _pgf: https://ctan.org/pkg/pgf +.. _Cairo: https://www.cairographics.org +.. _PyGObject: https://wiki.gnome.org/action/show/Projects/PyGObject +.. _pycairo: https://www.cairographics.org/pycairo/ +.. _cairocffi: https://pythonhosted.org/cairocffi/ +.. _wxPython: https://www.wxpython.org/ +.. _TkInter: https://docs.python.org/3/library/tk.html +.. _PyQt: https://riverbankcomputing.com/software/pyqt/intro +.. _`Qt for Python`: https://doc.qt.io/qtforpython/ +.. _Qt: https://qt.io/ +.. _GTK: https://www.gtk.org/ +.. _Tk: https://www.tcl.tk/ +.. _wxWidgets: https://www.wxwidgets.org/ +.. _ipympl: https://www.matplotlib.org/ipympl + +ipympl +^^^^^^ + +The Jupyter widget ecosystem is moving too fast to support directly in +Matplotlib. To install ipympl: + +.. code-block:: bash + + pip install ipympl + +or + +.. code-block:: bash + + conda install ipympl -c conda-forge + +See `installing ipympl `__ for more details. + +Using non-builtin backends +-------------------------- +More generally, any importable backend can be selected by using any of the +methods above. If ``name.of.the.backend`` is the module containing the +backend, use ``module://name.of.the.backend`` as the backend name, e.g. +``matplotlib.use('module://name.of.the.backend')``. + +Information for backend implementers is available at :ref:`writing_backend_interface`. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/event_handling.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/event_handling.rst new file mode 100644 index 0000000000000000000000000000000000000000..079139df43fdfd9ce0cdb5eae601a7ef74bb62ea --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/event_handling.rst @@ -0,0 +1,650 @@ +.. redirect-from:: /users/event_handling + +.. _event-handling: +.. _event_handling: + +************************** +Event handling and picking +************************** + +Matplotlib works with a number of user interface toolkits (wxpython, +tkinter, qt, gtk, and macosx) and in order to support features like +interactive panning and zooming of figures, it is helpful to the +developers to have an API for interacting with the figure via key +presses and mouse movements that is "GUI neutral" so we don't have to +repeat a lot of code across the different user interfaces. Although +the event handling API is GUI neutral, it is based on the GTK model, +which was the first user interface Matplotlib supported. The events +that are triggered are also a bit richer vis-a-vis Matplotlib than +standard GUI events, including information like which +`~.axes.Axes` the event occurred in. The events also +understand the Matplotlib coordinate system, and report event +locations in both pixel and data coordinates. + +.. _event-connections: + +Event connections +================= + +To receive events, you need to write a callback function and then +connect your function to the event manager, which is part of the +`~.FigureCanvasBase`. Here is a simple +example that prints the location of the mouse click and which button +was pressed:: + + fig, ax = plt.subplots() + ax.plot(np.random.rand(10)) + + def onclick(event): + print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % + ('double' if event.dblclick else 'single', event.button, + event.x, event.y, event.xdata, event.ydata)) + + cid = fig.canvas.mpl_connect('button_press_event', onclick) + +The `.FigureCanvasBase.mpl_connect` method returns a connection id (an +integer), which can be used to disconnect the callback via :: + + fig.canvas.mpl_disconnect(cid) + +.. note:: + The canvas retains only weak references to instance methods used as + callbacks. Therefore, you need to retain a reference to instances owning + such methods. Otherwise the instance will be garbage-collected and the + callback will vanish. + + This does not affect free functions used as callbacks. + +Here are the events that you can connect to, the class instances that +are sent back to you when the event occurs, and the event descriptions: + +====================== ================ ====================================== +Event name Class Description +====================== ================ ====================================== +'button_press_event' `.MouseEvent` mouse button is pressed +'button_release_event' `.MouseEvent` mouse button is released +'close_event' `.CloseEvent` figure is closed +'draw_event' `.DrawEvent` canvas has been drawn (but screen + widget not updated yet) +'key_press_event' `.KeyEvent` key is pressed +'key_release_event' `.KeyEvent` key is released +'motion_notify_event' `.MouseEvent` mouse moves +'pick_event' `.PickEvent` artist in the canvas is selected +'resize_event' `.ResizeEvent` figure canvas is resized +'scroll_event' `.MouseEvent` mouse scroll wheel is rolled +'figure_enter_event' `.LocationEvent` mouse enters a new figure +'figure_leave_event' `.LocationEvent` mouse leaves a figure +'axes_enter_event' `.LocationEvent` mouse enters a new axes +'axes_leave_event' `.LocationEvent` mouse leaves an axes +====================== ================ ====================================== + +.. note:: + When connecting to 'key_press_event' and 'key_release_event' events, + you may encounter inconsistencies between the different user interface + toolkits that Matplotlib works with. This is due to inconsistencies/limitations + of the user interface toolkit. The following table shows some basic examples of + what you may expect to receive as key(s) (using a QWERTY keyboard layout) + from the different user interface toolkits, where a comma separates different keys: + + .. container:: wide-table + + .. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Key(s) Pressed + - Tkinter + - Qt + - macosx + - WebAgg + - GTK + - WxPython + * - :kbd:`Shift+2` + - shift, @ + - shift, @ + - shift, @ + - shift, @ + - shift, @ + - shift, shift+2 + * - :kbd:`Shift+F1` + - shift, shift+f1 + - shift, shift+f1 + - shift, shift+f1 + - shift, shift+f1 + - shift, shift+f1 + - shift, shift+f1 + * - :kbd:`Shift` + - shift + - shift + - shift + - shift + - shift + - shift + * - :kbd:`Control` + - control + - control + - control + - control + - control + - control + * - :kbd:`Alt` + - alt + - alt + - alt + - alt + - alt + - alt + * - :kbd:`AltGr` + - iso_level3_shift + - *nothing* + - + - alt + - iso_level3_shift + - *nothing* + * - :kbd:`CapsLock` + - caps_lock + - caps_lock + - caps_lock + - caps_lock + - caps_lock + - caps_lock + * - :kbd:`CapsLock+a` + - caps_lock, A + - caps_lock, a + - caps_lock, a + - caps_lock, A + - caps_lock, A + - caps_lock, a + * - :kbd:`a` + - a + - a + - a + - a + - a + - a + * - :kbd:`Shift+a` + - shift, A + - shift, A + - shift, A + - shift, A + - shift, A + - shift, A + * - :kbd:`CapsLock+Shift+a` + - caps_lock, shift, a + - caps_lock, shift, A + - caps_lock, shift, A + - caps_lock, shift, a + - caps_lock, shift, a + - caps_lock, shift, A + * - :kbd:`Ctrl+Shift+Alt` + - control, ctrl+shift, ctrl+meta + - control, ctrl+shift, ctrl+meta + - control, ctrl+shift, ctrl+alt+shift + - control, ctrl+shift, ctrl+meta + - control, ctrl+shift, ctrl+meta + - control, ctrl+shift, ctrl+alt + * - :kbd:`Ctrl+Shift+a` + - control, ctrl+shift, ctrl+a + - control, ctrl+shift, ctrl+A + - control, ctrl+shift, ctrl+A + - control, ctrl+shift, ctrl+A + - control, ctrl+shift, ctrl+A + - control, ctrl+shift, ctrl+A + * - :kbd:`F1` + - f1 + - f1 + - f1 + - f1 + - f1 + - f1 + * - :kbd:`Ctrl+F1` + - control, ctrl+f1 + - control, ctrl+f1 + - control, *nothing* + - control, ctrl+f1 + - control, ctrl+f1 + - control, ctrl+f1 + +Matplotlib attaches some keypress callbacks by default for interactivity; they +are documented in the :ref:`key-event-handling` section. + +.. _event-attributes: + +Event attributes +================ + +All Matplotlib events inherit from the base class +`matplotlib.backend_bases.Event`, which stores the attributes: + +``name`` + the event name +``canvas`` + the FigureCanvas instance generating the event +``guiEvent`` + the GUI event that triggered the Matplotlib event + +The most common events that are the bread and butter of event handling +are key press/release events and mouse press/release and movement +events. The `.KeyEvent` and `.MouseEvent` classes that handle +these events are both derived from the LocationEvent, which has the +following attributes + +``x``, ``y`` + mouse x and y position in pixels from left and bottom of canvas +``inaxes`` + the `~.axes.Axes` instance over which the mouse is, if any; else None +``xdata``, ``ydata`` + mouse x and y position in data coordinates, if the mouse is over an + axes + +Let's look a simple example of a canvas, where a simple line segment +is created every time a mouse is pressed:: + + from matplotlib import pyplot as plt + + class LineBuilder: + def __init__(self, line): + self.line = line + self.xs = list(line.get_xdata()) + self.ys = list(line.get_ydata()) + self.cid = line.figure.canvas.mpl_connect('button_press_event', self) + + def __call__(self, event): + print('click', event) + if event.inaxes!=self.line.axes: return + self.xs.append(event.xdata) + self.ys.append(event.ydata) + self.line.set_data(self.xs, self.ys) + self.line.figure.canvas.draw() + + fig, ax = plt.subplots() + ax.set_title('click to build line segments') + line, = ax.plot([0], [0]) # empty line + linebuilder = LineBuilder(line) + + plt.show() + +The `.MouseEvent` that we just used is a `.LocationEvent`, so we have access to +the data and pixel coordinates via ``(event.x, event.y)`` and ``(event.xdata, +event.ydata)``. In addition to the ``LocationEvent`` attributes, it also has: + +``button`` + the button pressed: None, `.MouseButton`, 'up', or 'down' (up and down are used for scroll events) + +``key`` + the key pressed: None, any character, 'shift', 'win', or 'control' + +Draggable rectangle exercise +---------------------------- + +Write draggable rectangle class that is initialized with a +`.Rectangle` instance but will move its ``xy`` +location when dragged. Hint: you will need to store the original +``xy`` location of the rectangle which is stored as rect.xy and +connect to the press, motion and release mouse events. When the mouse +is pressed, check to see if the click occurs over your rectangle (see +`.Rectangle.contains`) and if it does, store +the rectangle xy and the location of the mouse click in data coords. +In the motion event callback, compute the deltax and deltay of the +mouse movement, and add those deltas to the origin of the rectangle +you stored. The redraw the figure. On the button release event, just +reset all the button press data you stored as None. + +Here is the solution:: + + import numpy as np + import matplotlib.pyplot as plt + + class DraggableRectangle: + def __init__(self, rect): + self.rect = rect + self.press = None + + def connect(self): + """Connect to all the events we need.""" + self.cidpress = self.rect.figure.canvas.mpl_connect( + 'button_press_event', self.on_press) + self.cidrelease = self.rect.figure.canvas.mpl_connect( + 'button_release_event', self.on_release) + self.cidmotion = self.rect.figure.canvas.mpl_connect( + 'motion_notify_event', self.on_motion) + + def on_press(self, event): + """Check whether mouse is over us; if so, store some data.""" + if event.inaxes != self.rect.axes: + return + contains, attrd = self.rect.contains(event) + if not contains: + return + print('event contains', self.rect.xy) + self.press = self.rect.xy, (event.xdata, event.ydata) + + def on_motion(self, event): + """Move the rectangle if the mouse is over us.""" + if self.press is None or event.inaxes != self.rect.axes: + return + (x0, y0), (xpress, ypress) = self.press + dx = event.xdata - xpress + dy = event.ydata - ypress + # print(f'x0={x0}, xpress={xpress}, event.xdata={event.xdata}, ' + # f'dx={dx}, x0+dx={x0+dx}') + self.rect.set_x(x0+dx) + self.rect.set_y(y0+dy) + + self.rect.figure.canvas.draw() + + def on_release(self, event): + """Clear button press information.""" + self.press = None + self.rect.figure.canvas.draw() + + def disconnect(self): + """Disconnect all callbacks.""" + self.rect.figure.canvas.mpl_disconnect(self.cidpress) + self.rect.figure.canvas.mpl_disconnect(self.cidrelease) + self.rect.figure.canvas.mpl_disconnect(self.cidmotion) + + fig, ax = plt.subplots() + rects = ax.bar(range(10), 20*np.random.rand(10)) + drs = [] + for rect in rects: + dr = DraggableRectangle(rect) + dr.connect() + drs.append(dr) + + plt.show() + + +**Extra credit**: Use blitting to make the animated drawing faster and +smoother. + +Extra credit solution:: + + # Draggable rectangle with blitting. + import numpy as np + import matplotlib.pyplot as plt + + class DraggableRectangle: + lock = None # only one can be animated at a time + + def __init__(self, rect): + self.rect = rect + self.press = None + self.background = None + + def connect(self): + """Connect to all the events we need.""" + self.cidpress = self.rect.figure.canvas.mpl_connect( + 'button_press_event', self.on_press) + self.cidrelease = self.rect.figure.canvas.mpl_connect( + 'button_release_event', self.on_release) + self.cidmotion = self.rect.figure.canvas.mpl_connect( + 'motion_notify_event', self.on_motion) + + def on_press(self, event): + """Check whether mouse is over us; if so, store some data.""" + if (event.inaxes != self.rect.axes + or DraggableRectangle.lock is not None): + return + contains, attrd = self.rect.contains(event) + if not contains: + return + print('event contains', self.rect.xy) + self.press = self.rect.xy, (event.xdata, event.ydata) + DraggableRectangle.lock = self + + # draw everything but the selected rectangle and store the pixel buffer + canvas = self.rect.figure.canvas + axes = self.rect.axes + self.rect.set_animated(True) + canvas.draw() + self.background = canvas.copy_from_bbox(self.rect.axes.bbox) + + # now redraw just the rectangle + axes.draw_artist(self.rect) + + # and blit just the redrawn area + canvas.blit(axes.bbox) + + def on_motion(self, event): + """Move the rectangle if the mouse is over us.""" + if (event.inaxes != self.rect.axes + or DraggableRectangle.lock is not self): + return + (x0, y0), (xpress, ypress) = self.press + dx = event.xdata - xpress + dy = event.ydata - ypress + self.rect.set_x(x0+dx) + self.rect.set_y(y0+dy) + + canvas = self.rect.figure.canvas + axes = self.rect.axes + # restore the background region + canvas.restore_region(self.background) + + # redraw just the current rectangle + axes.draw_artist(self.rect) + + # blit just the redrawn area + canvas.blit(axes.bbox) + + def on_release(self, event): + """Clear button press information.""" + if DraggableRectangle.lock is not self: + return + + self.press = None + DraggableRectangle.lock = None + + # turn off the rect animation property and reset the background + self.rect.set_animated(False) + self.background = None + + # redraw the full figure + self.rect.figure.canvas.draw() + + def disconnect(self): + """Disconnect all callbacks.""" + self.rect.figure.canvas.mpl_disconnect(self.cidpress) + self.rect.figure.canvas.mpl_disconnect(self.cidrelease) + self.rect.figure.canvas.mpl_disconnect(self.cidmotion) + + fig, ax = plt.subplots() + rects = ax.bar(range(10), 20*np.random.rand(10)) + drs = [] + for rect in rects: + dr = DraggableRectangle(rect) + dr.connect() + drs.append(dr) + + plt.show() + +.. _enter-leave-events: + +Mouse enter and leave +====================== + +If you want to be notified when the mouse enters or leaves a figure or +axes, you can connect to the figure/axes enter/leave events. Here is +a simple example that changes the colors of the axes and figure +background that the mouse is over:: + + """ + Illustrate the figure and axes enter and leave events by changing the + frame colors on enter and leave + """ + import matplotlib.pyplot as plt + + def enter_axes(event): + print('enter_axes', event.inaxes) + event.inaxes.patch.set_facecolor('yellow') + event.canvas.draw() + + def leave_axes(event): + print('leave_axes', event.inaxes) + event.inaxes.patch.set_facecolor('white') + event.canvas.draw() + + def enter_figure(event): + print('enter_figure', event.canvas.figure) + event.canvas.figure.patch.set_facecolor('red') + event.canvas.draw() + + def leave_figure(event): + print('leave_figure', event.canvas.figure) + event.canvas.figure.patch.set_facecolor('grey') + event.canvas.draw() + + fig1, axs = plt.subplots(2) + fig1.suptitle('mouse hover over figure or axes to trigger events') + + fig1.canvas.mpl_connect('figure_enter_event', enter_figure) + fig1.canvas.mpl_connect('figure_leave_event', leave_figure) + fig1.canvas.mpl_connect('axes_enter_event', enter_axes) + fig1.canvas.mpl_connect('axes_leave_event', leave_axes) + + fig2, axs = plt.subplots(2) + fig2.suptitle('mouse hover over figure or axes to trigger events') + + fig2.canvas.mpl_connect('figure_enter_event', enter_figure) + fig2.canvas.mpl_connect('figure_leave_event', leave_figure) + fig2.canvas.mpl_connect('axes_enter_event', enter_axes) + fig2.canvas.mpl_connect('axes_leave_event', leave_axes) + + plt.show() + +.. _object-picking: + +Object picking +============== + +You can enable picking by setting the ``picker`` property of an `.Artist` (such +as `.Line2D`, `.Text`, `.Patch`, `.Polygon`, `.AxesImage`, etc.) + +The ``picker`` property can be set using various types: + +``None`` + Picking is disabled for this artist (default). +``boolean`` + If True, then picking will be enabled and the artist will fire a + pick event if the mouse event is over the artist. +``callable`` + If picker is a callable, it is a user supplied function which + determines whether the artist is hit by the mouse event. The + signature is ``hit, props = picker(artist, mouseevent)`` to + determine the hit test. If the mouse event is over the artist, + return ``hit = True``; ``props`` is a dictionary of properties that + become additional attributes on the `.PickEvent`. + +The artist's ``pickradius`` property can additionally be set to a tolerance +value in points (there are 72 points per inch) that determines how far the +mouse can be and still trigger a mouse event. + +After you have enabled an artist for picking by setting the ``picker`` +property, you need to connect a handler to the figure canvas pick_event to get +pick callbacks on mouse press events. The handler typically looks like :: + + def pick_handler(event): + mouseevent = event.mouseevent + artist = event.artist + # now do something with this... + +The `.PickEvent` passed to your callback always has the following attributes: + +``mouseevent`` + The `.MouseEvent` that generate the pick event. See event-attributes_ + for a list of useful attributes on the mouse event. +``artist`` + The `.Artist` that generated the pick event. + +Additionally, certain artists like `.Line2D` and `.PatchCollection` may attach +additional metadata, like the indices of the data that meet the +picker criteria (e.g., all the points in the line that are within the +specified ``pickradius`` tolerance). + +Simple picking example +---------------------- + +In the example below, we enable picking on the line and set a pick radius +tolerance in points. The ``onpick`` +callback function will be called when the pick event it within the +tolerance distance from the line, and has the indices of the data +vertices that are within the pick distance tolerance. Our ``onpick`` +callback function simply prints the data that are under the pick +location. Different Matplotlib Artists can attach different data to +the PickEvent. For example, ``Line2D`` attaches the ind property, +which are the indices into the line data under the pick point. See +`.Line2D.pick` for details on the ``PickEvent`` properties of the line. :: + + import numpy as np + import matplotlib.pyplot as plt + + fig, ax = plt.subplots() + ax.set_title('click on points') + + line, = ax.plot(np.random.rand(100), 'o', + picker=True, pickradius=5) # 5 points tolerance + + def onpick(event): + thisline = event.artist + xdata = thisline.get_xdata() + ydata = thisline.get_ydata() + ind = event.ind + points = tuple(zip(xdata[ind], ydata[ind])) + print('onpick points:', points) + + fig.canvas.mpl_connect('pick_event', onpick) + + plt.show() + +Picking exercise +---------------- + +Create a data set of 100 arrays of 1000 Gaussian random numbers and +compute the sample mean and standard deviation of each of them (hint: +NumPy arrays have a mean and std method) and make a xy marker plot of +the 100 means vs. the 100 standard deviations. Connect the line +created by the plot command to the pick event, and plot the original +time series of the data that generated the clicked on points. If more +than one point is within the tolerance of the clicked on point, you +can use multiple subplots to plot the multiple time series. + +Exercise solution:: + + """ + Compute the mean and stddev of 100 data sets and plot mean vs. stddev. + When you click on one of the (mean, stddev) points, plot the raw dataset + that generated that point. + """ + + import numpy as np + import matplotlib.pyplot as plt + + X = np.random.rand(100, 1000) + xs = np.mean(X, axis=1) + ys = np.std(X, axis=1) + + fig, ax = plt.subplots() + ax.set_title('click on point to plot time series') + line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5) # 5 points tolerance + + + def onpick(event): + if event.artist != line: + return + n = len(event.ind) + if not n: + return + fig, axs = plt.subplots(n, squeeze=False) + for dataind, ax in zip(event.ind, axs.flat): + ax.plot(X[dataind]) + ax.text(0.05, 0.9, + f"$\\mu$={xs[dataind]:1.3f}\n$\\sigma$={ys[dataind]:1.3f}", + transform=ax.transAxes, verticalalignment='top') + ax.set_ylim(-0.5, 1.5) + fig.show() + return True + + + fig.canvas.mpl_connect('pick_event', onpick) + plt.show() diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/figure_intro.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/figure_intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..87bec6236d2a64b5d68c473d8e4f1520a4a573d6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/figure_intro.rst @@ -0,0 +1,259 @@ + +.. redirect-from:: /users/explain/figure + +.. _figure_explanation: + ++++++++++++++++++++++++ +Introduction to Figures ++++++++++++++++++++++++ + +.. plot:: + :include-source: + + fig = plt.figure(figsize=(2, 2), facecolor='lightskyblue', + layout='constrained') + fig.suptitle('Figure') + ax = fig.add_subplot() + ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium') + +When looking at Matplotlib visualization, you are almost always looking at +Artists placed on a `~.Figure`. In the example above, the figure is the +blue region and `~.Figure.add_subplot` has added an `~.axes.Axes` artist to the +`~.Figure` (see :ref:`figure_parts`). A more complicated visualization can add +multiple Axes to the Figure, colorbars, legends, annotations, and the Axes +themselves can have multiple Artists added to them +(e.g. ``ax.plot`` or ``ax.imshow``). + +.. contents:: :local: + + +.. _viewing_figures: + +Viewing Figures +================ + +We will discuss how to create Figures in more detail below, but first it is +helpful to understand how to view a Figure. This varies based on how you are +using Matplotlib, and what :ref:`Backend ` you are using. + +Notebooks and IDEs +------------------ + +.. figure:: /_static/FigureInline.png + :alt: Image of figure generated in Jupyter Notebook with inline backend. + :width: 400 + + Screenshot of a `Jupyter Notebook `_, with a figure + generated via the default `inline + `_ backend. + + +If you are using a Notebook (e.g. `Jupyter `_) or an IDE +that renders Notebooks (PyCharm, VSCode, etc), then they have a backend that +will render the Matplotlib Figure when a code cell is executed. One thing to +be aware of is that the default Jupyter backend (``%matplotlib inline``) will +by default trim or expand the figure size to have a tight box around Artists +added to the Figure (see :ref:`saving_figures`, below). If you use a backend +other than the default "inline" backend, you will likely need to use an ipython +"magic" like ``%matplotlib notebook`` for the Matplotlib :ref:`notebook +` or ``%matplotlib widget`` for the `ipympl +`_ backend. + +.. figure:: /_static/FigureNotebook.png + :alt: Image of figure generated in Jupyter Notebook with notebook + backend, including a toolbar. + :width: 400 + + Screenshot of a Jupyter Notebook with an interactive figure generated via + the ``%matplotlib notebook`` magic. Users should also try the similar + `widget `_ backend if using `JupyterLab + `_. + + +.. seealso:: + :ref:`interactive_figures`. + +Standalone scripts and interactive use +-------------------------------------- + +If the user is on a client with a windowing system, there are a number of +:ref:`Backends ` that can be used to render the Figure to +the screen, usually using a Python Qt, Tk, or Wx toolkit, or the native MacOS +backend. These are typically chosen either in the user's :ref:`matplotlibrc +`, or by calling, for example, +``matplotlib.use('QtAgg')`` at the beginning of a session or script. + +.. figure:: /_static/FigureQtAgg.png + :alt: Image of figure generated from a script via the QtAgg backend. + :width: 370 + + Screenshot of a Figure generated via a python script and shown using the + QtAgg backend. + +When run from a script, or interactively (e.g. from an +`iPython shell `_) the Figure +will not be shown until we call ``plt.show()``. The Figure will appear in +a new GUI window, and usually will have a toolbar with Zoom, Pan, and other tools +for interacting with the Figure. By default, ``plt.show()`` blocks +further interaction from the script or shell until the Figure window is closed, +though that can be toggled off for some purposes. For more details, please see +:ref:`controlling-interactive`. + +Note that if you are on a client that does not have access to a windowing +system, the Figure will fallback to being drawn using the "Agg" backend, and +cannot be viewed, though it can be :ref:`saved `. + +.. seealso:: + :ref:`interactive_figures`. + +.. _creating_figures: + +Creating Figures +================ + +By far the most common way to create a figure is using the +:ref:`pyplot ` interface. As noted in +:ref:`api_interfaces`, the pyplot interface serves two purposes. One is to spin +up the Backend and keep track of GUI windows. The other is a global state for +Axes and Artists that allow a short-form API to plotting methods. In the +example above, we use pyplot for the first purpose, and create the Figure object, +``fig``. As a side effect ``fig`` is also added to pyplot's global state, and +can be accessed via `~.pyplot.gcf`. + +Users typically want an Axes or a grid of Axes when they create a Figure, so in +addition to `~.pyplot.figure`, there are convenience methods that return both +a Figure and some Axes. A simple grid of Axes can be achieved with +`.pyplot.subplots` (which +simply wraps `.Figure.subplots`): + +.. plot:: + :include-source: + + fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout='constrained') + +More complex grids can be achieved with `.pyplot.subplot_mosaic` (which wraps +`.Figure.subplot_mosaic`): + +.. plot:: + :include-source: + + fig, axs = plt.subplot_mosaic([['A', 'right'], ['B', 'right']], + figsize=(4, 3), layout='constrained') + for ax_name in axs: + axs[ax_name].text(0.5, 0.5, ax_name, ha='center', va='center') + +Sometimes we want to have a nested layout in a Figure, with two or more sets of +Axes that do not share the same subplot grid. +We can use `~.Figure.add_subfigure` or `~.Figure.subfigures` to create virtual +figures inside a parent Figure; see +:doc:`/gallery/subplots_axes_and_figures/subfigures` for more details. + +.. plot:: + :include-source: + + fig = plt.figure(layout='constrained', facecolor='lightskyblue') + fig.suptitle('Figure') + figL, figR = fig.subfigures(1, 2) + figL.set_facecolor('thistle') + axL = figL.subplots(2, 1, sharex=True) + axL[1].set_xlabel('x [m]') + figL.suptitle('Left subfigure') + figR.set_facecolor('paleturquoise') + axR = figR.subplots(1, 2, sharey=True) + axR[0].set_title('Axes 1') + figR.suptitle('Right subfigure') + +It is possible to directly instantiate a `.Figure` instance without using the +pyplot interface. This is usually only necessary if you want to create your +own GUI application or service that you do not want carrying the pyplot global +state. See the embedding examples in :ref:`user_interfaces` for examples of +how to do this. + +Figure options +-------------- + +There are a few options available when creating figures. The Figure size on +the screen is set by *figsize* and *dpi*. *figsize* is the ``(width, height)`` +of the Figure in inches (or, if preferred, units of 72 typographic points). *dpi* +are how many pixels per inch the figure will be rendered at. To make your Figures +appear on the screen at the physical size you requested, you should set *dpi* +to the same *dpi* as your graphics system. Note that many graphics systems now use +a "dpi ratio" to specify how many screen pixels are used to represent a graphics +pixel. Matplotlib applies the dpi ratio to the *dpi* passed to the figure to make +it have higher resolution, so you should pass the lower number to the figure. + +The *facecolor*, *edgecolor*, *linewidth*, and *frameon* options all change the appearance of the +figure in expected ways, with *frameon* making the figure transparent if set to *False*. + +Finally, the user can specify a layout engine for the figure with the *layout* +parameter. Currently Matplotlib supplies +:ref:`"constrained" `, +:ref:`"compressed" ` and +:ref:`"tight" ` layout engines. These +rescale axes inside the Figure to prevent overlap of ticklabels, and try and align +axes, and can save significant manual adjustment of artists on a Figure for many +common cases. + +Adding Artists +-------------- + +The `~.FigureBase` class has a number of methods to add artists to a `~.Figure` or +a `~.SubFigure`. By far the most common are to add Axes of various configurations +(`~.FigureBase.add_axes`, `~.FigureBase.add_subplot`, `~.FigureBase.subplots`, +`~.FigureBase.subplot_mosaic`) and subfigures (`~.FigureBase.subfigures`). Colorbars +are added to Axes or group of Axes at the Figure level (`~.FigureBase.colorbar`). +It is also possible to have a Figure-level legend (`~.FigureBase.legend`). +Other Artists include figure-wide labels (`~.FigureBase.suptitle`, +`~.FigureBase.supxlabel`, `~.FigureBase.supylabel`) and text (`~.FigureBase.text`). +Finally, low-level Artists can be added directly using `~.FigureBase.add_artist` +usually with care being taken to use the appropriate transform. Usually these +include ``Figure.transFigure`` which ranges from 0 to 1 in each direction, and +represents the fraction of the current Figure size, or ``Figure.dpi_scale_trans`` +which will be in physical units of inches from the bottom left corner of the Figure +(see :ref:`transforms_tutorial` for more details). + + +.. _saving_figures: + +Saving Figures +============== + +Finally, Figures can be saved to disk using the `~.Figure.savefig` method. +``fig.savefig('MyFigure.png', dpi=200)`` will save a PNG formatted figure to +the file ``MyFigure.png`` in the current directory on disk with 200 dots-per-inch +resolution. Note that the filename can include a relative or absolute path to +any place on the file system. + +Many types of output are supported, including raster formats like PNG, GIF, JPEG, +TIFF and vector formats like PDF, EPS, and SVG. + +By default, the size of the saved Figure is set by the Figure size (in inches) and, for the raster +formats, the *dpi*. If *dpi* is not set, then the *dpi* of the Figure is used. +Note that *dpi* still has meaning for vector formats like PDF if the Figure includes +Artists that have been :doc:`rasterized `; the +*dpi* specified will be the resolution of the rasterized objects. + +It is possible to change the size of the Figure using the *bbox_inches* argument +to savefig. This can be specified manually, again in inches. However, by far +the most common use is ``bbox_inches='tight'``. This option "shrink-wraps", trimming +or expanding as needed, the size of the figure so that it is tight around all the artists +in a figure, with a small pad that can be specified by *pad_inches*, which defaults to +0.1 inches. The dashed box in the plot below shows the portion of the figure that +would be saved if ``bbox_inches='tight'`` were used in savefig. + +.. plot:: + + import matplotlib.pyplot as plt + from matplotlib.patches import FancyBboxPatch + + fig, ax = plt.subplots(figsize=(4, 2), facecolor='lightskyblue') + ax.set_position([0.1, 0.2, 0.8, 0.7]) + ax.set_aspect(1) + bb = ax.get_tightbbox() + bb = bb.padded(10) + bb = bb.transformed(fig.dpi_scale_trans.inverted()) + fancy = FancyBboxPatch(bb.p0, bb.width, bb.height, fc='none', + ec=(0, 0.0, 0, 0.5), lw=2, linestyle='--', + transform=fig.dpi_scale_trans, + clip_on=False, boxstyle='Square, pad=0') + ax.add_patch(fancy) diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/index.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..4433246e4074143dca43a93401e96976d94bac99 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/index.rst @@ -0,0 +1,36 @@ +++++++++++++++++++++ +Figures and backends +++++++++++++++++++++ + +When looking at Matplotlib visualization, you are almost always looking at +Artists placed on a `~.Figure`. In the example below, the figure is the +blue region and `~.Figure.add_subplot` has added an `~.axes.Axes` artist to the +`~.Figure` (see :ref:`figure_parts`). A more complicated visualization can add +multiple Axes to the Figure, colorbars, legends, annotations, and the Axes +themselves can have multiple Artists added to them +(e.g. ``ax.plot`` or ``ax.imshow``). + +.. plot:: + :include-source: + + fig = plt.figure(figsize=(4, 2), facecolor='lightskyblue', + layout='constrained') + fig.suptitle('A nice Matplotlib Figure') + ax = fig.add_subplot() + ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium') + + +.. toctree:: + :maxdepth: 2 + + Introduction to figures + +.. toctree:: + :maxdepth: 1 + + Output backends + Matplotlib Application Interfaces (APIs) + Interacting with figures + Interactive figures and asynchronous programming + Event handling + Writing a backend -- the pyplot interface diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive.rst new file mode 100644 index 0000000000000000000000000000000000000000..0d94a1cf8493358d05fb472c7360b39098fbd2c6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive.rst @@ -0,0 +1,384 @@ +.. redirect-from:: /users/interactive +.. redirect-from:: /users/explain/interactive + +.. currentmodule:: matplotlib + +.. _mpl-shell: +.. _interactive_figures: + +=================== +Interactive figures +=================== + +When working with data, interactivity can be invaluable. The pan/zoom and +mouse-location tools built into the Matplotlib GUI windows are often sufficient, but +you can also use the event system to build customized data exploration tools. + +.. seealso:: + :ref:`figure_explanation`. + + +Matplotlib ships with :ref:`backends ` binding to +several GUI toolkits (Qt, Tk, Wx, GTK, macOS, JavaScript) and third party +packages provide bindings to `kivy +`__ and `Jupyter Lab +`__. For the figures to be responsive to +mouse, keyboard, and paint events, the GUI event loop needs to be integrated +with an interactive prompt. We recommend using IPython (see :ref:`below `). + +The `.pyplot` module provides functions for explicitly creating figures +that include interactive tools, a toolbar, a tool-tip, and +:ref:`key bindings `: + +`.pyplot.figure` + Creates a new empty `.Figure` or selects an existing figure + +`.pyplot.subplots` + Creates a new `.Figure` and fills it with a grid of `~.axes.Axes` + +`.pyplot` has a notion of "The Current Figure" which can be accessed +through `.pyplot.gcf` and a notion of "The Current Axes" accessed +through `.pyplot.gca`. Almost all of the functions in `.pyplot` pass +through the current `.Figure` / `~.axes.Axes` (or create one) as +appropriate. + +Matplotlib keeps a reference to all of the open figures +created via `pyplot.figure` or `pyplot.subplots` so that the figures will not be garbage +collected. `.Figure`\s can be closed and deregistered from `.pyplot` individually via +`.pyplot.close`; all open `.Figure`\s can be closed via ``plt.close('all')``. + + +.. seealso:: + + For more discussion of Matplotlib's event system and integrated event loops: + + - :ref:`interactive_figures_and_eventloops` + - :ref:`event-handling` + + +.. _ipython-pylab: + +IPython integration +=================== + +We recommend using IPython for an interactive shell. In addition to +all of its features (improved tab-completion, magics, multiline editing, etc), +it also ensures that the GUI toolkit event loop is properly integrated +with the command line (see :ref:`cp_integration`). + +In this example, we create and modify a figure via an IPython prompt. +The figure displays in a QtAgg GUI window. To configure the integration +and enable :ref:`interactive mode ` use the +``%matplotlib`` magic: + +.. highlight:: ipython + +:: + + In [1]: %matplotlib + Using matplotlib backend: QtAgg + + In [2]: import matplotlib.pyplot as plt + +Create a new figure window: + +:: + + In [3]: fig, ax = plt.subplots() + + +Add a line plot of the data to the window: + +:: + + In [4]: ln, = ax.plot(range(5)) + +Change the color of the line from blue to orange: + +:: + + In [5]: ln.set_color('orange') + +If you wish to disable automatic redrawing of the plot: + +:: + + In [6]: plt.ioff() + +If you wish to re-enable automatic redrawing of the plot: + +:: + + In [7]: plt.ion() + + +In recent versions of ``Matplotlib`` and ``IPython``, it is +sufficient to import `matplotlib.pyplot` and call `.pyplot.ion`. +Using the ``%`` magic is guaranteed to work in all versions of Matplotlib and IPython. + + +.. highlight:: python + +.. _controlling-interactive: + +Interactive mode +================ + + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + pyplot.ion + pyplot.ioff + pyplot.isinteractive + + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + pyplot.show + pyplot.pause + + +Interactive mode controls: + +- whether created figures are automatically shown +- whether changes to artists automatically trigger re-drawing existing figures +- when `.pyplot.show()` returns if given no arguments: immediately, or after all of the figures have been closed + +If in interactive mode: + +- newly created figures will be displayed immediately +- figures will automatically redraw when elements are changed +- `pyplot.show()` displays the figures and immediately returns + +If not in interactive mode: + +- newly created figures and changes to figures are not displayed until + + * `.pyplot.show()` is called + * `.pyplot.pause()` is called + * `.FigureCanvasBase.flush_events()` is called + +- `pyplot.show()` runs the GUI event loop and does not return until all the plot windows are closed + +If you are in non-interactive mode (or created figures while in +non-interactive mode) you may need to explicitly call `.pyplot.show` +to display the windows on your screen. If you only want to run the +GUI event loop for a fixed amount of time, you can use `.pyplot.pause`. +This will block the progress of your code as if you had called +`time.sleep`, ensure the current window is shown and re-drawn if needed, +and run the GUI event loop for the specified period of time. + +The GUI event loop being integrated with your command prompt and +the figures being in interactive mode are independent of each other. +If you try to use `pyplot.ion` without arranging for the event-loop integration, +your figures will appear but will not be interactive while the prompt is waiting for input. +You will not be able to pan/zoom and the figure may not even render +(the window might appear black, transparent, or as a snapshot of the +desktop under it). Conversely, if you configure the event loop +integration, displayed figures will be responsive while waiting for input +at the prompt, regardless of pyplot's "interactive mode". + +No matter what combination of interactive mode setting and event loop integration, +figures will be responsive if you use ``pyplot.show(block=True)``, `.pyplot.pause`, or run +the GUI main loop in some other way. + + +.. warning:: + + Using `.Figure.show` it is possible to display a figure on + the screen without starting the event loop and without being in + interactive mode. This may work (depending on the GUI toolkit) but + will likely result in a non-responsive figure. + + +.. _default_ui: + +Default UI +========== + +The windows created by :mod:`~.pyplot` have an interactive toolbar with navigation +buttons and a readout of the data values the cursor is pointing at. + +.. _navigation-toolbar: + +Interactive navigation +====================== + +.. image:: ../../../_static/toolbar.png + +All figure windows come with a navigation toolbar, which can be used +to navigate through the data set. Here is a description of each of +the buttons at the bottom of the toolbar + +.. image:: ../../../../lib/matplotlib/mpl-data/images/home_large.png + +.. image:: ../../../../lib/matplotlib/mpl-data/images/back_large.png + +.. image:: ../../../../lib/matplotlib/mpl-data/images/forward_large.png + +The ``Home``, ``Forward`` and ``Back`` buttons + These are akin to a web browser's home, forward and back controls. + ``Forward`` and ``Back`` are used to navigate back and forth between + previously defined views. They have no meaning unless you have already + navigated somewhere else using the pan and zoom buttons. This is analogous + to trying to click ``Back`` on your web browser before visiting a + new page or ``Forward`` before you have gone back to a page -- + nothing happens. ``Home`` always takes you to the + first, default view of your data. Again, all of these buttons should + feel very familiar to any user of a web browser. + +.. image:: ../../../../lib/matplotlib/mpl-data/images/move_large.png + +The ``Pan/Zoom`` button + This button has two modes: pan and zoom. Click the toolbar button + to activate panning and zooming, then put your mouse somewhere + over an axes. Press the left mouse button and hold it to pan the + figure, dragging it to a new position. When you release it, the + data under the point where you pressed will be moved to the point + where you released. If you press 'x' or 'y' while panning the + motion will be constrained to the x or y axis, respectively. Press + the right mouse button to zoom, dragging it to a new position. + The x axis will be zoomed in proportionately to the rightward + movement and zoomed out proportionately to the leftward movement. + The same is true for the y axis and up/down motions. The point under your + mouse when you begin the zoom remains stationary, allowing you to + zoom in or out around that point as much as you wish. You can use the + modifier keys 'x', 'y' or 'CONTROL' to constrain the zoom to the x + axis, the y axis, or aspect ratio preserve, respectively. + + With polar plots, the pan and zoom functionality behaves + differently. The radius axis labels can be dragged using the left + mouse button. The radius scale can be zoomed in and out using the + right mouse button. + +.. image:: ../../../../lib/matplotlib/mpl-data/images/zoom_to_rect_large.png + +The ``Zoom-to-rectangle`` button + Click this toolbar button to activate this mode. Put your mouse somewhere + over an axes and press a mouse button. Define a rectangular region by + dragging the mouse while holding the button to a new location. When using + the left mouse button, the axes view limits will be zoomed to the defined + region. When using the right mouse button, the axes view limits will be + zoomed out, placing the original axes in the defined region. + +.. image:: ../../../../lib/matplotlib/mpl-data/images/subplots_large.png + +The ``Subplot-configuration`` button + Use this tool to configure the appearance of the subplot: + you can stretch or compress the left, right, top, or bottom + side of the subplot, or the space between the rows or + space between the columns. + +.. image:: ../../../../lib/matplotlib/mpl-data/images/filesave_large.png + +The ``Save`` button + Click this button to launch a file save dialog. You can save + files with the following extensions: ``png``, ``ps``, ``eps``, + ``svg`` and ``pdf``. + + +.. _key-event-handling: + +Navigation keyboard shortcuts +----------------------------- + +A number of helpful keybindings are registered by default. The following table +holds all the default keys, which can be overwritten by use of your +:ref:`matplotlibrc `. + +================================== =============================== +Command Default key binding and rcParam +================================== =============================== +Home/Reset :rc:`keymap.home` +Back :rc:`keymap.back` +Forward :rc:`keymap.forward` +Pan/Zoom :rc:`keymap.pan` +Zoom-to-rect :rc:`keymap.zoom` +Save :rc:`keymap.save` +Toggle fullscreen :rc:`keymap.fullscreen` +Toggle major grids :rc:`keymap.grid` +Toggle minor grids :rc:`keymap.grid_minor` +Toggle x axis scale (log/linear) :rc:`keymap.xscale` +Toggle y axis scale (log/linear) :rc:`keymap.yscale` +Close Figure :rc:`keymap.quit` +Constrain pan/zoom to x axis hold **x** when panning/zooming with mouse +Constrain pan/zoom to y axis hold **y** when panning/zooming with mouse +Preserve aspect ratio hold **CONTROL** when panning/zooming with mouse +================================== =============================== + + +.. _other-shells: + +Other Python prompts +==================== + +Interactive mode works in the default Python prompt: + + +.. sourcecode:: pycon + + >>> import matplotlib.pyplot as plt + >>> plt.ion() + >>> + +however this does not ensure that the event hook is properly installed +and your figures may not be responsive. Please consult the +documentation of your GUI toolkit for details. + + +.. _jupyter_notebooks_jupyterlab: + +Jupyter Notebooks / JupyterLab +------------------------------ + +.. note:: + + To get the interactive functionality described here, you must be + using an interactive backend. The default backend in notebooks, + the inline backend, is not. `~ipykernel.pylab.backend_inline` + renders the figure once and inserts a static image into the + notebook when the cell is executed. Because the images are static, they + cannot be panned / zoomed, take user input, or be updated from other + cells. + +To get interactive figures in the 'classic' notebook or Jupyter lab, +use the `ipympl `__ backend +(must be installed separately) which uses the **ipywidget** framework. +If ``ipympl`` is installed use the magic: + +.. sourcecode:: ipython + + %matplotlib widget + +to select and enable it. + +If you only need to use the classic notebook, you can use + +.. sourcecode:: ipython + + %matplotlib notebook + +which uses the `.backend_nbagg` backend provided by Matplotlib; +however, nbagg does not work in Jupyter Lab. + +GUIs + Jupyter +~~~~~~~~~~~~~~ + +You can also use one of the non-``ipympl`` GUI backends in a Jupyter Notebook. +If you are running your Jupyter kernel locally, the GUI window will spawn on +your desktop adjacent to your web browser. If you run your notebook on a remote server, +the kernel will try to open the GUI window on the remote computer. Unless you have +arranged to forward the xserver back to your desktop, you will not be able to +see or interact with the window. It may also raise an exception. + + + +PyCharm, Spyder, and VSCode +--------------------------- + +Many IDEs have built-in integration with Matplotlib, please consult their +documentation for configuration details. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive_guide.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive_guide.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7ccbe4cab25d89cd0c4cf7023502c5f9577461c --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/interactive_guide.rst @@ -0,0 +1,446 @@ +.. _interactive_figures_and_eventloops: + +.. redirect-from:: /users/interactive_guide + +.. currentmodule:: matplotlib + + +================================================ +Interactive figures and asynchronous programming +================================================ + +Matplotlib supports rich interactive figures by embedding figures into +a GUI window. The basic interactions of panning and zooming in an +Axes to inspect your data is 'baked in' to Matplotlib. This is +supported by a full mouse and keyboard event handling system that +you can use to build sophisticated interactive graphs. + +This guide is meant to be an introduction to the low-level details of +how Matplotlib integration with a GUI event loop works. For a more +practical introduction to the Matplotlib event API see :ref:`event +handling system `, `Interactive Tutorial +`__, and +`Interactive Applications using Matplotlib +`__. + +Event loops +=========== + +Fundamentally, all user interaction (and networking) is implemented as +an infinite loop waiting for events from the user (via the OS) and +then doing something about it. For example, a minimal Read Evaluate +Print Loop (REPL) is :: + + exec_count = 0 + while True: + inp = input(f"[{exec_count}] > ") # Read + ret = eval(inp) # Evaluate + print(ret) # Print + exec_count += 1 # Loop + + +This is missing many niceties (for example, it exits on the first +exception!), but is representative of the event loops that underlie +all terminals, GUIs, and servers [#f1]_. In general the *Read* step +is waiting on some sort of I/O -- be it user input or the network -- +while the *Evaluate* and *Print* are responsible for interpreting the +input and then **doing** something about it. + +In practice we interact with a framework that provides a mechanism to +register callbacks to be run in response to specific events rather +than directly implement the I/O loop [#f2]_. For example "when the +user clicks on this button, please run this function" or "when the +user hits the 'z' key, please run this other function". This allows +users to write reactive, event-driven, programs without having to +delve into the nitty-gritty [#f3]_ details of I/O. The core event loop +is sometimes referred to as "the main loop" and is typically started, +depending on the library, by methods with names like ``_exec``, +``run``, or ``start``. + + +All GUI frameworks (Qt, Wx, Gtk, tk, OSX, or web) have some method of +capturing user interactions and passing them back to the application +(for example ``Signal`` / ``Slot`` framework in Qt) but the exact +details depend on the toolkit. Matplotlib has a :ref:`backend +` for each GUI toolkit we support which uses the +toolkit API to bridge the toolkit UI events into Matplotlib's :ref:`event +handling system `. You can then use +`.FigureCanvasBase.mpl_connect` to connect your function to +Matplotlib's event handling system. This allows you to directly +interact with your data and write GUI toolkit agnostic user +interfaces. + + +.. _cp_integration: + +Command prompt integration +========================== + +So far, so good. We have the REPL (like the IPython terminal) that +lets us interactively send code to the interpreter and get results +back. We also have the GUI toolkit that runs an event loop waiting +for user input and lets us register functions to be run when that +happens. However, if we want to do both we have a problem: the prompt +and the GUI event loop are both infinite loops that each think *they* +are in charge! In order for both the prompt and the GUI windows to be +responsive we need a method to allow the loops to 'timeshare' : + +1. let the GUI main loop block the python process when you want + interactive windows +2. let the CLI main loop block the python process and intermittently + run the GUI loop +3. fully embed python in the GUI (but this is basically writing a full + application) + +.. _cp_block_the_prompt: + +Blocking the prompt +------------------- + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + pyplot.show + pyplot.pause + + backend_bases.FigureCanvasBase.start_event_loop + backend_bases.FigureCanvasBase.stop_event_loop + + +The simplest "integration" is to start the GUI event loop in +'blocking' mode and take over the CLI. While the GUI event loop is +running you cannot enter new commands into the prompt (your terminal +may echo the characters typed into the terminal, but they will not be +sent to the Python interpreter because it is busy running the GUI +event loop), but the figure windows will be responsive. Once the +event loop is stopped (leaving any still open figure windows +non-responsive) you will be able to use the prompt again. Re-starting +the event loop will make any open figure responsive again (and will +process any queued up user interaction). + +To start the event loop until all open figures are closed, use +`.pyplot.show` as :: + + pyplot.show(block=True) + +To start the event loop for a fixed amount of time (in seconds) use +`.pyplot.pause`. + +If you are not using `.pyplot` you can start and stop the event loops +via `.FigureCanvasBase.start_event_loop` and +`.FigureCanvasBase.stop_event_loop`. However, in most contexts where +you would not be using `.pyplot` you are embedding Matplotlib in a +large GUI application and the GUI event loop should already be running +for the application. + +Away from the prompt, this technique can be very useful if you want to +write a script that pauses for user interaction, or displays a figure +between polling for additional data. See :ref:`interactive_scripts` +for more details. + + +Input hook integration +---------------------- + +While running the GUI event loop in a blocking mode or explicitly +handling UI events is useful, we can do better! We really want to be +able to have a usable prompt **and** interactive figure windows. + +We can do this using the 'input hook' feature of the interactive +prompt. This hook is called by the prompt as it waits for the user +to type (even for a fast typist the prompt is mostly waiting for the +human to think and move their fingers). Although the details vary +between prompts the logic is roughly + +1. start to wait for keyboard input +2. start the GUI event loop +3. as soon as the user hits a key, exit the GUI event loop and handle the key +4. repeat + +This gives us the illusion of simultaneously having interactive GUI +windows and an interactive prompt. Most of the time the GUI event +loop is running, but as soon as the user starts typing the prompt +takes over again. + +This time-share technique only allows the event loop to run while +python is otherwise idle and waiting for user input. If you want the +GUI to be responsive during long running code it is necessary to +periodically flush the GUI event queue as described in :ref:`spin_event_loop`. +In this case it is your code, not the REPL, which +is blocking the process so you need to handle the "time-share" manually. +Conversely, a very slow figure draw will block the prompt until it +finishes drawing. + +Full embedding +============== + +It is also possible to go the other direction and fully embed figures +(and a `Python interpreter +`__) in a rich +native application. Matplotlib provides classes for each toolkit +which can be directly embedded in GUI applications (this is how the +built-in windows are implemented!). See :ref:`user_interfaces` for +more details. + + +.. _interactive_scripts : + +Scripts and functions +===================== + + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + backend_bases.FigureCanvasBase.flush_events + backend_bases.FigureCanvasBase.draw_idle + + figure.Figure.ginput + pyplot.ginput + + pyplot.show + pyplot.pause + +There are several use-cases for using interactive figures in scripts: + +- capture user input to steer the script +- progress updates as a long running script progresses +- streaming updates from a data source + +Blocking functions +------------------ + +If you only need to collect points in an Axes you can use +`.Figure.ginput`. However if you have written some custom event +handling or are using `.widgets` you will need to manually run the GUI +event loop using the methods described :ref:`above `. + +You can also use the methods described in :ref:`cp_block_the_prompt` +to suspend run the GUI event loop. Once the loop exits your code will +resume. In general, any place you would use `time.sleep` you can use +`.pyplot.pause` instead with the added benefit of interactive figures. + +For example, if you want to poll for data you could use something like :: + + fig, ax = plt.subplots() + ln, = ax.plot([], []) + + while True: + x, y = get_new_data() + ln.set_data(x, y) + plt.pause(1) + +which would poll for new data and update the figure at 1Hz. + +.. _spin_event_loop: + +Explicitly spinning the event Loop +---------------------------------- + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + backend_bases.FigureCanvasBase.flush_events + backend_bases.FigureCanvasBase.draw_idle + + + +If you have open windows that have pending UI +events (mouse clicks, button presses, or draws) you can explicitly +process those events by calling `.FigureCanvasBase.flush_events`. +This will run the GUI event loop until all UI events currently waiting +have been processed. The exact behavior is backend-dependent but +typically events on all figure are processed and only events waiting +to be processed (not those added during processing) will be handled. + +For example :: + + import time + import matplotlib.pyplot as plt + import numpy as np + plt.ion() + + fig, ax = plt.subplots() + th = np.linspace(0, 2*np.pi, 512) + ax.set_ylim(-1.5, 1.5) + + ln, = ax.plot(th, np.sin(th)) + + def slow_loop(N, ln): + for j in range(N): + time.sleep(.1) # to simulate some work + ln.figure.canvas.flush_events() + + slow_loop(100, ln) + +While this will feel a bit laggy (as we are only processing user input +every 100ms whereas 20-30ms is what feels "responsive") it will +respond. + +If you make changes to the plot and want it re-rendered you will need +to call `~.FigureCanvasBase.draw_idle` to request that the canvas be +re-drawn. This method can be thought of *draw_soon* in analogy to +`asyncio.loop.call_soon`. + +We can add this to our example above as :: + + def slow_loop(N, ln): + for j in range(N): + time.sleep(.1) # to simulate some work + if j % 10: + ln.set_ydata(np.sin(((j // 10) % 5 * th))) + ln.figure.canvas.draw_idle() + + ln.figure.canvas.flush_events() + + slow_loop(100, ln) + + +The more frequently you call `.FigureCanvasBase.flush_events` the more +responsive your figure will feel but at the cost of spending more +resources on the visualization and less on your computation. + + +.. _stale_artists: + +Stale artists +============= + +Artists (as of Matplotlib 1.5) have a **stale** attribute which is +`True` if the internal state of the artist has changed since the last +time it was rendered. By default the stale state is propagated up to +the Artists parents in the draw tree, e.g., if the color of a `.Line2D` +instance is changed, the `~.axes.Axes` and `.Figure` that +contain it will also be marked as "stale". Thus, ``fig.stale`` will +report if any artist in the figure has been modified and is out of sync +with what is displayed on the screen. This is intended to be used to +determine if ``draw_idle`` should be called to schedule a re-rendering +of the figure. + +Each artist has a `.Artist.stale_callback` attribute which holds a callback +with the signature :: + + def callback(self: Artist, val: bool) -> None: + ... + +which by default is set to a function that forwards the stale state to +the artist's parent. If you wish to suppress a given artist from propagating +set this attribute to None. + +`.Figure` instances do not have a containing artist and their +default callback is `None`. If you call `.pyplot.ion` and are not in +``IPython`` we will install a callback to invoke +`~.backend_bases.FigureCanvasBase.draw_idle` whenever the +`.Figure` becomes stale. In ``IPython`` we use the +``'post_execute'`` hook to invoke +`~.backend_bases.FigureCanvasBase.draw_idle` on any stale figures +after having executed the user's input, but before returning the prompt +to the user. If you are not using `.pyplot` you can use the callback +`Figure.stale_callback` attribute to be notified when a figure has +become stale. + + +.. _draw_idle: + +Idle draw +========= + +.. autosummary:: + :template: autosummary.rst + :nosignatures: + + backend_bases.FigureCanvasBase.draw + backend_bases.FigureCanvasBase.draw_idle + backend_bases.FigureCanvasBase.flush_events + + +In almost all cases, we recommend using +`backend_bases.FigureCanvasBase.draw_idle` over +`backend_bases.FigureCanvasBase.draw`. ``draw`` forces a rendering of +the figure whereas ``draw_idle`` schedules a rendering the next time +the GUI window is going to re-paint the screen. This improves +performance by only rendering pixels that will be shown on the screen. If +you want to be sure that the screen is updated as soon as possible do :: + + fig.canvas.draw_idle() + fig.canvas.flush_events() + + + +Threading +========= + +Most GUI frameworks require that all updates to the screen, and hence +their main event loop, run on the main thread. This makes pushing +periodic updates of a plot to a background thread impossible. +Although it seems backwards, it is typically easier to push your +computations to a background thread and periodically update +the figure on the main thread. + +In general Matplotlib is not thread safe. If you are going to update +`.Artist` objects in one thread and draw from another you should make +sure that you are locking in the critical sections. + + + +Eventloop integration mechanism +=============================== + +CPython / readline +------------------ + +The Python C API provides a hook, :c:data:`PyOS_InputHook`, to register a +function to be run ("The function will be called when Python's +interpreter prompt is about to become idle and wait for user input +from the terminal."). This hook can be used to integrate a second +event loop (the GUI event loop) with the python input prompt loop. +The hook functions typically exhaust all pending events on the GUI +event queue, run the main loop for a short fixed amount of time, or +run the event loop until a key is pressed on stdin. + +Matplotlib does not currently do any management of :c:data:`PyOS_InputHook` due +to the wide range of ways that Matplotlib is used. This management is left to +downstream libraries -- either user code or the shell. Interactive figures, +even with Matplotlib in 'interactive mode', may not work in the vanilla python +repl if an appropriate :c:data:`PyOS_InputHook` is not registered. + +Input hooks, and helpers to install them, are usually included with +the python bindings for GUI toolkits and may be registered on import. +IPython also ships input hook functions for all of the GUI frameworks +Matplotlib supports which can be installed via ``%matplotlib``. This +is the recommended method of integrating Matplotlib and a prompt. + + +IPython / prompt_toolkit +------------------------ + +With IPython >= 5.0 IPython has changed from using CPython's readline +based prompt to a ``prompt_toolkit`` based prompt. ``prompt_toolkit`` +has the same conceptual input hook, which is fed into ``prompt_toolkit`` via the +:meth:`IPython.terminal.interactiveshell.TerminalInteractiveShell.inputhook` +method. The source for the ``prompt_toolkit`` input hooks lives at +``IPython.terminal.pt_inputhooks``. + + + +.. rubric:: Footnotes + +.. [#f1] A limitation of this design is that you can only wait for one + input, if there is a need to multiplex between multiple sources + then the loop would look something like :: + + fds = [...] + while True: # Loop + inp = select(fds).read() # Read + eval(inp) # Evaluate / Print + +.. [#f2] Or you can `write your own + `__ if you must. + +.. [#f3] These examples are aggressively dropping many of the + complexities that must be dealt with in the real world such as + keyboard interrupts, timeouts, bad input, resource + allocation and cleanup, etc. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/figure/writing_a_backend_pyplot_interface.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/writing_a_backend_pyplot_interface.rst new file mode 100644 index 0000000000000000000000000000000000000000..452f4d7610bb2ca34780be94ff9ea8e0ae855619 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/figure/writing_a_backend_pyplot_interface.rst @@ -0,0 +1,86 @@ +.. redirect-from:: /users/explain/writing_a_backend_pyplot_interface + +.. _writing_backend_interface: + +========================================= +Writing a backend -- the pyplot interface +========================================= + +This page assumes general understanding of the information in the +:ref:`backends` page, and is instead intended as reference for +third-party backend implementers. It also only deals with the interaction +between backends and `.pyplot`, not with the rendering side, which is described +in `.backend_template`. + +There are two APIs for defining backends: a new canvas-based API (introduced in +Matplotlib 3.6), and an older function-based API. The new API is simpler to +implement because many methods can be inherited from "parent backends". It is +recommended if back-compatibility for Matplotlib < 3.6 is not a concern. +However, the old API remains supported. + +Fundamentally, a backend module needs to provide information to `.pyplot`, so +that + +1. `.pyplot.figure()` can create a new `.Figure` instance and associate it with + an instance of a backend-provided canvas class, itself hosted in an instance + of a backend-provided manager class. +2. `.pyplot.show()` can show all figures and start the GUI event loop (if any). + +To do so, the backend module must define a ``backend_module.FigureCanvas`` +subclass of `.FigureCanvasBase`. In the canvas-based API, this is the only +strict requirement for backend modules. The function-based API additionally +requires many module-level functions to be defined. + +Canvas-based API (Matplotlib >= 3.6) +------------------------------------ + +1. **Creating a figure**: `.pyplot.figure()` calls + ``figure = Figure(); FigureCanvas.new_manager(figure, num)`` + (``new_manager`` is a classmethod) to instantiate a canvas and a manager and + set up the ``figure.canvas`` and ``figure.canvas.manager`` attributes. + Figure unpickling uses the same approach, but replaces the newly + instantiated ``Figure()`` by the unpickled figure. + + Interactive backends should customize the effect of ``new_manager`` by + setting the ``FigureCanvas.manager_class`` attribute to the desired manager + class, and additionally (if the canvas cannot be created before the manager, + as in the case of the wx backends) by overriding the + ``FigureManager.create_with_canvas`` classmethod. (Non-interactive backends + can normally use a trivial ``FigureManagerBase`` and can therefore skip this + step.) + + After a new figure is registered with `.pyplot` (either via + `.pyplot.figure()` or via unpickling), if in interactive mode, `.pyplot` + will call its canvas' ``draw_idle()`` method, which can be overridden as + desired. + +2. **Showing figures**: `.pyplot.show()` calls + ``FigureCanvas.manager_class.pyplot_show()`` (a classmethod), forwarding any + arguments, to start the main event loop. + + By default, ``pyplot_show()`` checks whether there are any ``managers`` + registered with `.pyplot` (exiting early if not), calls ``manager.show()`` + on all such managers, and then, if called with ``block=True`` (or with + the default ``block=None`` and out of IPython's pylab mode and not in + interactive mode), calls ``FigureCanvas.manager_class.start_main_loop()`` + (a classmethod) to start the main event loop. Interactive backends should + therefore override the ``FigureCanvas.manager_class.start_main_loop`` + classmethod accordingly (or alternatively, they may also directly override + ``FigureCanvas.manager_class.pyplot_show`` directly). + +Function-based API +------------------ + +1. **Creating a figure**: `.pyplot.figure()` calls + ``new_figure_manager(num, *args, **kwargs)`` (which also takes care of + creating the new figure as ``Figure(*args, **kwargs)``); unpickling calls + ``new_figure_manager_given_figure(num, figure)``. + + Furthermore, in interactive mode, the first draw of the newly registered + figure can be customized by providing a module-level + ``draw_if_interactive()`` function. (In the new canvas-based API, this + function is not taken into account anymore.) + +2. **Showing figures**: `.pyplot.show()` calls a module-level ``show()`` + function, which is typically generated via the ``ShowBase`` class and its + ``mainloop`` method. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/index.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..46951ede91abcdc32eacca10991a5ccd46a867f1 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/index.rst @@ -0,0 +1,5 @@ +.. _users-guide-explain: + +==================== +User guide tutorials +==================== diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/quick_start.py b/testbed/matplotlib__matplotlib/galleries/users_explain/quick_start.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2d5850e6e597b8af70b3904af456f5b5afc1a9 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/quick_start.py @@ -0,0 +1,590 @@ +""" +.. redirect-from:: /tutorials/introductory/usage +.. redirect-from:: /tutorials/introductory/quick_start + +.. _quick_start: + +***************** +Quick start guide +***************** + +This tutorial covers some basic usage patterns and best practices to +help you get started with Matplotlib. + +""" + +import matplotlib.pyplot as plt +import numpy as np + +# sphinx_gallery_thumbnail_number = 3 +import matplotlib as mpl + +# %% +# +# A simple example +# ================ +# +# Matplotlib graphs your data on `.Figure`\s (e.g., windows, Jupyter +# widgets, etc.), each of which can contain one or more `~.axes.Axes`, an +# area where points can be specified in terms of x-y coordinates (or theta-r +# in a polar plot, x-y-z in a 3D plot, etc.). The simplest way of +# creating a Figure with an Axes is using `.pyplot.subplots`. We can then use +# `.Axes.plot` to draw some data on the Axes: + +fig, ax = plt.subplots() # Create a figure containing a single axes. +ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes. + +# %% +# +# Note that to get this Figure to display, you may have to call ``plt.show()``, +# depending on your backend. For more details of Figures and backends, see +# :ref:`figure_explanation`. +# +# .. _figure_parts: +# +# Parts of a Figure +# ================= +# +# Here are the components of a Matplotlib Figure. +# +# .. image:: ../../_static/anatomy.png +# +# :class:`~matplotlib.figure.Figure` +# ---------------------------------- +# +# The **whole** figure. The Figure keeps +# track of all the child :class:`~matplotlib.axes.Axes`, a group of +# 'special' Artists (titles, figure legends, colorbars, etc), and +# even nested subfigures. +# +# The easiest way to create a new Figure is with pyplot:: +# +# fig = plt.figure() # an empty figure with no Axes +# fig, ax = plt.subplots() # a figure with a single Axes +# fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes +# # a figure with one axes on the left, and two on the right: +# fig, axs = plt.subplot_mosaic([['left', 'right_top'], +# ['left', 'right_bottom']]) +# +# It is often convenient to create the Axes together with the Figure, but you +# can also manually add Axes later on. Note that many +# :ref:`Matplotlib backends ` support zooming and +# panning on figure windows. +# +# For more on Figures, see :ref:`figure_explanation`. +# +# :class:`~matplotlib.axes.Axes` +# ------------------------------ +# +# An Axes is an Artist attached to a Figure that contains a region for +# plotting data, and usually includes two (or three in the case of 3D) +# :class:`~matplotlib.axis.Axis` objects (be aware of the difference +# between **Axes** and **Axis**) that provide ticks and tick labels to +# provide scales for the data in the Axes. Each :class:`~.axes.Axes` also +# has a title +# (set via :meth:`~matplotlib.axes.Axes.set_title`), an x-label (set via +# :meth:`~matplotlib.axes.Axes.set_xlabel`), and a y-label set via +# :meth:`~matplotlib.axes.Axes.set_ylabel`). +# +# The :class:`~.axes.Axes` class and its member functions are the primary +# entry point to working with the OOP interface, and have most of the +# plotting methods defined on them (e.g. ``ax.plot()``, shown above, uses +# the `~.Axes.plot` method) +# +# :class:`~matplotlib.axis.Axis` +# ------------------------------ +# +# These objects set the scale and limits and generate ticks (the marks +# on the Axis) and ticklabels (strings labeling the ticks). The location +# of the ticks is determined by a `~matplotlib.ticker.Locator` object and the +# ticklabel strings are formatted by a `~matplotlib.ticker.Formatter`. The +# combination of the correct `.Locator` and `.Formatter` gives very fine +# control over the tick locations and labels. +# +# :class:`~matplotlib.artist.Artist` +# ---------------------------------- +# +# Basically, everything visible on the Figure is an Artist (even +# `.Figure`, `Axes <.axes.Axes>`, and `~.axis.Axis` objects). This includes +# `.Text` objects, `.Line2D` objects, :mod:`.collections` objects, `.Patch` +# objects, etc. When the Figure is rendered, all of the +# Artists are drawn to the **canvas**. Most Artists are tied to an Axes; such +# an Artist cannot be shared by multiple Axes, or moved from one to another. +# +# .. _input_types: +# +# Types of inputs to plotting functions +# ===================================== +# +# Plotting functions expect `numpy.array` or `numpy.ma.masked_array` as +# input, or objects that can be passed to `numpy.asarray`. +# Classes that are similar to arrays ('array-like') such as `pandas` +# data objects and `numpy.matrix` may not work as intended. Common convention +# is to convert these to `numpy.array` objects prior to plotting. +# For example, to convert a `numpy.matrix` :: +# +# b = np.matrix([[1, 2], [3, 4]]) +# b_asarray = np.asarray(b) +# +# Most methods will also parse an addressable object like a *dict*, a +# `numpy.recarray`, or a `pandas.DataFrame`. Matplotlib allows you to +# provide the ``data`` keyword argument and generate plots passing the +# strings corresponding to the *x* and *y* variables. +np.random.seed(19680801) # seed the random number generator. +data = {'a': np.arange(50), + 'c': np.random.randint(0, 50, 50), + 'd': np.random.randn(50)} +data['b'] = data['a'] + 10 * np.random.randn(50) +data['d'] = np.abs(data['d']) * 100 + +fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') +ax.scatter('a', 'b', c='c', s='d', data=data) +ax.set_xlabel('entry a') +ax.set_ylabel('entry b') + +# %% +# .. _coding_styles: +# +# Coding styles +# ============= +# +# The explicit and the implicit interfaces +# ---------------------------------------- +# +# As noted above, there are essentially two ways to use Matplotlib: +# +# - Explicitly create Figures and Axes, and call methods on them (the +# "object-oriented (OO) style"). +# - Rely on pyplot to implicitly create and manage the Figures and Axes, and +# use pyplot functions for plotting. +# +# See :ref:`api_interfaces` for an explanation of the tradeoffs between the +# implicit and explicit interfaces. +# +# So one can use the OO-style + +x = np.linspace(0, 2, 100) # Sample data. + +# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure. +fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') +ax.plot(x, x, label='linear') # Plot some data on the axes. +ax.plot(x, x**2, label='quadratic') # Plot more data on the axes... +ax.plot(x, x**3, label='cubic') # ... and some more. +ax.set_xlabel('x label') # Add an x-label to the axes. +ax.set_ylabel('y label') # Add a y-label to the axes. +ax.set_title("Simple Plot") # Add a title to the axes. +ax.legend() # Add a legend. + +# %% +# or the pyplot-style: + +x = np.linspace(0, 2, 100) # Sample data. + +plt.figure(figsize=(5, 2.7), layout='constrained') +plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes. +plt.plot(x, x**2, label='quadratic') # etc. +plt.plot(x, x**3, label='cubic') +plt.xlabel('x label') +plt.ylabel('y label') +plt.title("Simple Plot") +plt.legend() + +# %% +# (In addition, there is a third approach, for the case when embedding +# Matplotlib in a GUI application, which completely drops pyplot, even for +# figure creation. See the corresponding section in the gallery for more info: +# :ref:`user_interfaces`.) +# +# Matplotlib's documentation and examples use both the OO and the pyplot +# styles. In general, we suggest using the OO style, particularly for +# complicated plots, and functions and scripts that are intended to be reused +# as part of a larger project. However, the pyplot style can be very convenient +# for quick interactive work. +# +# .. note:: +# +# You may find older examples that use the ``pylab`` interface, +# via ``from pylab import *``. This approach is strongly deprecated. +# +# Making a helper functions +# ------------------------- +# +# If you need to make the same plots over and over again with different data +# sets, or want to easily wrap Matplotlib methods, use the recommended +# signature function below. + + +def my_plotter(ax, data1, data2, param_dict): + """ + A helper function to make a graph. + """ + out = ax.plot(data1, data2, **param_dict) + return out + +# %% +# which you would then use twice to populate two subplots: + +data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7)) +my_plotter(ax1, data1, data2, {'marker': 'x'}) +my_plotter(ax2, data3, data4, {'marker': 'o'}) + +# %% +# Note that if you want to install these as a python package, or any other +# customizations you could use one of the many templates on the web; +# Matplotlib has one at `mpl-cookiecutter +# `_ +# +# +# Styling Artists +# =============== +# +# Most plotting methods have styling options for the Artists, accessible either +# when a plotting method is called, or from a "setter" on the Artist. In the +# plot below we manually set the *color*, *linewidth*, and *linestyle* of the +# Artists created by `~.Axes.plot`, and we set the linestyle of the second line +# after the fact with `~.Line2D.set_linestyle`. + +fig, ax = plt.subplots(figsize=(5, 2.7)) +x = np.arange(len(data1)) +ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--') +l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2) +l.set_linestyle(':') + +# %% +# Colors +# ------ +# +# Matplotlib has a very flexible array of colors that are accepted for most +# Artists; see :ref:`allowable color definitions ` for a +# list of specifications. Some Artists will take multiple colors. i.e. for +# a `~.Axes.scatter` plot, the edge of the markers can be different colors +# from the interior: + +fig, ax = plt.subplots(figsize=(5, 2.7)) +ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k') + +# %% +# Linewidths, linestyles, and markersizes +# --------------------------------------- +# +# Line widths are typically in typographic points (1 pt = 1/72 inch) and +# available for Artists that have stroked lines. Similarly, stroked lines +# can have a linestyle. See the :doc:`linestyles example +# `. +# +# Marker size depends on the method being used. `~.Axes.plot` specifies +# markersize in points, and is generally the "diameter" or width of the +# marker. `~.Axes.scatter` specifies markersize as approximately +# proportional to the visual area of the marker. There is an array of +# markerstyles available as string codes (see :mod:`~.matplotlib.markers`), or +# users can define their own `~.MarkerStyle` (see +# :doc:`/gallery/lines_bars_and_markers/marker_reference`): + +fig, ax = plt.subplots(figsize=(5, 2.7)) +ax.plot(data1, 'o', label='data1') +ax.plot(data2, 'd', label='data2') +ax.plot(data3, 'v', label='data3') +ax.plot(data4, 's', label='data4') +ax.legend() + +# %% +# +# Labelling plots +# =============== +# +# Axes labels and text +# -------------------- +# +# `~.Axes.set_xlabel`, `~.Axes.set_ylabel`, and `~.Axes.set_title` are used to +# add text in the indicated locations (see :ref:`text_intro` +# for more discussion). Text can also be directly added to plots using +# `~.Axes.text`: + +mu, sigma = 115, 15 +x = mu + sigma * np.random.randn(10000) +fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') +# the histogram of the data +n, bins, patches = ax.hist(x, 50, density=True, facecolor='C0', alpha=0.75) + +ax.set_xlabel('Length [cm]') +ax.set_ylabel('Probability') +ax.set_title('Aardvark lengths\n (not really)') +ax.text(75, .025, r'$\mu=115,\ \sigma=15$') +ax.axis([55, 175, 0, 0.03]) +ax.grid(True) + +# %% +# All of the `~.Axes.text` functions return a `matplotlib.text.Text` +# instance. Just as with lines above, you can customize the properties by +# passing keyword arguments into the text functions:: +# +# t = ax.set_xlabel('my data', fontsize=14, color='red') +# +# These properties are covered in more detail in +# :ref:`text_props`. +# +# Using mathematical expressions in text +# -------------------------------------- +# +# Matplotlib accepts TeX equation expressions in any text expression. +# For example to write the expression :math:`\sigma_i=15` in the title, +# you can write a TeX expression surrounded by dollar signs:: +# +# ax.set_title(r'$\sigma_i=15$') +# +# where the ``r`` preceding the title string signifies that the string is a +# *raw* string and not to treat backslashes as python escapes. +# Matplotlib has a built-in TeX expression parser and +# layout engine, and ships its own math fonts – for details see +# :ref:`mathtext`. You can also use LaTeX directly to format +# your text and incorporate the output directly into your display figures or +# saved postscript – see :ref:`usetex`. +# +# Annotations +# ----------- +# +# We can also annotate points on a plot, often by connecting an arrow pointing +# to *xy*, to a piece of text at *xytext*: + +fig, ax = plt.subplots(figsize=(5, 2.7)) + +t = np.arange(0.0, 5.0, 0.01) +s = np.cos(2 * np.pi * t) +line, = ax.plot(t, s, lw=2) + +ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), + arrowprops=dict(facecolor='black', shrink=0.05)) + +ax.set_ylim(-2, 2) + +# %% +# In this basic example, both *xy* and *xytext* are in data coordinates. +# There are a variety of other coordinate systems one can choose -- see +# :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for +# details. More examples also can be found in +# :doc:`/gallery/text_labels_and_annotations/annotation_demo`. +# +# Legends +# ------- +# +# Often we want to identify lines or markers with a `.Axes.legend`: + +fig, ax = plt.subplots(figsize=(5, 2.7)) +ax.plot(np.arange(len(data1)), data1, label='data1') +ax.plot(np.arange(len(data2)), data2, label='data2') +ax.plot(np.arange(len(data3)), data3, 'd', label='data3') +ax.legend() + +# %% +# Legends in Matplotlib are quite flexible in layout, placement, and what +# Artists they can represent. They are discussed in detail in +# :ref:`legend_guide`. +# +# Axis scales and ticks +# ===================== +# +# Each Axes has two (or three) `~.axis.Axis` objects representing the x- and +# y-axis. These control the *scale* of the Axis, the tick *locators* and the +# tick *formatters*. Additional Axes can be attached to display further Axis +# objects. +# +# Scales +# ------ +# +# In addition to the linear scale, Matplotlib supplies non-linear scales, +# such as a log-scale. Since log-scales are used so much there are also +# direct methods like `~.Axes.loglog`, `~.Axes.semilogx`, and +# `~.Axes.semilogy`. There are a number of scales (see +# :doc:`/gallery/scales/scales` for other examples). Here we set the scale +# manually: + +fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), layout='constrained') +xdata = np.arange(len(data1)) # make an ordinal for this +data = 10**data1 +axs[0].plot(xdata, data) + +axs[1].set_yscale('log') +axs[1].plot(xdata, data) + +# %% +# The scale sets the mapping from data values to spacing along the Axis. This +# happens in both directions, and gets combined into a *transform*, which +# is the way that Matplotlib maps from data coordinates to Axes, Figure, or +# screen coordinates. See :ref:`transforms_tutorial`. +# +# Tick locators and formatters +# ---------------------------- +# +# Each Axis has a tick *locator* and *formatter* that choose where along the +# Axis objects to put tick marks. A simple interface to this is +# `~.Axes.set_xticks`: + +fig, axs = plt.subplots(2, 1, layout='constrained') +axs[0].plot(xdata, data1) +axs[0].set_title('Automatic ticks') + +axs[1].plot(xdata, data1) +axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90']) +axs[1].set_yticks([-1.5, 0, 1.5]) # note that we don't need to specify labels +axs[1].set_title('Manual ticks') + +# %% +# Different scales can have different locators and formatters; for instance +# the log-scale above uses `~.LogLocator` and `~.LogFormatter`. See +# :doc:`/gallery/ticks/tick-locators` and +# :doc:`/gallery/ticks/tick-formatters` for other formatters and +# locators and information for writing your own. +# +# Plotting dates and strings +# -------------------------- +# +# Matplotlib can handle plotting arrays of dates and arrays of strings, as +# well as floating point numbers. These get special locators and formatters +# as appropriate. For dates: + +fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') +dates = np.arange(np.datetime64('2021-11-15'), np.datetime64('2021-12-25'), + np.timedelta64(1, 'h')) +data = np.cumsum(np.random.randn(len(dates))) +ax.plot(dates, data) +cdf = mpl.dates.ConciseDateFormatter(ax.xaxis.get_major_locator()) +ax.xaxis.set_major_formatter(cdf) + +# %% +# For more information see the date examples +# (e.g. :doc:`/gallery/text_labels_and_annotations/date`) +# +# For strings, we get categorical plotting (see: +# :doc:`/gallery/lines_bars_and_markers/categorical_variables`). + +fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') +categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins'] + +ax.bar(categories, np.random.rand(len(categories))) + +# %% +# One caveat about categorical plotting is that some methods of parsing +# text files return a list of strings, even if the strings all represent +# numbers or dates. If you pass 1000 strings, Matplotlib will think you +# meant 1000 categories and will add 1000 ticks to your plot! +# +# +# Additional Axis objects +# ------------------------ +# +# Plotting data of different magnitude in one chart may require +# an additional y-axis. Such an Axis can be created by using +# `~.Axes.twinx` to add a new Axes with an invisible x-axis and a y-axis +# positioned at the right (analogously for `~.Axes.twiny`). See +# :doc:`/gallery/subplots_axes_and_figures/two_scales` for another example. +# +# Similarly, you can add a `~.Axes.secondary_xaxis` or +# `~.Axes.secondary_yaxis` having a different scale than the main Axis to +# represent the data in different scales or units. See +# :doc:`/gallery/subplots_axes_and_figures/secondary_axis` for further +# examples. + +fig, (ax1, ax3) = plt.subplots(1, 2, figsize=(7, 2.7), layout='constrained') +l1, = ax1.plot(t, s) +ax2 = ax1.twinx() +l2, = ax2.plot(t, range(len(t)), 'C1') +ax2.legend([l1, l2], ['Sine (left)', 'Straight (right)']) + +ax3.plot(t, s) +ax3.set_xlabel('Angle [rad]') +ax4 = ax3.secondary_xaxis('top', functions=(np.rad2deg, np.deg2rad)) +ax4.set_xlabel('Angle [°]') + +# %% +# Color mapped data +# ================= +# +# Often we want to have a third dimension in a plot represented by a colors in +# a colormap. Matplotlib has a number of plot types that do this: + +X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) +Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2) + +fig, axs = plt.subplots(2, 2, layout='constrained') +pc = axs[0, 0].pcolormesh(X, Y, Z, vmin=-1, vmax=1, cmap='RdBu_r') +fig.colorbar(pc, ax=axs[0, 0]) +axs[0, 0].set_title('pcolormesh()') + +co = axs[0, 1].contourf(X, Y, Z, levels=np.linspace(-1.25, 1.25, 11)) +fig.colorbar(co, ax=axs[0, 1]) +axs[0, 1].set_title('contourf()') + +pc = axs[1, 0].imshow(Z**2 * 100, cmap='plasma', + norm=mpl.colors.LogNorm(vmin=0.01, vmax=100)) +fig.colorbar(pc, ax=axs[1, 0], extend='both') +axs[1, 0].set_title('imshow() with LogNorm()') + +pc = axs[1, 1].scatter(data1, data2, c=data3, cmap='RdBu_r') +fig.colorbar(pc, ax=axs[1, 1], extend='both') +axs[1, 1].set_title('scatter()') + +# %% +# Colormaps +# --------- +# +# These are all examples of Artists that derive from `~.ScalarMappable` +# objects. They all can set a linear mapping between *vmin* and *vmax* into +# the colormap specified by *cmap*. Matplotlib has many colormaps to choose +# from (:ref:`colormaps`) you can make your +# own (:ref:`colormap-manipulation`) or download as +# `third-party packages +# `_. +# +# Normalizations +# -------------- +# +# Sometimes we want a non-linear mapping of the data to the colormap, as +# in the ``LogNorm`` example above. We do this by supplying the +# ScalarMappable with the *norm* argument instead of *vmin* and *vmax*. +# More normalizations are shown at :ref:`colormapnorms`. +# +# Colorbars +# --------- +# +# Adding a `~.Figure.colorbar` gives a key to relate the color back to the +# underlying data. Colorbars are figure-level Artists, and are attached to +# a ScalarMappable (where they get their information about the norm and +# colormap) and usually steal space from a parent Axes. Placement of +# colorbars can be complex: see +# :ref:`colorbar_placement` for +# details. You can also change the appearance of colorbars with the +# *extend* keyword to add arrows to the ends, and *shrink* and *aspect* to +# control the size. Finally, the colorbar will have default locators +# and formatters appropriate to the norm. These can be changed as for +# other Axis objects. +# +# +# Working with multiple Figures and Axes +# ====================================== +# +# You can open multiple Figures with multiple calls to +# ``fig = plt.figure()`` or ``fig2, ax = plt.subplots()``. By keeping the +# object references you can add Artists to either Figure. +# +# Multiple Axes can be added a number of ways, but the most basic is +# ``plt.subplots()`` as used above. One can achieve more complex layouts, +# with Axes objects spanning columns or rows, using `~.pyplot.subplot_mosaic`. + +fig, axd = plt.subplot_mosaic([['upleft', 'right'], + ['lowleft', 'right']], layout='constrained') +axd['upleft'].set_title('upleft') +axd['lowleft'].set_title('lowleft') +axd['right'].set_title('right') + +# %% +# Matplotlib has quite sophisticated tools for arranging Axes: See +# :ref:`arranging_axes` and :ref:`mosaic`. +# +# +# More reading +# ============ +# +# For more plot types see :doc:`Plot types ` and the +# :doc:`API reference `, in particular the +# :doc:`Axes API `. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/README.txt b/testbed/matplotlib__matplotlib/galleries/users_explain/text/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..9046e991c92485f5b5e13e23f55f9677007a1e59 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/README.txt @@ -0,0 +1,14 @@ +.. redirect-from:: /tutorials/text + +.. _tutorials-text: + +Text +---- + +Matplotlib has extensive text support, including support for +mathematical expressions, TrueType support for raster and +vector outputs, newline separated text with arbitrary +rotations, and Unicode support. These tutorials cover +the basics of working with text in Matplotlib. + +For even more information see the :ref:`examples page `. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/annotations.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..a28f5419a8ba883d643843f94e14a9315038b2e2 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/annotations.py @@ -0,0 +1,748 @@ +r""" +.. redirect-from:: /gallery/userdemo/annotate_simple01 +.. redirect-from:: /gallery/userdemo/annotate_simple02 +.. redirect-from:: /gallery/userdemo/annotate_simple03 +.. redirect-from:: /gallery/userdemo/annotate_simple04 +.. redirect-from:: /gallery/userdemo/anchored_box04 +.. redirect-from:: /gallery/userdemo/annotate_simple_coord01 +.. redirect-from:: /gallery/userdemo/annotate_simple_coord02 +.. redirect-from:: /gallery/userdemo/annotate_simple_coord03 +.. redirect-from:: /gallery/userdemo/connect_simple01 +.. redirect-from:: /tutorials/text/annotations + +.. _annotations: + +Annotations +=========== + +Annotations are graphical elements, often pieces of text, that explain, add +context to, or otherwise highlight some portion of the visualized data. +`~.Axes.annotate` supports a number of coordinate systems for flexibly +positioning data and annotations relative to each other and a variety of +options of for styling the text. Axes.annotate also provides an optional arrow +from the text to the data and this arrow can be styled in various ways. +`~.Axes.text` can also be used for simple text annotation, but does not +provide as much flexibility in positioning and styling as `~.Axes.annotate`. + +.. contents:: Table of Contents + :depth: 3 +""" +# %% +# .. _annotations-tutorial: +# +# Basic annotation +# ---------------- +# +# In an annotation, there are two points to consider: the location of the data +# being annotated *xy* and the location of the annotation text *xytext*. Both +# of these arguments are ``(x, y)`` tuples: + +import matplotlib.pyplot as plt +import numpy as np + +fig, ax = plt.subplots(figsize=(3, 3)) + +t = np.arange(0.0, 5.0, 0.01) +s = np.cos(2*np.pi*t) +line, = ax.plot(t, s, lw=2) + +ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), + arrowprops=dict(facecolor='black', shrink=0.05)) +ax.set_ylim(-2, 2) + +# %% +# In this example, both the *xy* (arrow tip) and *xytext* locations +# (text location) are in data coordinates. There are a variety of other +# coordinate systems one can choose -- you can specify the coordinate +# system of *xy* and *xytext* with one of the following strings for +# *xycoords* and *textcoords* (default is 'data') +# +# ================== ======================================================== +# argument coordinate system +# ================== ======================================================== +# 'figure points' points from the lower left corner of the figure +# 'figure pixels' pixels from the lower left corner of the figure +# 'figure fraction' (0, 0) is lower left of figure and (1, 1) is upper right +# 'axes points' points from lower left corner of axes +# 'axes pixels' pixels from lower left corner of axes +# 'axes fraction' (0, 0) is lower left of axes and (1, 1) is upper right +# 'data' use the axes data coordinate system +# ================== ======================================================== +# +# The following strings are also valid arguments for *textcoords* +# +# ================== ======================================================== +# argument coordinate system +# ================== ======================================================== +# 'offset points' offset (in points) from the xy value +# 'offset pixels' offset (in pixels) from the xy value +# ================== ======================================================== +# +# For physical coordinate systems (points or pixels) the origin is the +# bottom-left of the figure or axes. Points are +# `typographic points `_ +# meaning that they are a physical unit measuring 1/72 of an inch. Points and +# pixels are discussed in further detail in :ref:`transforms-fig-scale-dpi`. +# +# .. _annotation-data: +# +# Annotating data +# ^^^^^^^^^^^^^^^ +# +# This example places the text coordinates in fractional axes coordinates: + +fig, ax = plt.subplots(figsize=(3, 3)) + +t = np.arange(0.0, 5.0, 0.01) +s = np.cos(2*np.pi*t) +line, = ax.plot(t, s, lw=2) + +ax.annotate('local max', xy=(2, 1), xycoords='data', + xytext=(0.01, .99), textcoords='axes fraction', + va='top', ha='left', + arrowprops=dict(facecolor='black', shrink=0.05)) +ax.set_ylim(-2, 2) + +# %% +# +# Annotating an Artist +# ^^^^^^^^^^^^^^^^^^^^ +# +# Annotations can be positioned relative to an `.Artist` instance by passing +# that Artist in as *xycoords*. Then *xy* is interpreted as a fraction of the +# Artist's bounding box. + +import matplotlib.patches as mpatches + +fig, ax = plt.subplots(figsize=(3, 3)) +arr = mpatches.FancyArrowPatch((1.25, 1.5), (1.75, 1.5), + arrowstyle='->,head_width=.15', mutation_scale=20) +ax.add_patch(arr) +ax.annotate("label", (.5, .5), xycoords=arr, ha='center', va='bottom') +ax.set(xlim=(1, 2), ylim=(1, 2)) + +# %% +# Here the annotation is placed at position (.5,.5) relative to the arrow's +# lower left corner and is vertically and horizontally at that position. +# Vertically, the bottom aligns to that reference point so that the label +# is above the line. For an example of chaining annotation Artists, see the +# :ref:`Artist section ` of +# :ref:`annotating_coordinate_systems`. +# +# +# .. _annotation-with-arrow: +# +# Annotating with arrows +# ^^^^^^^^^^^^^^^^^^^^^^ +# +# You can enable drawing of an arrow from the text to the annotated point +# by giving a dictionary of arrow properties in the optional keyword +# argument *arrowprops*. +# +# ==================== ===================================================== +# *arrowprops* key description +# ==================== ===================================================== +# width the width of the arrow in points +# frac the fraction of the arrow length occupied by the head +# headwidth the width of the base of the arrow head in points +# shrink move the tip and base some percent away from +# the annotated point and text +# +# \*\*kwargs any key for :class:`matplotlib.patches.Polygon`, +# e.g., ``facecolor`` +# ==================== ===================================================== +# +# In the example below, the *xy* point is in the data coordinate system +# since *xycoords* defaults to 'data'. For a polar axes, this is in +# (theta, radius) space. The text in this example is placed in the +# fractional figure coordinate system. :class:`matplotlib.text.Text` +# keyword arguments like *horizontalalignment*, *verticalalignment* and +# *fontsize* are passed from `~matplotlib.axes.Axes.annotate` to the +# ``Text`` instance. + +fig = plt.figure() +ax = fig.add_subplot(projection='polar') +r = np.arange(0, 1, 0.001) +theta = 2 * 2*np.pi * r +line, = ax.plot(theta, r, color='#ee8d18', lw=3) + +ind = 800 +thisr, thistheta = r[ind], theta[ind] +ax.plot([thistheta], [thisr], 'o') +ax.annotate('a polar annotation', + xy=(thistheta, thisr), # theta, radius + xytext=(0.05, 0.05), # fraction, fraction + textcoords='figure fraction', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='left', + verticalalignment='bottom') + +# %% +# For more on plotting with arrows, see :ref:`annotation_with_custom_arrow` +# +# .. _annotations-offset-text: +# +# Placing text annotations relative to data +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# Annotations can be positioned at a relative offset to the *xy* input to +# annotation by setting the *textcoords* keyword argument to ``'offset points'`` +# or ``'offset pixels'``. + +fig, ax = plt.subplots(figsize=(3, 3)) +x = [1, 3, 5, 7, 9] +y = [2, 4, 6, 8, 10] +annotations = ["A", "B", "C", "D", "E"] +ax.scatter(x, y, s=20) + +for xi, yi, text in zip(x, y, annotations): + ax.annotate(text, + xy=(xi, yi), xycoords='data', + xytext=(1.5, 1.5), textcoords='offset points') + +# %% +# The annotations are offset 1.5 points (1.5*1/72 inches) from the *xy* values. +# +# .. _plotting-guide-annotation: +# +# Advanced annotation +# ------------------- +# +# We recommend reading :ref:`annotations-tutorial`, :func:`~matplotlib.pyplot.text` +# and :func:`~matplotlib.pyplot.annotate` before reading this section. +# +# Annotating with boxed text +# ^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# `~.Axes.text` takes a *bbox* keyword argument, which draws a box around the +# text: + +fig, ax = plt.subplots(figsize=(5, 5)) +t = ax.text(0.5, 0.5, "Direction", + ha="center", va="center", rotation=45, size=15, + bbox=dict(boxstyle="rarrow,pad=0.3", + fc="lightblue", ec="steelblue", lw=2)) + +# %% +# The arguments are the name of the box style with its attributes as +# keyword arguments. Currently, following box styles are implemented: +# +# ========== ============== ========================== +# Class Name Attrs +# ========== ============== ========================== +# Circle ``circle`` pad=0.3 +# DArrow ``darrow`` pad=0.3 +# Ellipse ``ellipse`` pad=0.3 +# LArrow ``larrow`` pad=0.3 +# RArrow ``rarrow`` pad=0.3 +# Round ``round`` pad=0.3,rounding_size=None +# Round4 ``round4`` pad=0.3,rounding_size=None +# Roundtooth ``roundtooth`` pad=0.3,tooth_size=None +# Sawtooth ``sawtooth`` pad=0.3,tooth_size=None +# Square ``square`` pad=0.3 +# ========== ============== ========================== +# +# .. figure:: /gallery/shapes_and_collections/images/sphx_glr_fancybox_demo_001.png +# :target: /gallery/shapes_and_collections/fancybox_demo.html +# :align: center +# +# The patch object (box) associated with the text can be accessed using:: +# +# bb = t.get_bbox_patch() +# +# The return value is a `.FancyBboxPatch`; patch properties +# (facecolor, edgewidth, etc.) can be accessed and modified as usual. +# `.FancyBboxPatch.set_boxstyle` sets the box shape:: +# +# bb.set_boxstyle("rarrow", pad=0.6) +# +# The attribute arguments can also be specified within the style +# name with separating comma:: +# +# bb.set_boxstyle("rarrow, pad=0.6") +# +# +# Defining custom box styles +# ^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# You can use a custom box style. The value for the ``boxstyle`` can be a +# callable object in the following forms: + +from matplotlib.path import Path + + +def custom_box_style(x0, y0, width, height, mutation_size): + """ + Given the location and size of the box, return the path of the box around + it. Rotation is automatically taken care of. + + Parameters + ---------- + x0, y0, width, height : float + Box location and size. + mutation_size : float + Mutation reference scale, typically the text font size. + """ + # padding + mypad = 0.3 + pad = mutation_size * mypad + # width and height with padding added. + width = width + 2 * pad + height = height + 2 * pad + # boundary of the padded box + x0, y0 = x0 - pad, y0 - pad + x1, y1 = x0 + width, y0 + height + # return the new path + return Path([(x0, y0), (x1, y0), (x1, y1), (x0, y1), + (x0-pad, (y0+y1)/2), (x0, y0), (x0, y0)], + closed=True) + +fig, ax = plt.subplots(figsize=(3, 3)) +ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", rotation=30, + bbox=dict(boxstyle=custom_box_style, alpha=0.2)) + +# %% +# See also :doc:`/gallery/userdemo/custom_boxstyle01`. Similarly, you can define a +# custom `.ConnectionStyle` and a custom `.ArrowStyle`. View the source code at +# `.patches` to learn how each class is defined. +# +# .. _annotation_with_custom_arrow: +# +# Customizing annotation arrows +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# An arrow connecting *xy* to *xytext* can be optionally drawn by +# specifying the *arrowprops* argument. To draw only an arrow, use +# empty string as the first argument: + +fig, ax = plt.subplots(figsize=(3, 3)) +ax.annotate("", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + arrowprops=dict(arrowstyle="->", connectionstyle="arc3")) + +# %% +# The arrow is drawn as follows: +# +# 1. A path connecting the two points is created, as specified by the +# *connectionstyle* parameter. +# 2. The path is clipped to avoid patches *patchA* and *patchB*, if these are +# set. +# 3. The path is further shrunk by *shrinkA* and *shrinkB* (in pixels). +# 4. The path is transmuted to an arrow patch, as specified by the *arrowstyle* +# parameter. +# +# .. figure:: /gallery/userdemo/images/sphx_glr_annotate_explain_001.png +# :target: /gallery/userdemo/annotate_explain.html +# :align: center +# +# The creation of the connecting path between two points is controlled by +# ``connectionstyle`` key and the following styles are available: +# +# ========== ============================================= +# Name Attrs +# ========== ============================================= +# ``angle`` angleA=90,angleB=0,rad=0.0 +# ``angle3`` angleA=90,angleB=0 +# ``arc`` angleA=0,angleB=0,armA=None,armB=None,rad=0.0 +# ``arc3`` rad=0.0 +# ``bar`` armA=0.0,armB=0.0,fraction=0.3,angle=None +# ========== ============================================= +# +# Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the +# resulting path is a quadratic spline segment (three control +# points). As will be discussed below, some arrow style options can only +# be used when the connecting path is a quadratic spline. +# +# The behavior of each connection style is (limitedly) demonstrated in the +# example below. (Warning: The behavior of the ``bar`` style is currently not +# well-defined and may be changed in the future). +# +# .. figure:: /gallery/userdemo/images/sphx_glr_connectionstyle_demo_001.png +# :target: /gallery/userdemo/connectionstyle_demo.html +# :align: center +# +# The connecting path (after clipping and shrinking) is then mutated to +# an arrow patch, according to the given ``arrowstyle``: +# +# ========== ============================================= +# Name Attrs +# ========== ============================================= +# ``-`` None +# ``->`` head_length=0.4,head_width=0.2 +# ``-[`` widthB=1.0,lengthB=0.2,angleB=None +# ``|-|`` widthA=1.0,widthB=1.0 +# ``-|>`` head_length=0.4,head_width=0.2 +# ``<-`` head_length=0.4,head_width=0.2 +# ``<->`` head_length=0.4,head_width=0.2 +# ``<|-`` head_length=0.4,head_width=0.2 +# ``<|-|>`` head_length=0.4,head_width=0.2 +# ``fancy`` head_length=0.4,head_width=0.4,tail_width=0.4 +# ``simple`` head_length=0.5,head_width=0.5,tail_width=0.2 +# ``wedge`` tail_width=0.3,shrink_factor=0.5 +# ========== ============================================= +# +# .. figure:: /gallery/text_labels_and_annotations/images/sphx_glr_fancyarrow_demo_001.png +# :target: /gallery/text_labels_and_annotations/fancyarrow_demo.html +# :align: center +# +# Some arrowstyles only work with connection styles that generate a +# quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``. +# For these arrow styles, you must use the "angle3" or "arc3" connection +# style. +# +# If the annotation string is given, the patch is set to the bbox patch +# of the text by default. + +fig, ax = plt.subplots(figsize=(3, 3)) + +ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + arrowprops=dict(arrowstyle="simple", + connectionstyle="arc3,rad=-0.2")) + +# %% +# As with `~.Axes.text`, a box around the text can be drawn using the *bbox* +# argument. + +fig, ax = plt.subplots(figsize=(3, 3)) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=-0.2", + fc="w")) + +# %% +# By default, the starting point is set to the center of the text +# extent. This can be adjusted with ``relpos`` key value. The values +# are normalized to the extent of the text. For example, (0, 0) means +# lower-left corner and (1, 1) means top-right. + +fig, ax = plt.subplots(figsize=(3, 3)) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=0.2", + relpos=(0., 0.), + fc="w")) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=-0.2", + relpos=(1., 0.), + fc="w")) + +# %% +# Placing Artist at anchored Axes locations +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# There are classes of artists that can be placed at an anchored +# location in the Axes. A common example is the legend. This type +# of artist can be created by using the `.OffsetBox` class. A few +# predefined classes are available in :mod:`matplotlib.offsetbox` and in +# :mod:`mpl_toolkits.axes_grid1.anchored_artists`. + +from matplotlib.offsetbox import AnchoredText + +fig, ax = plt.subplots(figsize=(3, 3)) +at = AnchoredText("Figure 1a", + prop=dict(size=15), frameon=True, loc='upper left') +at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") +ax.add_artist(at) + +# %% +# The *loc* keyword has same meaning as in the legend command. +# +# A simple application is when the size of the artist (or collection of +# artists) is known in pixel size during the time of creation. For +# example, If you want to draw a circle with fixed size of 20 pixel x 20 +# pixel (radius = 10 pixel), you can utilize +# `~mpl_toolkits.axes_grid1.anchored_artists.AnchoredDrawingArea`. The instance +# is created with a size of the drawing area (in pixels), and arbitrary artists +# can be added to the drawing area. Note that the extents of the artists that are +# added to the drawing area are not related to the placement of the drawing +# area itself. Only the initial size matters. +# +# The artists that are added to the drawing area should not have a +# transform set (it will be overridden) and the dimensions of those +# artists are interpreted as a pixel coordinate, i.e., the radius of the +# circles in above example are 10 pixels and 5 pixels, respectively. + +from matplotlib.patches import Circle +from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea + +fig, ax = plt.subplots(figsize=(3, 3)) +ada = AnchoredDrawingArea(40, 20, 0, 0, + loc='upper right', pad=0., frameon=False) +p1 = Circle((10, 10), 10) +ada.drawing_area.add_artist(p1) +p2 = Circle((30, 10), 5, fc="r") +ada.drawing_area.add_artist(p2) +ax.add_artist(ada) + +# %% +# Sometimes, you want your artists to scale with the data coordinate (or +# coordinates other than canvas pixels). You can use +# `~mpl_toolkits.axes_grid1.anchored_artists.AnchoredAuxTransformBox` class. +# This is similar to +# `~mpl_toolkits.axes_grid1.anchored_artists.AnchoredDrawingArea` except that +# the extent of the artist is determined during the drawing time respecting the +# specified transform. +# +# The ellipse in the example below will have width and height +# corresponding to 0.1 and 0.4 in data coordinates and will be +# automatically scaled when the view limits of the axes change. + +from matplotlib.patches import Ellipse +from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox + +fig, ax = plt.subplots(figsize=(3, 3)) +box = AnchoredAuxTransformBox(ax.transData, loc='upper left') +el = Ellipse((0, 0), width=0.1, height=0.4, angle=30) # in data coordinates! +box.drawing_area.add_artist(el) +ax.add_artist(box) + +# %% +# Another method of anchoring an artist relative to a parent axes or anchor +# point is via the *bbox_to_anchor* argument of `.AnchoredOffsetbox`. This +# artist can then be automatically positioned relative to another artist using +# `.HPacker` and `.VPacker`: + +from matplotlib.offsetbox import (AnchoredOffsetbox, DrawingArea, HPacker, + TextArea) + +fig, ax = plt.subplots(figsize=(3, 3)) + +box1 = TextArea(" Test: ", textprops=dict(color="k")) +box2 = DrawingArea(60, 20, 0, 0) + +el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r") +el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc="g") +el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc="b") +box2.add_artist(el1) +box2.add_artist(el2) +box2.add_artist(el3) + +box = HPacker(children=[box1, box2], + align="center", + pad=0, sep=5) + +anchored_box = AnchoredOffsetbox(loc='lower left', + child=box, pad=0., + frameon=True, + bbox_to_anchor=(0., 1.02), + bbox_transform=ax.transAxes, + borderpad=0.,) + +ax.add_artist(anchored_box) +fig.subplots_adjust(top=0.8) + +# %% +# Note that, unlike in `.Legend`, the ``bbox_transform`` is set to +# `.IdentityTransform` by default +# +# .. _annotating_coordinate_systems: +# +# Coordinate systems for annotations +# ---------------------------------- +# +# Matplotlib Annotations support several types of coordinate systems. The +# examples in :ref:`annotations-tutorial` used the ``data`` coordinate system; +# Some others more advanced options are: +# +# `.Transform` instance +# ^^^^^^^^^^^^^^^^^^^^^ +# +# Transforms map coordinates into different coordinate systems, usually the +# display coordinate system. See :ref:`transforms_tutorial` for a detailed +# explanation. Here Transform objects are used to identify the coordinate +# system of the corresponding points. For example, the ``Axes.transAxes`` +# transform positions the annotation relative to the Axes coordinates; therefore +# using it is identical to setting the coordinate system to "axes fraction": + +fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) +ax1.annotate("Test", xy=(0.2, 0.2), xycoords=ax1.transAxes) +ax2.annotate("Test", xy=(0.2, 0.2), xycoords="axes fraction") + +# %% +# Another commonly used `.Transform` instance is ``Axes.transData``. This +# transform is the coordinate system of the data plotted in the axes. In this +# example, it is used to draw an arrow between related data points in two +# Axes. We have passed an empty text because in this case, the annotation +# connects data points. + +x = np.linspace(-1, 1) + +fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) +ax1.plot(x, -x**3) +ax2.plot(x, -3*x**2) +ax2.annotate("", + xy=(0, 0), xycoords=ax1.transData, + xytext=(0, 0), textcoords=ax2.transData, + arrowprops=dict(arrowstyle="<->")) + +# %% +# .. _artist_annotation_coord: +# +# `.Artist` instance +# ^^^^^^^^^^^^^^^^^^ +# +# The *xy* value (or *xytext*) is interpreted as a fractional coordinate of the +# bounding box (bbox) of the artist: + +fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 3)) +an1 = ax.annotate("Test 1", + xy=(0.5, 0.5), xycoords="data", + va="center", ha="center", + bbox=dict(boxstyle="round", fc="w")) + +an2 = ax.annotate("Test 2", + xy=(1, 0.5), xycoords=an1, # (1, 0.5) of an1's bbox + xytext=(30, 0), textcoords="offset points", + va="center", ha="left", + bbox=dict(boxstyle="round", fc="w"), + arrowprops=dict(arrowstyle="->")) + +# %% +# Note that you must ensure that the extent of the coordinate artist (*an1* in +# this example) is determined before *an2* gets drawn. Usually, this means +# that *an2* needs to be drawn after *an1*. The base class for all bounding +# boxes is `.BboxBase` +# +# Callable that returns `.Transform` of `.BboxBase` +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# A callable object that takes the renderer instance as single argument, and +# returns either a `.Transform` or a `.BboxBase`. For example, the return +# value of `.Artist.get_window_extent` is a bbox, so this method is identical +# to (2) passing in the artist: + +fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 3)) +an1 = ax.annotate("Test 1", + xy=(0.5, 0.5), xycoords="data", + va="center", ha="center", + bbox=dict(boxstyle="round", fc="w")) + +an2 = ax.annotate("Test 2", + xy=(1, 0.5), xycoords=an1.get_window_extent, + xytext=(30, 0), textcoords="offset points", + va="center", ha="left", + bbox=dict(boxstyle="round", fc="w"), + arrowprops=dict(arrowstyle="->")) + +# %% +# `.Artist.get_window_extent` is the bounding box of the Axes object and is +# therefore identical to setting the coordinate system to axes fraction: + +fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) + +an1 = ax1.annotate("Test1", xy=(0.5, 0.5), xycoords="axes fraction") +an2 = ax2.annotate("Test 2", xy=(0.5, 0.5), xycoords=ax2.get_window_extent) + +# %% +# Blended coordinate specification +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# A blended pair of coordinate specifications -- the first for the +# x-coordinate, and the second is for the y-coordinate. For example, x=0.5 is +# in data coordinates, and y=1 is in normalized axes coordinates: + +fig, ax = plt.subplots(figsize=(3, 3)) +ax.annotate("Test", xy=(0.5, 1), xycoords=("data", "axes fraction")) +ax.axvline(x=.5, color='lightgray') +ax.set(xlim=(0, 2), ylim=(1, 2)) + +# %% +# Any of the supported coordinate systems can be used in a blended +# specification. For example, the text "Anchored to 1 & 2" is positioned +# relative to the two `.Text` Artists: + +fig, ax = plt.subplots(figsize=(3, 3)) + +t1 = ax.text(0.05, .05, "Text 1", va='bottom', ha='left') +t2 = ax.text(0.90, .90, "Text 2", ha='right') +t3 = ax.annotate("Anchored to 1 & 2", xy=(0, 0), xycoords=(t1, t2), + va='bottom', color='tab:orange',) + +# %% +# `.text.OffsetFrom` +# ^^^^^^^^^^^^^^^^^^ +# +# Sometimes, you want your annotation with some "offset points", not from the +# annotated point but from some other point or artist. `.text.OffsetFrom` is +# a helper for such cases. + +from matplotlib.text import OffsetFrom + +fig, ax = plt.subplots(figsize=(3, 3)) +an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data", + va="center", ha="center", + bbox=dict(boxstyle="round", fc="w")) + +offset_from = OffsetFrom(an1, (0.5, 0)) +an2 = ax.annotate("Test 2", xy=(0.1, 0.1), xycoords="data", + xytext=(0, -10), textcoords=offset_from, + # xytext is offset points from "xy=(0.5, 0), xycoords=an1" + va="top", ha="center", + bbox=dict(boxstyle="round", fc="w"), + arrowprops=dict(arrowstyle="->")) + +# %% +# Non-text annotations +# -------------------- +# +# .. _using_connectionpatch: +# +# Using ConnectionPatch +# ^^^^^^^^^^^^^^^^^^^^^ +# +# `.ConnectionPatch` is like an annotation without text. While `~.Axes.annotate` +# is sufficient in most situations, `.ConnectionPatch` is useful when you want +# to connect points in different axes. For example, here we connect the point +# *xy* in the data coordinates of ``ax1`` to point *xy* in the data coordinates +# of ``ax2``: + +from matplotlib.patches import ConnectionPatch + +fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) +xy = (0.3, 0.2) +con = ConnectionPatch(xyA=xy, coordsA=ax1.transData, + xyB=xy, coordsB=ax2.transData) + +fig.add_artist(con) + +# %% +# Here, we added the `.ConnectionPatch` to the *figure* +# (with `~.Figure.add_artist`) rather than to either axes. This ensures that +# the ConnectionPatch artist is drawn on top of both axes, and is also necessary +# when using :ref:`constrained_layout ` +# for positioning the axes. +# +# Zoom effect between Axes +# ^^^^^^^^^^^^^^^^^^^^^^^^ +# +# `mpl_toolkits.axes_grid1.inset_locator` defines some patch classes useful for +# interconnecting two axes. +# +# .. figure:: /gallery/subplots_axes_and_figures/images/sphx_glr_axes_zoom_effect_001.png +# :target: /gallery/subplots_axes_and_figures/axes_zoom_effect.html +# :align: center +# +# The code for this figure is at +# :doc:`/gallery/subplots_axes_and_figures/axes_zoom_effect` and +# familiarity with :ref:`transforms_tutorial` +# is recommended. diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/fonts.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/fonts.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb2de82ff5cc7f2c02b250f280de6ba3f992479 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/fonts.py @@ -0,0 +1,201 @@ +r""" +.. redirect-from:: /users/fonts +.. redirect-from:: /users/explain/fonts + +.. _fonts: + +Fonts in Matplotlib +=================== + +Matplotlib needs fonts to work with its text engine, some of which are shipped +alongside the installation. The default font is `DejaVu Sans +`_ which covers most European writing systems. +However, users can configure the default fonts, and provide their own custom +fonts. See :ref:`Customizing text properties ` for +details and :ref:`font-nonlatin` in particular for glyphs not supported by +DejaVu Sans. + +Matplotlib also provides an option to offload text rendering to a TeX engine +(``usetex=True``), see :ref:`Text rendering with LaTeX +`. + +Fonts in PDF and PostScript +--------------------------- + +Fonts have a long (and sometimes incompatible) history in computing, leading to +different platforms supporting different types of fonts. In practice, +Matplotlib supports three font specifications (in addition to pdf 'core fonts', +which are explained later in the guide): + +.. list-table:: Type of Fonts + :header-rows: 1 + + * - Type 1 (PDF) + - Type 3 (PDF/PS) + - TrueType (PDF) + * - One of the oldest types, introduced by Adobe + - Similar to Type 1 in terms of introduction + - Newer than previous types, used commonly today, introduced by Apple + * - Restricted subset of PostScript, charstrings are in bytecode + - Full PostScript language, allows embedding arbitrary code + (in theory, even render fractals when rasterizing!) + - Include a virtual machine that can execute code! + * - These fonts support font hinting + - Do not support font hinting + - Hinting supported (virtual machine processes the "hints") + * - Non-subsetted through Matplotlib + - Subsetted via external module ttconv + - Subsetted via external module + `fontTools `__ + +.. note:: + + Adobe disabled__ support for authoring with Type 1 fonts in January 2023. + + __ https://helpx.adobe.com/fonts/kb/postscript-type-1-fonts-end-of-support.html + +Other font specifications which Matplotlib supports: + +- Type 42 fonts (PS): + + - PostScript wrapper around TrueType fonts + - 42 is the `Answer to Life, the Universe, and Everything! + `_ + - Matplotlib uses the external library + `fontTools `__ to subset these types of + fonts + +- OpenType fonts: + + - OpenType is a new standard for digital type fonts, developed jointly by + Adobe and Microsoft + - Generally contain a much larger character set! + - Limited support with Matplotlib + +Font subsetting +~~~~~~~~~~~~~~~ + +The PDF and PostScript formats support embedding fonts in files, allowing the +display program to correctly render the text, independent of what fonts are +installed on the viewer's computer and without the need to pre-rasterize the text. +This ensures that if the output is zoomed or resized the text does not become +pixelated. However, embedding full fonts in the file can lead to large output +files, particularly with fonts with many glyphs such as those that support CJK +(Chinese/Japanese/Korean). + +The solution to this problem is to subset the fonts used in the document and +only embed the glyphs actually used. This gets both vector text and small +files sizes. Computing the subset of the font required and writing the new +(reduced) font are both complex problem and thus Matplotlib relies on +`fontTools `__ and a vendored fork +of ttconv. + +Currently Type 3, Type 42, and TrueType fonts are subsetted. Type 1 fonts are not. + +Core Fonts +~~~~~~~~~~ + +In addition to the ability to embed fonts, as part of the `PostScript +`_ and `PDF +specification +`_ +there are 14 Core Fonts that compliant viewers must ensure are available. If +you restrict your document to only these fonts you do not have to embed any +font information in the document but still get vector text. + +This is especially helpful to generate *really lightweight* documents:: + + # trigger core fonts for PDF backend + plt.rcParams["pdf.use14corefonts"] = True + # trigger core fonts for PS backend + plt.rcParams["ps.useafm"] = True + + chars = "AFM ftw!" + fig, ax = plt.subplots() + ax.text(0.5, 0.5, chars) + + fig.savefig("AFM_PDF.pdf", format="pdf") + fig.savefig("AFM_PS.ps", format="ps") + +Fonts in SVG +------------ + +Text can output to SVG in two ways controlled by :rc:`svg.fonttype`: + +- as a path (``'path'``) in the SVG +- as string in the SVG with font styling on the element (``'none'``) + +When saving via ``'path'`` Matplotlib will compute the path of the glyphs used +as vector paths and write those to the output. The advantage of doing so is +that the SVG will look the same on all computers independent of what fonts are +installed. However the text will not be editable after the fact. +In contrast, saving with ``'none'`` will result in smaller files and the +text will appear directly in the markup. However, the appearance may vary +based on the SVG viewer and what fonts are available. + +Fonts in Agg +------------ + +To output text to raster formats via Agg, Matplotlib relies on `FreeType +`_. Because the exact rendering of the glyphs +changes between FreeType versions we pin to a specific version for our image +comparison tests. + +How Matplotlib selects fonts +---------------------------- + +Internally, using a font in Matplotlib is a three step process: + +1. a `.FontProperties` object is created (explicitly or implicitly) +2. based on the `.FontProperties` object the methods on `.FontManager` are used + to select the closest "best" font Matplotlib is aware of (except for + ``'none'`` mode of SVG). +3. the Python proxy for the font object is used by the backend code to render + the text -- the exact details depend on the backend via `.font_manager.get_font`. + +The algorithm to select the "best" font is a modified version of the algorithm +specified by the `CSS1 Specifications +`_ which is used by web browsers. +This algorithm takes into account the font family name (e.g. "Arial", "Noto +Sans CJK", "Hack", ...), the size, style, and weight. In addition to family +names that map directly to fonts there are five "generic font family names" +(serif, monospace, fantasy, cursive, and sans-serif) that will internally be +mapped to any one of a set of fonts. + +Currently the public API for doing step 2 is `.FontManager.findfont` (and that +method on the global `.FontManager` instance is aliased at the module level as +`.font_manager.findfont`), which will only find a single font and return the absolute +path to the font on the filesystem. + +Font fallback +------------- + +There is no font that covers the entire Unicode space thus it is possible for the +users to require a mix of glyphs that cannot be satisfied from a single font. +While it has been possible to use multiple fonts within a Figure, on distinct +`.Text` instances, it was not previous possible to use multiple fonts in the +same `.Text` instance (as a web browser does). As of Matplotlib 3.6 the Agg, +SVG, PDF, and PS backends will "fallback" through multiple fonts in a single +`.Text` instance: + +.. plot:: + :include-source: + :caption: The string "There are 几个汉字 in between!" rendered with 2 fonts. + + fig, ax = plt.subplots() + ax.text( + .5, .5, "There are 几个汉字 in between!", + family=['DejaVu Sans', 'Noto Sans CJK JP', 'Noto Sans TC'], + ha='center' + ) + +Internally this is implemented by setting The "font family" on +`.FontProperties` objects to a list of font families. A (currently) +private API extracts a list of paths to all of the fonts found and then +constructs a single `.ft2font.FT2Font` object that is aware of all of the fonts. +Each glyph of the string is rendered using the first font in the list that +contains that glyph. + +A majority of this work was done by Aitik Gupta supported by Google Summer of +Code 2021. +""" diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/mathtext.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/mathtext.py new file mode 100644 index 0000000000000000000000000000000000000000..0b786e3e7ed017ad2fca3c955a4459502707708a --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/mathtext.py @@ -0,0 +1,371 @@ +r""" + +.. redirect-from:: /tutorials/text/mathtext + +.. _mathtext: + +Writing mathematical expressions +================================ + +You can use a subset of TeX markup in any Matplotlib text string by placing it +inside a pair of dollar signs ($). + +Note that you do not need to have TeX installed, since Matplotlib ships +its own TeX expression parser, layout engine, and fonts. The layout engine +is a fairly direct adaptation of the layout algorithms in Donald Knuth's +TeX, so the quality is quite good (Matplotlib also provides a ``usetex`` +option for those who do want to call out to TeX to generate their text; see +:ref:`usetex`). + +Any text element can use math text. You should use raw strings (precede the +quotes with an ``'r'``), and surround the math text with dollar signs ($), as +in TeX. Regular text and mathtext can be interleaved within the same string. +Mathtext can use DejaVu Sans (default), DejaVu Serif, the Computer Modern fonts +(from (La)TeX), `STIX `_ fonts (which are designed +to blend well with Times), or a Unicode font that you provide. The mathtext +font can be selected via :rc:`mathtext.fontset` (see +:ref:`customizing`) + +Here is a simple example:: + + # plain text + plt.title('alpha > beta') + +produces "alpha > beta". + +Whereas this:: + + # math text + plt.title(r'$\alpha > \beta$') + +produces ":mathmpl:`\alpha > \beta`". + +.. note:: + Mathtext should be placed between a pair of dollar signs ($). To make it + easy to display monetary values, e.g., "$100.00", if a single dollar sign + is present in the entire string, it will be displayed verbatim as a dollar + sign. This is a small change from regular TeX, where the dollar sign in + non-math text would have to be escaped ('\\\$'). + +.. note:: + While the syntax inside the pair of dollar signs ($) aims to be TeX-like, + the text outside does not. In particular, characters such as:: + + # $ % & ~ _ ^ \ { } \( \) \[ \] + + have special meaning outside of math mode in TeX. Therefore, these + characters will behave differently depending on :rc:`text.usetex`. See the + :ref:`usetex tutorial ` for more information. + +.. note:: + To generate html output in documentation that will exactly match the output + generated by ``mathtext``, use the `matplotlib.sphinxext.mathmpl` Sphinx + extension. + +Subscripts and superscripts +--------------------------- +To make subscripts and superscripts, use the ``'_'`` and ``'^'`` symbols:: + + r'$\alpha_i > \beta_i$' + +.. math:: + + \alpha_i > \beta_i + +To display multi-letter subscripts or superscripts correctly, +you should put them in curly braces ``{...}``:: + + r'$\alpha^{ic} > \beta_{ic}$' + +.. math:: + + \alpha^{ic} > \beta_{ic} + +Some symbols automatically put their sub/superscripts under and over the +operator. For example, to write the sum of :mathmpl:`x_i` from :mathmpl:`0` to +:mathmpl:`\infty`, you could do:: + + r'$\sum_{i=0}^\infty x_i$' + +.. math:: + + \sum_{i=0}^\infty x_i + +Fractions, binomials, and stacked numbers +----------------------------------------- +Fractions, binomials, and stacked numbers can be created with the +``\frac{}{}``, ``\binom{}{}`` and ``\genfrac{}{}{}{}{}{}`` commands, +respectively:: + + r'$\frac{3}{4} \binom{3}{4} \genfrac{}{}{0}{}{3}{4}$' + +produces + +.. math:: + + \frac{3}{4} \binom{3}{4} \genfrac{}{}{0pt}{}{3}{4} + +Fractions can be arbitrarily nested:: + + r'$\frac{5 - \frac{1}{x}}{4}$' + +produces + +.. math:: + + \frac{5 - \frac{1}{x}}{4} + +Note that special care needs to be taken to place parentheses and brackets +around fractions. Doing things the obvious way produces brackets that are too +small:: + + r'$(\frac{5 - \frac{1}{x}}{4})$' + +.. math:: + + (\frac{5 - \frac{1}{x}}{4}) + +The solution is to precede the bracket with ``\left`` and ``\right`` to inform +the parser that those brackets encompass the entire object.:: + + r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$' + +.. math:: + + \left(\frac{5 - \frac{1}{x}}{4}\right) + +Radicals +-------- +Radicals can be produced with the ``\sqrt[]{}`` command. For example:: + + r'$\sqrt{2}$' + +.. math:: + + \sqrt{2} + +Any base can (optionally) be provided inside square brackets. Note that the +base must be a simple expression, and cannot contain layout commands such as +fractions or sub/superscripts:: + + r'$\sqrt[3]{x}$' + +.. math:: + + \sqrt[3]{x} + +.. _mathtext-fonts: + +Fonts +----- +The default font is *italics* for mathematical symbols. + +.. note:: + + This default can be changed using :rc:`mathtext.default`. This is + useful, for example, to use the same font as regular non-math text for math + text, by setting it to ``regular``. + +To change fonts, e.g., to write "sin" in a Roman font, enclose the text in a +font command:: + + r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$' + +.. math:: + + s(t) = \mathcal{A}\mathrm{sin}(2 \omega t) + +More conveniently, many commonly used function names that are typeset in +a Roman font have shortcuts. So the expression above could be written as +follows:: + + r'$s(t) = \mathcal{A}\sin(2 \omega t)$' + +.. math:: + + s(t) = \mathcal{A}\sin(2 \omega t) + +Here "s" and "t" are variable in italics font (default), "sin" is in Roman +font, and the amplitude "A" is in calligraphy font. Note in the example above +the calligraphy ``A`` is squished into the ``sin``. You can use a spacing +command to add a little whitespace between them:: + + r's(t) = \mathcal{A}\/\sin(2 \omega t)' + +.. Here we cheat a bit: for HTML math rendering, Sphinx relies on MathJax which + doesn't actually support the italic correction (\/); instead, use a thin + space (\,) which is supported. + +.. math:: + + s(t) = \mathcal{A}\,\sin(2 \omega t) + +The choices available with all fonts are: + +========================= ================================ +Command Result +========================= ================================ +``\mathrm{Roman}`` :mathmpl:`\mathrm{Roman}` +``\mathit{Italic}`` :mathmpl:`\mathit{Italic}` +``\mathtt{Typewriter}`` :mathmpl:`\mathtt{Typewriter}` +``\mathcal{CALLIGRAPHY}`` :mathmpl:`\mathcal{CALLIGRAPHY}` +========================= ================================ + +.. role:: math-stix(mathmpl) + :fontset: stix + +When using the `STIX `_ fonts, you also have the +choice of: + +================================ ========================================= +Command Result +================================ ========================================= +``\mathbb{blackboard}`` :math-stix:`\mathbb{blackboard}` +``\mathrm{\mathbb{blackboard}}`` :math-stix:`\mathrm{\mathbb{blackboard}}` +``\mathfrak{Fraktur}`` :math-stix:`\mathfrak{Fraktur}` +``\mathsf{sansserif}`` :math-stix:`\mathsf{sansserif}` +``\mathrm{\mathsf{sansserif}}`` :math-stix:`\mathrm{\mathsf{sansserif}}` +``\mathbfit{bolditalic}`` :math-stix:`\mathbfit{bolditalic}` +================================ ========================================= + +There are also five global "font sets" to choose from, which are +selected using the ``mathtext.fontset`` parameter in :ref:`matplotlibrc +`. + +``dejavusans``: DejaVu Sans + .. mathmpl:: + :fontset: dejavusans + + \mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right) + +``dejavuserif``: DejaVu Serif + .. mathmpl:: + :fontset: dejavuserif + + \mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right) + +``cm``: Computer Modern (TeX) + .. mathmpl:: + :fontset: cm + + \mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right) + +``stix``: STIX (designed to blend well with Times) + .. mathmpl:: + :fontset: stix + + \mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right) + +``stixsans``: STIX sans-serif + .. mathmpl:: + :fontset: stixsans + + \mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right) + +Additionally, you can use ``\mathdefault{...}`` or its alias +``\mathregular{...}`` to use the font used for regular text outside of +mathtext. There are a number of limitations to this approach, most notably +that far fewer symbols will be available, but it can be useful to make math +expressions blend well with other text in the plot. + +For compatibility with popular packages, ``\text{...}`` is available and uses the +``\mathrm{...}`` font, but otherwise retains spaces and renders - as a dash +(not minus). + +Custom fonts +~~~~~~~~~~~~ +mathtext also provides a way to use custom fonts for math. This method is +fairly tricky to use, and should be considered an experimental feature for +patient users only. By setting :rc:`mathtext.fontset` to ``custom``, +you can then set the following parameters, which control which font file to use +for a particular set of math characters. + +============================== ================================= +Parameter Corresponds to +============================== ================================= +``mathtext.it`` ``\mathit{}`` or default italic +``mathtext.rm`` ``\mathrm{}`` Roman (upright) +``mathtext.tt`` ``\mathtt{}`` Typewriter (monospace) +``mathtext.bf`` ``\mathbf{}`` bold +``mathtext.bfit`` ``\mathbfit{}`` bold italic +``mathtext.cal`` ``\mathcal{}`` calligraphic +``mathtext.sf`` ``\mathsf{}`` sans-serif +============================== ================================= + +Each parameter should be set to a fontconfig font descriptor (as defined in the +yet-to-be-written font chapter). + +.. TODO: Link to font chapter + +The fonts used should have a Unicode mapping in order to find any +non-Latin characters, such as Greek. If you want to use a math symbol +that is not contained in your custom fonts, you can set +:rc:`mathtext.fallback` to either ``'cm'``, ``'stix'`` or ``'stixsans'`` +which will cause the mathtext system to use +characters from an alternative font whenever a particular +character cannot be found in the custom font. + +Note that the math glyphs specified in Unicode have evolved over time, and many +fonts may not have glyphs in the correct place for mathtext. + +Accents +------- +An accent command may precede any symbol to add an accent above it. There are +long and short forms for some of them. + +============================== ================================= +Command Result +============================== ================================= +``\acute a`` or ``\'a`` :mathmpl:`\acute a` +``\bar a`` :mathmpl:`\bar a` +``\breve a`` :mathmpl:`\breve a` +``\dot a`` or ``\.a`` :mathmpl:`\dot a` +``\ddot a`` or ``\''a`` :mathmpl:`\ddot a` +``\dddot a`` :mathmpl:`\dddot a` +``\ddddot a`` :mathmpl:`\ddddot a` +``\grave a`` or ``\`a`` :mathmpl:`\grave a` +``\hat a`` or ``\^a`` :mathmpl:`\hat a` +``\tilde a`` or ``\~a`` :mathmpl:`\tilde a` +``\vec a`` :mathmpl:`\vec a` +``\overline{abc}`` :mathmpl:`\overline{abc}` +============================== ================================= + +In addition, there are two special accents that automatically adjust to the +width of the symbols below: + +============================== ================================= +Command Result +============================== ================================= +``\widehat{xyz}`` :mathmpl:`\widehat{xyz}` +``\widetilde{xyz}`` :mathmpl:`\widetilde{xyz}` +============================== ================================= + +Care should be taken when putting accents on lower-case i's and j's. Note that +in the following ``\imath`` is used to avoid the extra dot over the i:: + + r"$\hat i\ \ \hat \imath$" + +.. math:: + + \hat i\ \ \hat \imath + +Symbols +------- +You can also use a large number of the TeX symbols, as in ``\infty``, +``\leftarrow``, ``\sum``, ``\int``. + +.. math_symbol_table:: + +If a particular symbol does not have a name (as is true of many of the more +obscure symbols in the STIX fonts), Unicode characters can also be used:: + + r'$\u23ce$' + +Example +------- +Here is an example illustrating many of these features in context. + +.. figure:: /gallery/text_labels_and_annotations/images/sphx_glr_mathtext_demo_001.png + :target: /gallery/text_labels_and_annotations/mathtext_demo.html + :align: center +""" diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/pgf.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/pgf.py new file mode 100644 index 0000000000000000000000000000000000000000..0c63ec368043373d9fde874e561b8e07642eeb64 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/pgf.py @@ -0,0 +1,209 @@ +r""" + +.. redirect-from:: /tutorials/text/pgf + +.. _pgf: + +************************************************************ +Text rendering with XeLaTeX/LuaLaTeX via the ``pgf`` backend +************************************************************ + +Using the ``pgf`` backend, Matplotlib can export figures as pgf drawing +commands that can be processed with pdflatex, xelatex or lualatex. XeLaTeX and +LuaLaTeX have full Unicode support and can use any font that is installed in +the operating system, making use of advanced typographic features of OpenType, +AAT and Graphite. Pgf pictures created by ``plt.savefig('figure.pgf')`` +can be embedded as raw commands in LaTeX documents. Figures can also be +directly compiled and saved to PDF with ``plt.savefig('figure.pdf')`` by +switching the backend :: + + matplotlib.use('pgf') + +or by explicitly requesting the use of the ``pgf`` backend :: + + plt.savefig('figure.pdf', backend='pgf') + +or by registering it for handling pdf output :: + + from matplotlib.backends.backend_pgf import FigureCanvasPgf + matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf) + +The last method allows you to keep using regular interactive backends and to +save xelatex, lualatex or pdflatex compiled PDF files from the graphical user +interface. + +Matplotlib's pgf support requires a recent LaTeX_ installation that includes +the TikZ/PGF packages (such as TeXLive_), preferably with XeLaTeX or LuaLaTeX +installed. If either pdftocairo or ghostscript is present on your system, +figures can optionally be saved to PNG images as well. The executables +for all applications must be located on your :envvar:`PATH`. + +`.rcParams` that control the behavior of the pgf backend: + +================= ===================================================== +Parameter Documentation +================= ===================================================== +pgf.preamble Lines to be included in the LaTeX preamble +pgf.rcfonts Setup fonts from rc params using the fontspec package +pgf.texsystem Either "xelatex" (default), "lualatex" or "pdflatex" +================= ===================================================== + +.. note:: + + TeX defines a set of special characters, such as:: + + # $ % & ~ _ ^ \ { } + + Generally, these characters must be escaped correctly. For convenience, + some characters (_, ^, %) are automatically escaped outside of math + environments. Other characters are not escaped as they are commonly needed + in actual TeX expressions. However, one can configure TeX to treat them as + "normal" characters (known as "catcode 12" to TeX) via a custom preamble, + such as:: + + plt.rcParams["pgf.preamble"] = ( + r"\AtBeginDocument{\catcode`\&=12\catcode`\#=12}") + +.. _pgf-rcfonts: + + +Multi-Page PDF Files +==================== + +The pgf backend also supports multipage pdf files using +`~.backend_pgf.PdfPages` + +.. code-block:: python + + from matplotlib.backends.backend_pgf import PdfPages + import matplotlib.pyplot as plt + + with PdfPages('multipage.pdf', metadata={'author': 'Me'}) as pdf: + + fig1, ax1 = plt.subplots() + ax1.plot([1, 5, 3]) + pdf.savefig(fig1) + + fig2, ax2 = plt.subplots() + ax2.plot([1, 5, 3]) + pdf.savefig(fig2) + + +Font specification +================== + +The fonts used for obtaining the size of text elements or when compiling +figures to PDF are usually defined in the `.rcParams`. You can also use the +LaTeX default Computer Modern fonts by clearing the lists for :rc:`font.serif`, +:rc:`font.sans-serif` or :rc:`font.monospace`. Please note that the glyph +coverage of these fonts is very limited. If you want to keep the Computer +Modern font face but require extended Unicode support, consider installing the +`Computer Modern Unicode`__ fonts *CMU Serif*, *CMU Sans Serif*, etc. + +__ https://sourceforge.net/projects/cm-unicode/ + +When saving to ``.pgf``, the font configuration Matplotlib used for the +layout of the figure is included in the header of the text file. + +.. literalinclude:: /gallery/userdemo/pgf_fonts.py + :end-before: fig.savefig + + +.. _pgf-preamble: + +Custom preamble +=============== + +Full customization is possible by adding your own commands to the preamble. +Use :rc:`pgf.preamble` if you want to configure the math fonts, +using ``unicode-math`` for example, or for loading additional packages. Also, +if you want to do the font configuration yourself instead of using the fonts +specified in the rc parameters, make sure to disable :rc:`pgf.rcfonts`. + +.. only:: html + + .. literalinclude:: /gallery/userdemo/pgf_preamble_sgskip.py + :end-before: fig.savefig + +.. only:: latex + + .. literalinclude:: /gallery/userdemo/pgf_preamble_sgskip.py + :end-before: import matplotlib.pyplot as plt + + +.. _pgf-texsystem: + +Choosing the TeX system +======================= + +The TeX system to be used by Matplotlib is chosen by :rc:`pgf.texsystem`. +Possible values are ``'xelatex'`` (default), ``'lualatex'`` and ``'pdflatex'``. +Please note that when selecting pdflatex, the fonts and Unicode handling must +be configured in the preamble. + +.. literalinclude:: /gallery/userdemo/pgf_texsystem.py + :end-before: fig.savefig + + +.. _pgf-troubleshooting: + +Troubleshooting +=============== + +* Please note that the TeX packages found in some Linux distributions and + MiKTeX installations are dramatically outdated. Make sure to update your + package catalog and upgrade or install a recent TeX distribution. + +* On Windows, the :envvar:`PATH` environment variable may need to be modified + to include the directories containing the latex, dvipng and ghostscript + executables. See :ref:`environment-variables` and + :ref:`setting-windows-environment-variables` for details. + +* Sometimes the font rendering in figures that are saved to png images is + very bad. This happens when the pdftocairo tool is not available and + ghostscript is used for the pdf to png conversion. + +* Make sure what you are trying to do is possible in a LaTeX document, + that your LaTeX syntax is valid and that you are using raw strings + if necessary to avoid unintended escape sequences. + +* :rc:`pgf.preamble` provides lots of flexibility, and lots of + ways to cause problems. When experiencing problems, try to minimalize or + disable the custom preamble. + +* Configuring an ``unicode-math`` environment can be a bit tricky. The + TeXLive distribution for example provides a set of math fonts which are + usually not installed system-wide. XeTeX, unlike LuaLatex, cannot find + these fonts by their name, which is why you might have to specify + ``\setmathfont{xits-math.otf}`` instead of ``\setmathfont{XITS Math}`` or + alternatively make the fonts available to your OS. See this + `tex.stackexchange.com question`__ for more details. + + __ https://tex.stackexchange.com/q/43642/ + +* If the font configuration used by Matplotlib differs from the font setting + in yout LaTeX document, the alignment of text elements in imported figures + may be off. Check the header of your ``.pgf`` file if you are unsure about + the fonts Matplotlib used for the layout. + +* Vector images and hence ``.pgf`` files can become bloated if there are a lot + of objects in the graph. This can be the case for image processing or very + big scatter graphs. In an extreme case this can cause TeX to run out of + memory: "TeX capacity exceeded, sorry" You can configure latex to increase + the amount of memory available to generate the ``.pdf`` image as discussed on + `tex.stackexchange.com `_. + Another way would be to "rasterize" parts of the graph causing problems + using either the ``rasterized=True`` keyword, or ``.set_rasterized(True)`` as + per :doc:`this example `. + +* Various math fonts are compiled and rendered only if corresponding font + packages are loaded. Specifically, when using ``\mathbf{}`` on Greek letters, + the default computer modern font may not contain them, in which case the + letter is not rendered. In such scenarios, the ``lmodern`` package should be + loaded. + +* If you still need help, please see :ref:`reporting-problems` + +.. _LaTeX: http://www.tug.org +.. _TeXLive: http://www.tug.org/texlive/ +""" diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_intro.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_intro.py new file mode 100644 index 0000000000000000000000000000000000000000..eccd584ce36fde8c18874a36c8eb78a8723906f6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_intro.py @@ -0,0 +1,429 @@ +""" + +.. redirect-from:: /tutorials/text/text_intro + +.. _text_intro: + +======================== +Text in Matplotlib Plots +======================== + +Introduction to plotting and working with text in Matplotlib. + +Matplotlib has extensive text support, including support for +mathematical expressions, truetype support for raster and +vector outputs, newline separated text with arbitrary +rotations, and Unicode support. + +Because it embeds fonts directly in output documents, e.g., for postscript +or PDF, what you see on the screen is what you get in the hardcopy. +`FreeType `_ support +produces very nice, antialiased fonts, that look good even at small +raster sizes. Matplotlib includes its own +:mod:`matplotlib.font_manager` (thanks to Paul Barrett), which +implements a cross platform, `W3C `_ +compliant font finding algorithm. + +The user has a great deal of control over text properties (font size, font +weight, text location and color, etc.) with sensible defaults set in +the :ref:`rc file `. +And significantly, for those interested in mathematical +or scientific figures, Matplotlib implements a large number of TeX +math symbols and commands, supporting :ref:`mathematical expressions +` anywhere in your figure. + + +Basic text commands +=================== + +The following commands are used to create text in the implicit and explicit +interfaces (see :ref:`api_interfaces` for an explanation of the tradeoffs): + +=================== =================== ====================================== +implicit API explicit API description +=================== =================== ====================================== +`~.pyplot.text` `~.Axes.text` Add text at an arbitrary location of + the `~matplotlib.axes.Axes`. + +`~.pyplot.annotate` `~.Axes.annotate` Add an annotation, with an optional + arrow, at an arbitrary location of the + `~matplotlib.axes.Axes`. + +`~.pyplot.xlabel` `~.Axes.set_xlabel` Add a label to the + `~matplotlib.axes.Axes`\\'s x-axis. + +`~.pyplot.ylabel` `~.Axes.set_ylabel` Add a label to the + `~matplotlib.axes.Axes`\\'s y-axis. + +`~.pyplot.title` `~.Axes.set_title` Add a title to the + `~matplotlib.axes.Axes`. + +`~.pyplot.figtext` `~.Figure.text` Add text at an arbitrary location of + the `.Figure`. + +`~.pyplot.suptitle` `~.Figure.suptitle` Add a title to the `.Figure`. +=================== =================== ====================================== + +All of these functions create and return a `.Text` instance, which can be +configured with a variety of font and other properties. The example below +shows all of these commands in action, and more detail is provided in the +sections that follow. + +""" + +import matplotlib.pyplot as plt + +import matplotlib + +fig = plt.figure() +ax = fig.add_subplot() +fig.subplots_adjust(top=0.85) + +# Set titles for the figure and the subplot respectively +fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') +ax.set_title('axes title') + +ax.set_xlabel('xlabel') +ax.set_ylabel('ylabel') + +# Set both x- and y-axis limits to [0, 10] instead of default [0, 1] +ax.axis([0, 10, 0, 10]) + +ax.text(3, 8, 'boxed italics text in data coords', style='italic', + bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10}) + +ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) + +ax.text(3, 2, 'Unicode: Institut für Festkörperphysik') + +ax.text(0.95, 0.01, 'colored text in axes coords', + verticalalignment='bottom', horizontalalignment='right', + transform=ax.transAxes, + color='green', fontsize=15) + +ax.plot([2], [1], 'o') +ax.annotate('annotate', xy=(2, 1), xytext=(3, 4), + arrowprops=dict(facecolor='black', shrink=0.05)) + +plt.show() + +# %% +# Labels for x- and y-axis +# ======================== +# +# Specifying the labels for the x- and y-axis is straightforward, via the +# `~matplotlib.axes.Axes.set_xlabel` and `~matplotlib.axes.Axes.set_ylabel` +# methods. + +import matplotlib.pyplot as plt +import numpy as np + +x1 = np.linspace(0.0, 5.0, 100) +y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.15, left=0.2) +ax.plot(x1, y1) +ax.set_xlabel('Time [s]') +ax.set_ylabel('Damped oscillation [V]') + +plt.show() + +# %% +# The x- and y-labels are automatically placed so that they clear the x- and +# y-ticklabels. Compare the plot below with that above, and note the y-label +# is to the left of the one above. + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.15, left=0.2) +ax.plot(x1, y1*10000) +ax.set_xlabel('Time [s]') +ax.set_ylabel('Damped oscillation [V]') + +plt.show() + +# %% +# If you want to move the labels, you can specify the *labelpad* keyword +# argument, where the value is points (1/72", the same unit used to specify +# fontsizes). + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.15, left=0.2) +ax.plot(x1, y1*10000) +ax.set_xlabel('Time [s]') +ax.set_ylabel('Damped oscillation [V]', labelpad=18) + +plt.show() + +# %% +# Or, the labels accept all the `.Text` keyword arguments, including +# *position*, via which we can manually specify the label positions. Here we +# put the xlabel to the far left of the axis. Note, that the y-coordinate of +# this position has no effect - to adjust the y-position we need to use the +# *labelpad* keyword argument. + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.15, left=0.2) +ax.plot(x1, y1) +ax.set_xlabel('Time [s]', position=(0., 1e6), horizontalalignment='left') +ax.set_ylabel('Damped oscillation [V]') + +plt.show() + +# %% +# All the labelling in this tutorial can be changed by manipulating the +# `matplotlib.font_manager.FontProperties` method, or by named keyword +# arguments to `~matplotlib.axes.Axes.set_xlabel` + +from matplotlib.font_manager import FontProperties + +font = FontProperties() +font.set_family('serif') +font.set_name('Times New Roman') +font.set_style('italic') + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.15, left=0.2) +ax.plot(x1, y1) +ax.set_xlabel('Time [s]', fontsize='large', fontweight='bold') +ax.set_ylabel('Damped oscillation [V]', fontproperties=font) + +plt.show() + +# %% +# Finally, we can use native TeX rendering in all text objects and have +# multiple lines: + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(bottom=0.2, left=0.2) +ax.plot(x1, np.cumsum(y1**2)) +ax.set_xlabel('Time [s] \n This was a long experiment') +ax.set_ylabel(r'$\int\ Y^2\ dt\ \ [V^2 s]$') +plt.show() + + +# %% +# Titles +# ====== +# +# Subplot titles are set in much the same way as labels, but there is +# the *loc* keyword arguments that can change the position and justification +# from the default value of ``loc=center``. + +fig, axs = plt.subplots(3, 1, figsize=(5, 6), tight_layout=True) +locs = ['center', 'left', 'right'] +for ax, loc in zip(axs, locs): + ax.plot(x1, y1) + ax.set_title('Title with loc at '+loc, loc=loc) +plt.show() + +# %% +# Vertical spacing for titles is controlled via :rc:`axes.titlepad`. +# Setting to a different value moves the title. + +fig, ax = plt.subplots(figsize=(5, 3)) +fig.subplots_adjust(top=0.8) +ax.plot(x1, y1) +ax.set_title('Vertically offset title', pad=30) +plt.show() + + +# %% +# Ticks and ticklabels +# ==================== +# +# Placing ticks and ticklabels is a very tricky aspect of making a figure. +# Matplotlib does its best to accomplish the task automatically, but it also +# offers a very flexible framework for determining the choices for tick +# locations, and how they are labelled. +# +# Terminology +# ~~~~~~~~~~~ +# +# *Axes* have an `matplotlib.axis.Axis` object for the ``ax.xaxis`` and +# ``ax.yaxis`` that contain the information about how the labels in the axis +# are laid out. +# +# The axis API is explained in detail in the documentation to +# `~matplotlib.axis`. +# +# An Axis object has major and minor ticks. The Axis has +# `.Axis.set_major_locator` and `.Axis.set_minor_locator` methods that use the +# data being plotted to determine the location of major and minor ticks. There +# are also `.Axis.set_major_formatter` and `.Axis.set_minor_formatter` methods +# that format the tick labels. +# +# Simple ticks +# ~~~~~~~~~~~~ +# +# It is often convenient to simply define the +# tick values, and sometimes the tick labels, overriding the default +# locators and formatters. This is discouraged because it breaks interactive +# navigation of the plot. It also can reset the axis limits: note that +# the second plot has the ticks we asked for, including ones that are +# well outside the automatic view limits. + +fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) +axs[0].plot(x1, y1) +axs[1].plot(x1, y1) +axs[1].xaxis.set_ticks(np.arange(0., 8.1, 2.)) +plt.show() + +# %% +# We can of course fix this after the fact, but it does highlight a +# weakness of hard-coding the ticks. This example also changes the format +# of the ticks: + +fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) +axs[0].plot(x1, y1) +axs[1].plot(x1, y1) +ticks = np.arange(0., 8.1, 2.) +# list comprehension to get all tick labels... +tickla = [f'{tick:1.2f}' for tick in ticks] +axs[1].xaxis.set_ticks(ticks) +axs[1].xaxis.set_ticklabels(tickla) +axs[1].set_xlim(axs[0].get_xlim()) +plt.show() + +# %% +# Tick Locators and Formatters +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Instead of making a list of all the ticklabels, we could have +# used `matplotlib.ticker.StrMethodFormatter` (new-style ``str.format()`` +# format string) or `matplotlib.ticker.FormatStrFormatter` (old-style '%' +# format string) and passed it to the ``ax.xaxis``. A +# `matplotlib.ticker.StrMethodFormatter` can also be created by passing a +# ``str`` without having to explicitly create the formatter. + +fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) +axs[0].plot(x1, y1) +axs[1].plot(x1, y1) +ticks = np.arange(0., 8.1, 2.) +axs[1].xaxis.set_ticks(ticks) +axs[1].xaxis.set_major_formatter('{x:1.1f}') +axs[1].set_xlim(axs[0].get_xlim()) +plt.show() + +# %% +# And of course we could have used a non-default locator to set the +# tick locations. Note we still pass in the tick values, but the +# x-limit fix used above is *not* needed. + +fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) +axs[0].plot(x1, y1) +axs[1].plot(x1, y1) +locator = matplotlib.ticker.FixedLocator(ticks) +axs[1].xaxis.set_major_locator(locator) +axs[1].xaxis.set_major_formatter('±{x}°') +plt.show() + +# %% +# The default formatter is the `matplotlib.ticker.MaxNLocator` called as +# ``ticker.MaxNLocator(self, nbins='auto', steps=[1, 2, 2.5, 5, 10])`` +# The *steps* keyword contains a list of multiples that can be used for +# tick values. i.e. in this case, 2, 4, 6 would be acceptable ticks, +# as would 20, 40, 60 or 0.2, 0.4, 0.6. However, 3, 6, 9 would not be +# acceptable because 3 doesn't appear in the list of steps. +# +# ``nbins=auto`` uses an algorithm to determine how many ticks will +# be acceptable based on how long the axis is. The fontsize of the +# ticklabel is taken into account, but the length of the tick string +# is not (because it's not yet known.) In the bottom row, the +# ticklabels are quite large, so we set ``nbins=4`` to make the +# labels fit in the right-hand plot. + +fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True) +for n, ax in enumerate(axs.flat): + ax.plot(x1*10., y1) + +formatter = matplotlib.ticker.FormatStrFormatter('%1.1f') +locator = matplotlib.ticker.MaxNLocator(nbins='auto', steps=[1, 4, 10]) +axs[0, 1].xaxis.set_major_locator(locator) +axs[0, 1].xaxis.set_major_formatter(formatter) + +formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') +locator = matplotlib.ticker.AutoLocator() +axs[1, 0].xaxis.set_major_formatter(formatter) +axs[1, 0].xaxis.set_major_locator(locator) + +formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') +locator = matplotlib.ticker.MaxNLocator(nbins=4) +axs[1, 1].xaxis.set_major_formatter(formatter) +axs[1, 1].xaxis.set_major_locator(locator) + +plt.show() + +# %% +# Finally, we can specify functions for the formatter using +# `matplotlib.ticker.FuncFormatter`. Further, like +# `matplotlib.ticker.StrMethodFormatter`, passing a function will +# automatically create a `matplotlib.ticker.FuncFormatter`. + + +def formatoddticks(x, pos): + """Format odd tick positions.""" + if x % 2: + return f'{x:1.2f}' + else: + return '' + + +fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) +ax.plot(x1, y1) +locator = matplotlib.ticker.MaxNLocator(nbins=6) +ax.xaxis.set_major_formatter(formatoddticks) +ax.xaxis.set_major_locator(locator) + +plt.show() + + +# %% +# Dateticks +# ~~~~~~~~~ +# +# Matplotlib can accept `datetime.datetime` and `numpy.datetime64` +# objects as plotting arguments. Dates and times require special +# formatting, which can often benefit from manual intervention. In +# order to help, dates have special Locators and Formatters, +# defined in the `matplotlib.dates` module. +# +# A simple example is as follows. Note how we have to rotate the +# tick labels so that they don't over-run each other. + +import datetime + +fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) +base = datetime.datetime(2017, 1, 1, 0, 0, 1) +time = [base + datetime.timedelta(days=x) for x in range(len(x1))] + +ax.plot(time, y1) +ax.tick_params(axis='x', rotation=70) +plt.show() + +# %% +# We can pass a format to `matplotlib.dates.DateFormatter`. Also note that the +# 29th and the next month are very close together. We can fix this by using +# the `.dates.DayLocator` class, which allows us to specify a list of days of +# the month to use. Similar formatters are listed in the `matplotlib.dates` +# module. + +import matplotlib.dates as mdates + +locator = mdates.DayLocator(bymonthday=[1, 15]) +formatter = mdates.DateFormatter('%b %d') + +fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) +ax.xaxis.set_major_locator(locator) +ax.xaxis.set_major_formatter(formatter) +ax.plot(time, y1) +ax.tick_params(axis='x', rotation=70) +plt.show() + +# %% +# Legends and Annotations +# ======================= +# +# - Legends: :ref:`legend_guide` +# - Annotations: :ref:`annotations` +# diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_props.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_props.py new file mode 100644 index 0000000000000000000000000000000000000000..20111f0775f53ce5c8dd42550c6e1ee4814bc61f --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/text_props.py @@ -0,0 +1,272 @@ +""" + +.. redirect-from:: /tutorials/text/text_props + +.. _text_props: + +============================ + Text properties and layout +============================ + +Controlling properties of text and its layout with Matplotlib. + +`matplotlib.text.Text` instances have a variety of properties which can be +configured via keyword arguments to `~.Axes.set_title`, `~.Axes.set_xlabel`, +`~.Axes.text`, etc. + +========================== ====================================================================================================================== +Property Value Type +========================== ====================================================================================================================== +alpha `float` +backgroundcolor any matplotlib :ref:`color ` +bbox `~matplotlib.patches.Rectangle` prop dict plus key ``'pad'`` which is a pad in points +clip_box a matplotlib.transform.Bbox instance +clip_on bool +clip_path a `~matplotlib.path.Path` instance and a `~matplotlib.transforms.Transform` instance, a `~matplotlib.patches.Patch` +color any matplotlib :ref:`color ` +family [ ``'serif'`` | ``'sans-serif'`` | ``'cursive'`` | ``'fantasy'`` | ``'monospace'`` ] +fontproperties `~matplotlib.font_manager.FontProperties` +horizontalalignment or ha [ ``'center'`` | ``'right'`` | ``'left'`` ] +label any string +linespacing `float` +multialignment [``'left'`` | ``'right'`` | ``'center'`` ] +name or fontname string e.g., [``'Sans'`` | ``'Courier'`` | ``'Helvetica'`` ...] +picker [None|float|bool|callable] +position (x, y) +rotation [ angle in degrees | ``'vertical'`` | ``'horizontal'`` ] +size or fontsize [ size in points | relative size, e.g., ``'smaller'``, ``'x-large'`` ] +style or fontstyle [ ``'normal'`` | ``'italic'`` | ``'oblique'`` ] +text string or anything printable with '%s' conversion +transform `~matplotlib.transforms.Transform` subclass +variant [ ``'normal'`` | ``'small-caps'`` ] +verticalalignment or va [ ``'center'`` | ``'top'`` | ``'bottom'`` | ``'baseline'`` ] +visible bool +weight or fontweight [ ``'normal'`` | ``'bold'`` | ``'heavy'`` | ``'light'`` | ``'ultrabold'`` | ``'ultralight'``] +x `float` +y `float` +zorder any number +========================== ====================================================================================================================== + + +You can lay out text with the alignment arguments +``horizontalalignment``, ``verticalalignment``, and +``multialignment``. ``horizontalalignment`` controls whether the x +positional argument for the text indicates the left, center or right +side of the text bounding box. ``verticalalignment`` controls whether +the y positional argument for the text indicates the bottom, center or +top side of the text bounding box. ``multialignment``, for newline +separated strings only, controls whether the different lines are left, +center or right justified. Here is an example which uses the +:func:`~matplotlib.pyplot.text` command to show the various alignment +possibilities. The use of ``transform=ax.transAxes`` throughout the +code indicates that the coordinates are given relative to the axes +bounding box, with (0, 0) being the lower left of the axes and (1, 1) the +upper right. +""" + +import matplotlib.pyplot as plt + +import matplotlib.patches as patches + +# build a rectangle in axes coords +left, width = .25, .5 +bottom, height = .25, .5 +right = left + width +top = bottom + height + +fig = plt.figure() +ax = fig.add_axes([0, 0, 1, 1]) + +# axes coordinates: (0, 0) is bottom left and (1, 1) is upper right +p = patches.Rectangle( + (left, bottom), width, height, + fill=False, transform=ax.transAxes, clip_on=False + ) + +ax.add_patch(p) + +ax.text(left, bottom, 'left top', + horizontalalignment='left', + verticalalignment='top', + transform=ax.transAxes) + +ax.text(left, bottom, 'left bottom', + horizontalalignment='left', + verticalalignment='bottom', + transform=ax.transAxes) + +ax.text(right, top, 'right bottom', + horizontalalignment='right', + verticalalignment='bottom', + transform=ax.transAxes) + +ax.text(right, top, 'right top', + horizontalalignment='right', + verticalalignment='top', + transform=ax.transAxes) + +ax.text(right, bottom, 'center top', + horizontalalignment='center', + verticalalignment='top', + transform=ax.transAxes) + +ax.text(left, 0.5*(bottom+top), 'right center', + horizontalalignment='right', + verticalalignment='center', + rotation='vertical', + transform=ax.transAxes) + +ax.text(left, 0.5*(bottom+top), 'left center', + horizontalalignment='left', + verticalalignment='center', + rotation='vertical', + transform=ax.transAxes) + +ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle', + horizontalalignment='center', + verticalalignment='center', + fontsize=20, color='red', + transform=ax.transAxes) + +ax.text(right, 0.5*(bottom+top), 'centered', + horizontalalignment='center', + verticalalignment='center', + rotation='vertical', + transform=ax.transAxes) + +ax.text(left, top, 'rotated\nwith newlines', + horizontalalignment='center', + verticalalignment='center', + rotation=45, + transform=ax.transAxes) + +ax.set_axis_off() +plt.show() + +# %% +# ============== +# Default Font +# ============== +# +# The base default font is controlled by a set of rcParams. To set the font +# for mathematical expressions, use the rcParams beginning with ``mathtext`` +# (see :ref:`mathtext `). +# +# +---------------------+----------------------------------------------------+ +# | rcParam | usage | +# +=====================+====================================================+ +# | ``'font.family'`` | List of font families (installed on user's machine)| +# | | and/or ``{'cursive', 'fantasy', 'monospace', | +# | | 'sans', 'sans serif', 'sans-serif', 'serif'}``. | +# | | | +# +---------------------+----------------------------------------------------+ +# | ``'font.style'`` | The default style, ex ``'normal'``, | +# | | ``'italic'``. | +# | | | +# +---------------------+----------------------------------------------------+ +# | ``'font.variant'`` | Default variant, ex ``'normal'``, ``'small-caps'`` | +# | | (untested) | +# +---------------------+----------------------------------------------------+ +# | ``'font.stretch'`` | Default stretch, ex ``'normal'``, ``'condensed'`` | +# | | (incomplete) | +# | | | +# +---------------------+----------------------------------------------------+ +# | ``'font.weight'`` | Default weight. Either string or integer | +# | | | +# | | | +# +---------------------+----------------------------------------------------+ +# | ``'font.size'`` | Default font size in points. Relative font sizes | +# | | (``'large'``, ``'x-small'``) are computed against | +# | | this size. | +# +---------------------+----------------------------------------------------+ +# +# Matplotlib can use font families installed on the user's computer, i.e. +# Helvetica, Times, etc. Font families can also be specified with +# generic-family aliases like (``{'cursive', 'fantasy', 'monospace', +# 'sans', 'sans serif', 'sans-serif', 'serif'}``). +# +# .. note:: +# To access the full list of available fonts: :: +# +# matplotlib.font_manager.get_font_names() +# +# The mapping between the generic family aliases and actual font families +# (mentioned at :ref:`default rcParams `) +# is controlled by the following rcParams: +# +# +# +------------------------------------------+--------------------------------+ +# | CSS-based generic-family alias | rcParam with mappings | +# +==========================================+================================+ +# | ``'serif'`` | ``'font.serif'`` | +# +------------------------------------------+--------------------------------+ +# | ``'monospace'`` | ``'font.monospace'`` | +# +------------------------------------------+--------------------------------+ +# | ``'fantasy'`` | ``'font.fantasy'`` | +# +------------------------------------------+--------------------------------+ +# | ``'cursive'`` | ``'font.cursive'`` | +# +------------------------------------------+--------------------------------+ +# | ``{'sans', 'sans serif', 'sans-serif'}`` | ``'font.sans-serif'`` | +# +------------------------------------------+--------------------------------+ +# +# +# If any of generic family names appear in ``'font.family'``, we replace that entry +# by all the entries in the corresponding rcParam mapping. +# For example: :: +# +# matplotlib.rcParams['font.family'] = ['Family1', 'serif', 'Family2'] +# matplotlib.rcParams['font.serif'] = ['SerifFamily1', 'SerifFamily2'] +# +# # This is effectively translated to: +# matplotlib.rcParams['font.family'] = ['Family1', 'SerifFamily1', 'SerifFamily2', 'Family2'] +# +# +# .. _font-nonlatin: +# +# Text with non-latin glyphs +# ========================== +# +# As of v2.0 the :ref:`default font `, DejaVu, contains +# glyphs for many western alphabets, but not other scripts, such as Chinese, +# Korean, or Japanese. +# +# To set the default font to be one that supports the code points you +# need, prepend the font name to ``'font.family'`` (recommended), or to the +# desired alias lists. :: +# +# # first method +# matplotlib.rcParams['font.family'] = ['Source Han Sans TW', 'sans-serif'] +# +# # second method +# matplotlib.rcParams['font.family'] = ['sans-serif'] +# matplotlib.rcParams['sans-serif'] = ['Source Han Sans TW', ...] +# +# The generic family alias lists contain fonts that are either shipped +# alongside Matplotlib (so they have 100% chance of being found), or fonts +# which have a very high probability of being present in most systems. +# +# A good practice when setting custom font families is to append +# a generic-family to the font-family list as a last resort. +# +# You can also set it in your :file:`.matplotlibrc` file:: +# +# font.family: Source Han Sans TW, Arial, sans-serif +# +# To control the font used on per-artist basis use the *name*, *fontname* or +# *fontproperties* keyword arguments documented in :ref:`text_props`. +# +# +# On linux, `fc-list `__ can be a +# useful tool to discover the font name; for example :: +# +# $ fc-list :lang=zh family +# Noto to Sans Mono CJK TC,Noto Sans Mono CJK TC Bold +# Noto Sans CJK TC,Noto Sans CJK TC Medium +# Noto Sans CJK TC,Noto Sans CJK TC DemiLight +# Noto Sans CJK KR,Noto Sans CJK KR Black +# Noto Sans CJK TC,Noto Sans CJK TC Black +# Noto Sans Mono CJK TC,Noto Sans Mono CJK TC Regular +# Noto Sans CJK SC,Noto Sans CJK SC Light +# +# lists all of the fonts that support Chinese. +# diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/text/usetex.py b/testbed/matplotlib__matplotlib/galleries/users_explain/text/usetex.py new file mode 100644 index 0000000000000000000000000000000000000000..0194a0030d4833017a1f888cda7bcfad8a097dc6 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/text/usetex.py @@ -0,0 +1,177 @@ +r""" +.. redirect-from:: /tutorials/text/usetex + +.. _usetex: + +************************* +Text rendering with LaTeX +************************* + +Matplotlib can use LaTeX to render text. This is activated by setting +``text.usetex : True`` in your rcParams, or by setting the ``usetex`` property +to True on individual `.Text` objects. Text handling through LaTeX is slower +than Matplotlib's very capable :ref:`mathtext `, but +is more flexible, since different LaTeX packages (font packages, math packages, +etc.) can be used. The results can be striking, especially when you take care +to use the same fonts in your figures as in the main document. + +Matplotlib's LaTeX support requires a working LaTeX_ installation. For +the \*Agg backends, dvipng_ is additionally required; for the PS backend, +PSfrag_, dvips_ and Ghostscript_ are additionally required. For the PDF +and SVG backends, if LuaTeX is present, it will be used to speed up some +post-processing steps, but note that it is not used to parse the TeX string +itself (only LaTeX is supported). The executables for these external +dependencies must all be located on your :envvar:`PATH`. + +Only a small number of font families (defined by the PSNFSS_ scheme) are +supported. They are listed here, with the corresponding LaTeX font selection +commands and LaTeX packages, which are automatically used. + +=========================== ================================================= +generic family fonts +=========================== ================================================= +serif (``\rmfamily``) Computer Modern Roman, Palatino (``mathpazo``), + Times (``mathptmx``), Bookman (``bookman``), + New Century Schoolbook (``newcent``), + Charter (``charter``) + +sans-serif (``\sffamily``) Computer Modern Serif, Helvetica (``helvet``), + Avant Garde (``avant``) + +cursive (``\rmfamily``) Zapf Chancery (``chancery``) + +monospace (``\ttfamily``) Computer Modern Typewriter, Courier (``courier``) +=========================== ================================================= + +The default font family (which does not require loading any LaTeX package) is +Computer Modern. All other families are Adobe fonts. Times and Palatino each +have their own accompanying math fonts, while the other Adobe serif fonts make +use of the Computer Modern math fonts. + +To enable LaTeX and select a font, use e.g.:: + + plt.rcParams.update({ + "text.usetex": True, + "font.family": "Helvetica" + }) + +or equivalently, set your :ref:`matplotlibrc ` to:: + + text.usetex : true + font.family : Helvetica + +It is also possible to instead set ``font.family`` to one of the generic family +names and then configure the corresponding generic family; e.g.:: + + plt.rcParams.update({ + "text.usetex": True, + "font.family": "sans-serif", + "font.sans-serif": "Helvetica", + }) + +(this was the required approach until Matplotlib 3.5). + +Here is the standard example, +:doc:`/gallery/text_labels_and_annotations/tex_demo`: + +.. figure:: /gallery/text_labels_and_annotations/images/sphx_glr_tex_demo_001.png + :target: /gallery/text_labels_and_annotations/tex_demo.html + :align: center + +Note that display math mode (``$$ e=mc^2 $$``) is not supported, but adding the +command ``\displaystyle``, as in the above demo, will produce the same results. + +Non-ASCII characters (e.g. the degree sign in the y-label above) are supported +to the extent that they are supported by inputenc_. + +.. note:: + For consistency with the non-usetex case, Matplotlib special-cases newlines, + so that single-newlines yield linebreaks (rather than being interpreted as + whitespace in standard LaTeX). + + Matplotlib uses the underscore_ package so that underscores (``_``) are + printed "as-is" in text mode (rather than causing an error as in standard + LaTeX). Underscores still introduce subscripts in math mode. + +.. note:: + Certain characters require special escaping in TeX, such as:: + + # $ % & ~ ^ \ { } \( \) \[ \] + + Therefore, these characters will behave differently depending on + :rc:`text.usetex`. As noted above, underscores (``_``) do not require + escaping outside of math mode. + +PostScript options +================== + +In order to produce encapsulated PostScript (EPS) files that can be embedded +in a new LaTeX document, the default behavior of Matplotlib is to distill the +output, which removes some PostScript operators used by LaTeX that are illegal +in an EPS file. This step produces results which may be unacceptable to some +users, because the text is coarsely rasterized and converted to bitmaps, which +are not scalable like standard PostScript, and the text is not searchable. One +workaround is to set :rc:`ps.distiller.res` to a higher value (perhaps 6000) +in your rc settings, which will produce larger files but may look better and +scale reasonably. A better workaround, which requires Poppler_ or Xpdf_, can +be activated by changing :rc:`ps.usedistiller` to ``xpdf``. This alternative +produces PostScript without rasterizing text, so it scales properly, can be +edited in Adobe Illustrator, and searched text in pdf documents. + +.. _usetex-hangups: + +Possible hangups +================ + +* On Windows, the :envvar:`PATH` environment variable may need to be modified + to include the directories containing the latex, dvipng and ghostscript + executables. See :ref:`environment-variables` and + :ref:`setting-windows-environment-variables` for details. + +* Using MiKTeX with Computer Modern fonts, if you get odd \*Agg and PNG + results, go to MiKTeX/Options and update your format files + +* On Ubuntu and Gentoo, the base texlive install does not ship with + the type1cm package. You may need to install some of the extra + packages to get all the goodies that come bundled with other LaTeX + distributions. + +* Some progress has been made so Matplotlib uses the dvi files + directly for text layout. This allows LaTeX to be used for text + layout with the pdf and svg backends, as well as the \*Agg and PS + backends. In the future, a LaTeX installation may be the only + external dependency. + +.. _usetex-troubleshooting: + +Troubleshooting +=============== + +* Try deleting your :file:`.matplotlib/tex.cache` directory. If you don't know + where to find :file:`.matplotlib`, see :ref:`locating-matplotlib-config-dir`. + +* Make sure LaTeX, dvipng and ghostscript are each working and on your + :envvar:`PATH`. + +* Make sure what you are trying to do is possible in a LaTeX document, + that your LaTeX syntax is valid and that you are using raw strings + if necessary to avoid unintended escape sequences. + +* :rc:`text.latex.preamble` is not officially supported. This + option provides lots of flexibility, and lots of ways to cause + problems. Please disable this option before reporting problems to + the mailing list. + +* If you still need help, please see :ref:`reporting-problems`. + +.. _dvipng: http://www.nongnu.org/dvipng/ +.. _dvips: https://tug.org/texinfohtml/dvips.html +.. _Ghostscript: https://ghostscript.com/ +.. _inputenc: https://ctan.org/pkg/inputenc +.. _LaTeX: http://www.tug.org +.. _Poppler: https://poppler.freedesktop.org/ +.. _PSNFSS: http://www.ctan.org/tex-archive/macros/latex/required/psnfss/psnfss2e.pdf +.. _PSfrag: https://ctan.org/pkg/psfrag +.. _underscore: https://ctan.org/pkg/underscore +.. _Xpdf: http://www.xpdfreader.com/ +""" diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axes_grid.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axes_grid.rst new file mode 100644 index 0000000000000000000000000000000000000000..a9c39bd55b1027096f8b4df0bf038af00c101f63 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axes_grid.rst @@ -0,0 +1,332 @@ +.. redirect-from:: /tutorials/toolkits/axes_grid + +.. _axes_grid1_users-guide-index: +.. _axes_grid: + +====================== +The axes_grid1 toolkit +====================== + +:mod:`.axes_grid1` provides the following features: + +- Helper classes (ImageGrid_, RGBAxes_, AxesDivider_) to ease the layout of + axes displaying images with a fixed aspect ratio while satisfying additional + constraints (matching the heights of a colorbar and an image, or fixing the + padding between images); +- ParasiteAxes_ (twinx/twiny-like features so that you can plot different data + (e.g., different y-scale) in a same Axes); +- AnchoredArtists_ (custom artists which are placed at an anchored position, + similarly to legends). + +.. figure:: /gallery/axes_grid1/images/sphx_glr_demo_axes_grid_001.png + :target: /gallery/axes_grid1/demo_axes_grid.html + :align: center + +axes_grid1 +========== + +ImageGrid +--------- + +In Matplotlib, axes location and size are usually specified in normalized +figure coordinates (0 = bottom left, 1 = top right), which makes +it difficult to achieve a fixed (absolute) padding between images. +`~.axes_grid1.axes_grid.ImageGrid` can be used to achieve such a padding; see +its docs for detailed API information. + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_axesgrid_001.png + :target: /gallery/axes_grid1/simple_axesgrid.html + :align: center + +* The position of each axes is determined at the drawing time (see + AxesDivider_), so that the size of the entire grid fits in the + given rectangle (like the aspect of axes). Note that in this example, + the paddings between axes are fixed even if you change the figure + size. + +* Axes in the same column share their x-axis, and axes in the same row share + their y-axis (in the sense of `~.Axes.sharex`, `~.Axes.sharey`). + Additionally, Axes in the same column all have the same width, and axes in + the same row all have the same height. These widths and heights are scaled + in proportion to the axes' view limits (xlim or ylim). + + .. figure:: /gallery/axes_grid1/images/sphx_glr_simple_axesgrid2_001.png + :target: /gallery/axes_grid1/simple_axesgrid2.html + :align: center + +The examples below show what you can do with ImageGrid. + +.. figure:: /gallery/axes_grid1/images/sphx_glr_demo_axes_grid_001.png + :target: /gallery/axes_grid1/demo_axes_grid.html + :align: center + +AxesDivider Class +----------------- + +Behind the scenes, ImageGrid (and RGBAxes, described below) rely on +`~.axes_grid1.axes_divider.AxesDivider`, whose role is to calculate the +location of the axes at drawing time. + +Users typically do not need to directly instantiate dividers +by calling `~.axes_grid1.axes_divider.AxesDivider`; instead, +`~.axes_grid1.axes_divider.make_axes_locatable` can be used to create a divider +for an Axes:: + + ax = subplot(1, 1, 1) + divider = make_axes_locatable(ax) + +`.AxesDivider.append_axes` can then be used to create a new axes on a given +side ("left", "right", "top", "bottom") of the original axes. + +colorbar whose height (or width) is in sync with the main axes +-------------------------------------------------------------- + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_colorbar_001.png + :target: /gallery/axes_grid1/simple_colorbar.html + :align: center + +scatter_hist.py with AxesDivider +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :doc:`/gallery/lines_bars_and_markers/scatter_hist` example can be +rewritten using `~.axes_grid1.axes_divider.make_axes_locatable`:: + + axScatter = plt.subplot() + axScatter.scatter(x, y) + axScatter.set_aspect(1.) + + # create new axes on the right and on the top of the current axes. + divider = make_axes_locatable(axScatter) + axHistx = divider.append_axes("top", size=1.2, pad=0.1, sharex=axScatter) + axHisty = divider.append_axes("right", size=1.2, pad=0.1, sharey=axScatter) + + # the scatter plot: + # histograms + bins = np.arange(-lim, lim + binwidth, binwidth) + axHistx.hist(x, bins=bins) + axHisty.hist(y, bins=bins, orientation='horizontal') + +See the full source code below. + +.. figure:: /gallery/axes_grid1/images/sphx_glr_scatter_hist_locatable_axes_001.png + :target: /gallery/axes_grid1/scatter_hist_locatable_axes.html + :align: center + +The :doc:`/gallery/axes_grid1/scatter_hist_locatable_axes` using the +AxesDivider has some advantages over the +original :doc:`/gallery/lines_bars_and_markers/scatter_hist` in Matplotlib. +For example, you can set the aspect ratio of the scatter plot, even with the +x-axis or y-axis is shared accordingly. + +ParasiteAxes +------------ + +The ParasiteAxes is an Axes whose location is identical to its host +axes. The location is adjusted in the drawing time, thus it works even +if the host change its location (e.g., images). + +In most cases, you first create a host axes, which provides a few +methods that can be used to create parasite axes. They are ``twinx``, +``twiny`` (which are similar to ``twinx`` and ``twiny`` in the matplotlib) and +``twin``. ``twin`` takes an arbitrary transformation that maps between the +data coordinates of the host axes and the parasite axes. The ``draw`` +method of the parasite axes are never called. Instead, host axes +collects artists in parasite axes and draws them as if they belong to +the host axes, i.e., artists in parasite axes are merged to those of +the host axes and then drawn according to their zorder. The host and +parasite axes modifies some of the axes behavior. For example, color +cycle for plot lines are shared between host and parasites. Also, the +legend command in host, creates a legend that includes lines in the +parasite axes. To create a host axes, you may use ``host_subplot`` or +``host_axes`` command. + +Example 1: twinx +~~~~~~~~~~~~~~~~ + +.. figure:: /gallery/axes_grid1/images/sphx_glr_parasite_simple_001.png + :target: /gallery/axes_grid1/parasite_simple.html + :align: center + +Example 2: twin +~~~~~~~~~~~~~~~ + +``twin`` without a transform argument assumes that the parasite axes has the +same data transform as the host. This can be useful when you want the +top(or right)-axis to have different tick-locations, tick-labels, or +tick-formatter for bottom(or left)-axis. :: + + ax2 = ax.twin() # now, ax2 is responsible for "top" axis and "right" axis + ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi], + labels=["0", r"$\frac{1}{2}\pi$", + r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_axisline4_001.png + :target: /gallery/axes_grid1/simple_axisline4.html + :align: center + +A more sophisticated example using twin. Note that if you change the +x-limit in the host axes, the x-limit of the parasite axes will change +accordingly. + +.. figure:: /gallery/axes_grid1/images/sphx_glr_parasite_simple2_001.png + :target: /gallery/axes_grid1/parasite_simple2.html + :align: center + +AnchoredArtists +--------------- + +:mod:`.axes_grid1.anchored_artists` is a collection of artists whose location +is anchored to the (axes) bbox, similarly to legends. These artists derive +from `.offsetbox.OffsetBox`, and the artist need to be drawn in canvas +coordinates. There is limited support for arbitrary transforms. For example, +the ellipse in the example below will have width and height in data coordinates. + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_anchored_artists_001.png + :target: /gallery/axes_grid1/simple_anchored_artists.html + :align: center + +InsetLocator +------------ + +.. seealso:: + `.Axes.inset_axes` and `.Axes.indicate_inset_zoom` in the main library. + +:mod:`.axes_grid1.inset_locator` provides helper classes and functions to +place inset axes at an anchored position of the parent axes, similarly to +AnchoredArtist. + +`.inset_locator.inset_axes` creates an inset axes whose size is either fixed, +or a fixed proportion of the parent axes:: + + inset_axes = inset_axes(parent_axes, + width="30%", # width = 30% of parent_bbox + height=1., # height = 1 inch + loc='lower left') + +creates an inset axes whose width is 30% of the parent axes and whose +height is fixed at 1 inch. + +`.inset_locator.zoomed_inset_axes` creates an inset axes whose data scale is +that of the parent axes multiplied by some factor, e.g. :: + + inset_axes = zoomed_inset_axes(ax, + 0.5, # zoom = 0.5 + loc='upper right') + +creates an inset axes whose data scale is half of the parent axes. This can be +useful to mark the zoomed area on the parent axes: + +.. figure:: /gallery/axes_grid1/images/sphx_glr_inset_locator_demo_001.png + :target: /gallery/axes_grid1/inset_locator_demo.html + :align: center + +`.inset_locator.mark_inset` allows marking the location of the area represented +by the inset axes: + +.. figure:: /gallery/axes_grid1/images/sphx_glr_inset_locator_demo2_001.png + :target: /gallery/axes_grid1/inset_locator_demo2.html + :align: center + +RGBAxes +------- + +RGBAxes is a helper class to conveniently show RGB composite +images. Like ImageGrid, the location of axes are adjusted so that the +area occupied by them fits in a given rectangle. Also, the xaxis and +yaxis of each axes are shared. :: + + from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes + + fig = plt.figure() + ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0) + r, g, b = get_rgb() # r, g, b are 2D images. + ax.imshow_rgb(r, g, b) + +.. figure:: /gallery/axes_grid1/images/sphx_glr_demo_axes_rgb_001.png + :target: /gallery/axes_grid1/demo_axes_rgb.html + :align: center + +AxesDivider +=========== + +The :mod:`mpl_toolkits.axes_grid1.axes_divider` module provides helper classes +to adjust the axes positions of a set of images at drawing time. + +* :mod:`~mpl_toolkits.axes_grid1.axes_size` provides a class of + units that are used to determine the size of each axes. For example, + you can specify a fixed size. + +* `~mpl_toolkits.axes_grid1.axes_divider.Divider` is the class that + calculates the axes position. It divides the given rectangular area into + several areas. The divider is initialized by setting the lists of horizontal + and vertical sizes on which the division will be based. Then use + :meth:`~mpl_toolkits.axes_grid1.axes_divider.Divider.new_locator`, which + returns a callable object that can be used to set the axes_locator of the + axes. + +Here, we demonstrate how to achieve the following layout: we want to position +axes in a 3x4 grid (note that `.Divider` makes row indices start from the +*bottom*\(!) of the grid): + +.. code-block:: none + + ┌────────┬────────┬────────┬────────┐ + │ (2, 0) │ (2, 1) │ (2, 2) │ (2, 3) │ + ├────────┼────────┼────────┼────────┤ + │ (1, 0) │ (1, 1) │ (1, 2) │ (1, 3) │ + ├────────┼────────┼────────┼────────┤ + │ (0, 0) │ (0, 1) │ (0, 2) │ (0, 3) │ + └────────┴────────┴────────┴────────┘ + +such that the bottom row has a fixed height of 2 (inches) and the top two rows +have a height ratio of 2 (middle) to 3 (top). (For example, if the grid has +a size of 7 inches, the bottom row will be 2 inches, the middle row also 2 +inches, and the top row 3 inches.) + +These constraints are specified using classes from the +:mod:`~mpl_toolkits.axes_grid1.axes_size` module, namely:: + + from mpl_toolkits.axes_grid1.axes_size import Fixed, Scaled + vert = [Fixed(2), Scaled(2), Scaled(3)] + +(More generally, :mod:`~mpl_toolkits.axes_grid1.axes_size` classes define a +``get_size(renderer)`` method that returns a pair of floats -- a relative size, +and an absolute size. ``Fixed(2).get_size(renderer)`` returns ``(0, 2)``; +``Scaled(2).get_size(renderer)`` returns ``(2, 0)``.) + +We use these constraints to initialize a `.Divider` object:: + + rect = [0.2, 0.2, 0.6, 0.6] # Position of the grid in the figure. + vert = [Fixed(2), Scaled(2), Scaled(3)] # As above. + horiz = [...] # Some other horizontal constraints. + divider = Divider(fig, rect, horiz, vert) + +then use `.Divider.new_locator` to create an axes locator callable for a +given grid entry:: + + locator = divider.new_locator(nx=0, ny=1) # Grid entry (1, 0). + +and make it responsible for locating the axes:: + + ax.set_axes_locator(locator) + +The axes locator callable returns the location and size of +the cell at the first column and the second row. + +Locators that spans over multiple cells can be created with, e.g.:: + + # Columns #0 and #1 ("0-2 range"), row #1. + locator = divider.new_locator(nx=0, nx1=2, ny=1) + +See the example, + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_axes_divider1_001.png + :target: /gallery/axes_grid1/simple_axes_divider1.html + :align: center + +You can also adjust the size of each axes according to its x or y +data limits (AxesX and AxesY). + +.. figure:: /gallery/axes_grid1/images/sphx_glr_simple_axes_divider3_001.png + :target: /gallery/axes_grid1/simple_axes_divider3.html + :align: center diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axisartist.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axisartist.rst new file mode 100644 index 0000000000000000000000000000000000000000..9246fb27271bc499cf34e1ab5d841fac12b8b119 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/axisartist.rst @@ -0,0 +1,562 @@ +.. redirect-from:: /tutorials/toolkits/axisartist + +.. _axisartist: + +====================== +The axisartist toolkit +====================== + +.. warning:: + *axisartist* uses a custom Axes class + (derived from the Matplotlib's original Axes class). + As a side effect, some commands (mostly tick-related) do not work. + +The *axisartist* contains a custom Axes class that is meant to support +curvilinear grids (e.g., the world coordinate system in astronomy). +Unlike Matplotlib's original Axes class which uses Axes.xaxis and Axes.yaxis +to draw ticks, ticklines, etc., axisartist uses a special +artist (AxisArtist) that can handle ticks, ticklines, etc. for +curved coordinate systems. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_floating_axis_001.png + :target: /gallery/axisartist/demo_floating_axis.html + :align: center + +Since it uses special artists, some Matplotlib commands that work on +Axes.xaxis and Axes.yaxis may not work. + +.. _axisartist_users-guide-index: + +axisartist +========== + +The *axisartist* module provides a custom (and very experimental) Axes +class, where each axis (left, right, top, and bottom) have a separate +associated artist which is responsible for drawing the axis-line, ticks, +ticklabels, and labels. You can also create your own axis, which can pass +through a fixed position in the axes coordinate, or a fixed position +in the data coordinate (i.e., the axis floats around when viewlimit +changes). + +The axes class, by default, has its xaxis and yaxis invisible, and +has 4 additional artists which are responsible for drawing the 4 axis spines in +"left", "right", "bottom", and "top". They are accessed as +ax.axis["left"], ax.axis["right"], and so on, i.e., ax.axis is a +dictionary that contains artists (note that ax.axis is still a +callable method and it behaves as an original Axes.axis method in +Matplotlib). + +To create an Axes, :: + + import mpl_toolkits.axisartist as AA + fig = plt.figure() + fig.add_axes([0.1, 0.1, 0.8, 0.8], axes_class=AA.Axes) + +or to create a subplot :: + + fig.add_subplot(111, axes_class=AA.Axes) + # Given that 111 is the default, one can also do + fig.add_subplot(axes_class=AA.Axes) + +For example, you can hide the right and top spines using:: + + ax.axis["right"].set_visible(False) + ax.axis["top"].set_visible(False) + +.. figure:: /gallery/axisartist/images/sphx_glr_simple_axisline3_001.png + :target: /gallery/axisartist/simple_axisline3.html + :align: center + +It is also possible to add a horizontal axis. For example, you may have an +horizontal axis at y=0 (in data coordinate). :: + + ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0) + +.. figure:: /gallery/axisartist/images/sphx_glr_simple_axisartist1_001.png + :target: /gallery/axisartist/simple_axisartist1.html + :align: center + +Or a fixed axis with some offset :: + + # make new (right-side) yaxis, but with some offset + ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(20, 0)) + +axisartist with ParasiteAxes +---------------------------- + +Most commands in the axes_grid1 toolkit can take an axes_class keyword +argument, and the commands create an Axes of the given class. For example, +to create a host subplot with axisartist.Axes, :: + + import mpl_toolkits.axisartist as AA + from mpl_toolkits.axes_grid1 import host_subplot + + host = host_subplot(111, axes_class=AA.Axes) + +Here is an example that uses ParasiteAxes. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_parasite_axes2_001.png + :target: /gallery/axisartist/demo_parasite_axes2.html + :align: center + +Curvilinear Grid +---------------- + +The motivation behind the AxisArtist module is to support a curvilinear grid +and ticks. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_curvelinear_grid_001.png + :target: /gallery/axisartist/demo_curvelinear_grid.html + :align: center + +Floating Axes +------------- + +AxisArtist also supports a Floating Axes whose outer axes are defined as +floating axis. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_floating_axes_001.png + :target: /gallery/axisartist/demo_floating_axes.html + :align: center + +axisartist namespace +==================== + +The *axisartist* namespace includes a derived Axes implementation. The +biggest difference is that the artists responsible to draw axis line, +ticks, ticklabel and axis labels are separated out from the Matplotlib's Axis +class, which are much more than artists in the original Matplotlib. This +change was strongly motivated to support curvilinear grid. Here are a +few things that mpl_toolkits.axisartist.Axes is different from original +Axes from Matplotlib. + +* Axis elements (axis line(spine), ticks, ticklabel and axis labels) + are drawn by a AxisArtist instance. Unlike Axis, left, right, top + and bottom axis are drawn by separate artists. And each of them may + have different tick location and different tick labels. + +* gridlines are drawn by a Gridlines instance. The change was + motivated that in curvilinear coordinate, a gridline may not cross + axis-lines (i.e., no associated ticks). In the original Axes class, + gridlines are tied to ticks. + +* ticklines can be rotated if necessary (i.e, along the gridlines) + +In summary, all these changes was to support + +* a curvilinear grid. +* a floating axis + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_floating_axis_001.png + :target: /gallery/axisartist/demo_floating_axis.html + :align: center + +*mpl_toolkits.axisartist.Axes* class defines a *axis* attribute, which +is a dictionary of AxisArtist instances. By default, the dictionary +has 4 AxisArtist instances, responsible for drawing of left, right, +bottom and top axis. + +xaxis and yaxis attributes are still available, however they are set +to not visible. As separate artists are used for rendering axis, some +axis-related method in Matplotlib may have no effect. +In addition to AxisArtist instances, the mpl_toolkits.axisartist.Axes will +have *gridlines* attribute (Gridlines), which obviously draws grid +lines. + +In both AxisArtist and Gridlines, the calculation of tick and grid +location is delegated to an instance of GridHelper class. +mpl_toolkits.axisartist.Axes class uses GridHelperRectlinear as a grid +helper. The GridHelperRectlinear class is a wrapper around the *xaxis* +and *yaxis* of Matplotlib's original Axes, and it was meant to work as the +way how Matplotlib's original axes works. For example, tick location changes +using set_ticks method and etc. should work as expected. But change in +artist properties (e.g., color) will not work in general, although +some effort has been made so that some often-change attributes (color, +etc.) are respected. + +AxisArtist +========== + +AxisArtist can be considered as a container artist with following +attributes which will draw ticks, labels, etc. + +* line +* major_ticks, major_ticklabels +* minor_ticks, minor_ticklabels +* offsetText +* label + +line +---- + +Derived from Line2D class. Responsible for drawing a spinal(?) line. + +major_ticks, minor_ticks +------------------------ + +Derived from Line2D class. Note that ticks are markers. + +major_ticklabels, minor_ticklabels +---------------------------------- + +Derived from Text. Note that it is not a list of Text artist, but a +single artist (similar to a collection). + +axislabel +--------- + +Derived from Text. + +Default AxisArtists +=================== + +By default, following for axis artists are defined.:: + + ax.axis["left"], ax.axis["bottom"], ax.axis["right"], ax.axis["top"] + +The ticklabels and axislabel of the top and the right axis are set to +not visible. + +For example, if you want to change the color attributes of +major_ticklabels of the bottom x-axis :: + + ax.axis["bottom"].major_ticklabels.set_color("b") + +Similarly, to make ticklabels invisible :: + + ax.axis["bottom"].major_ticklabels.set_visible(False) + +AxisArtist provides a helper method to control the visibility of ticks, +ticklabels, and label. To make ticklabel invisible, :: + + ax.axis["bottom"].toggle(ticklabels=False) + +To make all of ticks, ticklabels, and (axis) label invisible :: + + ax.axis["bottom"].toggle(all=False) + +To turn all off but ticks on :: + + ax.axis["bottom"].toggle(all=False, ticks=True) + +To turn all on but (axis) label off :: + + ax.axis["bottom"].toggle(all=True, label=False) + +ax.axis's __getitem__ method can take multiple axis names. For +example, to turn ticklabels of "top" and "right" axis on, :: + + ax.axis["top", "right"].toggle(ticklabels=True) + +Note that ``ax.axis["top", "right"]`` returns a simple proxy object that +translate above code to something like below. :: + + for n in ["top", "right"]: + ax.axis[n].toggle(ticklabels=True) + +So, any return values in the for loop are ignored. And you should not +use it anything more than a simple method. + +Like the list indexing ":" means all items, i.e., :: + + ax.axis[:].major_ticks.set_color("r") + +changes tick color in all axis. + +HowTo +===== + +1. Changing tick locations and label. + + Same as the original Matplotlib's axes:: + + ax.set_xticks([1, 2, 3]) + +2. Changing axis properties like color, etc. + + Change the properties of appropriate artists. For example, to change + the color of the ticklabels:: + + ax.axis["left"].major_ticklabels.set_color("r") + +3. To change the attributes of multiple axis:: + + ax.axis["left", "bottom"].major_ticklabels.set_color("r") + + or to change the attributes of all axis:: + + ax.axis[:].major_ticklabels.set_color("r") + +4. To change the tick size (length), you need to use + axis.major_ticks.set_ticksize method. To change the direction of + the ticks (ticks are in opposite direction of ticklabels by + default), use axis.major_ticks.set_tick_out method. + + To change the pad between ticks and ticklabels, use + axis.major_ticklabels.set_pad method. + + To change the pad between ticklabels and axis label, + axis.label.set_pad method. + +Rotation and Alignment of TickLabels +==================================== + +This is also quite different from standard Matplotlib and can be +confusing. When you want to rotate the ticklabels, first consider +using "set_axis_direction" method. :: + + ax1.axis["left"].major_ticklabels.set_axis_direction("top") + ax1.axis["right"].label.set_axis_direction("left") + +.. figure:: /gallery/axisartist/images/sphx_glr_simple_axis_direction01_001.png + :target: /gallery/axisartist/simple_axis_direction01.html + :align: center + +The parameter for set_axis_direction is one of ["left", "right", +"bottom", "top"]. + +You must understand some underlying concept of directions. + +- There is a reference direction which is defined as the direction + of the axis line with increasing coordinate. For example, the + reference direction of the left x-axis is from bottom to top. + + The direction, text angle, and alignments of the ticks, ticklabels and + axis-label is determined with respect to the reference direction + +- *label_direction* and *ticklabel_direction* are either the right-hand side + (+) of the reference direction or the left-hand side (-). + +- ticks are by default drawn toward the opposite direction of the ticklabels. + +- text rotation of ticklabels and label is determined in reference + to the *ticklabel_direction* or *label_direction*, + respectively. The rotation of ticklabels and label is anchored. + +.. figure:: /gallery/axisartist/images/sphx_glr_axis_direction_001.png + :target: /gallery/axisartist/axis_direction.html + :align: center + +On the other hand, there is a concept of "axis_direction". This is a +default setting of above properties for each, "bottom", "left", "top", +and "right" axis. + +========== =========== ========= ========== ========= ========== + ? ? left bottom right top +---------- ----------- --------- ---------- --------- ---------- +axislabel direction '-' '+' '+' '-' +axislabel rotation 180 0 0 180 +axislabel va center top center bottom +axislabel ha right center right center +ticklabel direction '-' '+' '+' '-' +ticklabels rotation 90 0 -90 180 +ticklabel ha right center right center +ticklabel va center baseline center baseline +========== =========== ========= ========== ========= ========== + +And, 'set_axis_direction("top")' means to adjust the text rotation +etc, for settings suitable for "top" axis. The concept of axis +direction can be more clear with curved axis. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_axis_direction_001.png + :target: /gallery/axisartist/demo_axis_direction.html + :align: center + +The axis_direction can be adjusted in the AxisArtist level, or in the +level of its child artists, i.e., ticks, ticklabels, and axis-label. :: + + ax1.axis["left"].set_axis_direction("top") + +changes axis_direction of all the associated artist with the "left" +axis, while :: + + ax1.axis["left"].major_ticklabels.set_axis_direction("top") + +changes the axis_direction of only the major_ticklabels. Note that +set_axis_direction in the AxisArtist level changes the +ticklabel_direction and label_direction, while changing the +axis_direction of ticks, ticklabels, and axis-label does not affect +them. + +If you want to make ticks outward and ticklabels inside the axes, +use invert_ticklabel_direction method. :: + + ax.axis[:].invert_ticklabel_direction() + +A related method is "set_tick_out". It makes ticks outward (as a +matter of fact, it makes ticks toward the opposite direction of the +default direction). :: + + ax.axis[:].major_ticks.set_tick_out(True) + +.. figure:: /gallery/axisartist/images/sphx_glr_simple_axis_direction03_001.png + :target: /gallery/axisartist/simple_axis_direction03.html + :align: center + +So, in summary, + +* AxisArtist's methods + + - set_axis_direction: "left", "right", "bottom", or "top" + - set_ticklabel_direction: "+" or "-" + - set_axislabel_direction: "+" or "-" + - invert_ticklabel_direction + +* Ticks' methods (major_ticks and minor_ticks) + + - set_tick_out: True or False + - set_ticksize: size in points + +* TickLabels' methods (major_ticklabels and minor_ticklabels) + + - set_axis_direction: "left", "right", "bottom", or "top" + - set_rotation: angle with respect to the reference direction + - set_ha and set_va: see below + +* AxisLabels' methods (label) + + - set_axis_direction: "left", "right", "bottom", or "top" + - set_rotation: angle with respect to the reference direction + - set_ha and set_va + +Adjusting ticklabels alignment +------------------------------ + +Alignment of TickLabels are treated specially. See below + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_ticklabel_alignment_001.png + :target: /gallery/axisartist/demo_ticklabel_alignment.html + :align: center + +Adjusting pad +------------- + +To change the pad between ticks and ticklabels :: + + ax.axis["left"].major_ticklabels.set_pad(10) + +Or ticklabels and axis-label :: + + ax.axis["left"].label.set_pad(10) + +.. figure:: /gallery/axisartist/images/sphx_glr_simple_axis_pad_001.png + :target: /gallery/axisartist/simple_axis_pad.html + :align: center + +GridHelper +========== + +To actually define a curvilinear coordinate, you have to use your own +grid helper. A generalised version of grid helper class is supplied +and this class should suffice in most of cases. A user may provide +two functions which defines a transformation (and its inverse pair) +from the curved coordinate to (rectilinear) image coordinate. Note that +while ticks and grids are drawn for curved coordinate, the data +transform of the axes itself (ax.transData) is still rectilinear +(image) coordinate. :: + + from mpl_toolkits.axisartist.grid_helper_curvelinear \ + import GridHelperCurveLinear + from mpl_toolkits.axisartist import Axes + + # from curved coordinate to rectlinear coordinate. + def tr(x, y): + x, y = np.asarray(x), np.asarray(y) + return x, y-x + + # from rectlinear coordinate to curved coordinate. + def inv_tr(x, y): + x, y = np.asarray(x), np.asarray(y) + return x, y+x + + grid_helper = GridHelperCurveLinear((tr, inv_tr)) + + fig.add_subplot(axes_class=Axes, grid_helper=grid_helper) + +You may use Matplotlib's Transform instance instead (but a +inverse transformation must be defined). Often, coordinate range in a +curved coordinate system may have a limited range, or may have +cycles. In those cases, a more customized version of grid helper is +required. :: + + import mpl_toolkits.axisartist.angle_helper as angle_helper + + # PolarAxes.PolarTransform takes radian. However, we want our coordinate + # system in degree + tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() + + # extreme finder: find a range of coordinate. + # 20, 20: number of sampling points along x, y direction + # The first coordinate (longitude, but theta in polar) + # has a cycle of 360 degree. + # The second coordinate (latitude, but radius in polar) has a minimum of 0 + extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, + lon_cycle=360, + lat_cycle=None, + lon_minmax=None, + lat_minmax=(0, np.inf), + ) + + # Find a grid values appropriate for the coordinate (degree, + # minute, second). The argument is a approximate number of grids. + grid_locator1 = angle_helper.LocatorDMS(12) + + # And also uses an appropriate formatter. Note that the acceptable Locator + # and Formatter classes are different than that of Matplotlib's, and you + # cannot directly use Matplotlib's Locator and Formatter here (but may be + # possible in the future). + tick_formatter1 = angle_helper.FormatterDMS() + + grid_helper = GridHelperCurveLinear(tr, + extreme_finder=extreme_finder, + grid_locator1=grid_locator1, + tick_formatter1=tick_formatter1 + ) + +Again, the *transData* of the axes is still a rectilinear coordinate +(image coordinate). You may manually do conversion between two +coordinates, or you may use Parasite Axes for convenience.:: + + ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper) + + # A parasite axes with given transform + ax2 = ax1.get_aux_axes(tr, "equal") + # note that ax2.transData == tr + ax1.transData + # Anything you draw in ax2 will match the ticks and grids of ax1. + +.. figure:: /gallery/axisartist/images/sphx_glr_demo_curvelinear_grid_001.png + :target: /gallery/axisartist/demo_curvelinear_grid.html + :align: center + +FloatingAxis +============ + +A floating axis is an axis one of whose data coordinate is fixed, i.e, +its location is not fixed in Axes coordinate but changes as axes data +limits changes. A floating axis can be created using +*new_floating_axis* method. However, it is your responsibility that +the resulting AxisArtist is properly added to the axes. A recommended +way is to add it as an item of Axes's axis attribute.:: + + # floating axis whose first (index starts from 0) coordinate + # (theta) is fixed at 60 + + ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60) + axis.label.set_text(r"$\theta = 60^{\circ}$") + axis.label.set_visible(True) + +See the first example of this page. + +Current Limitations and TODO's +============================== + +The code need more refinement. Here is a incomplete list of issues and TODO's + +* No easy way to support a user customized tick location (for + curvilinear grid). A new Locator class needs to be created. + +* FloatingAxis may have coordinate limits, e.g., a floating axis of x = 0, + but y only spans from 0 to 1. + +* The location of axislabel of FloatingAxis needs to be optionally + given as a coordinate value. ex, a floating axis of x=0 with label at y=1 diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/index.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d9f38388da81c69f2172f784c30af2a43c5ac500 --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/index.rst @@ -0,0 +1,15 @@ +.. _tutorials-toolkits: + +.. redirect-from:: /tutorials/toolkits + +User Toolkits +============= + +Here you can find examples and explanations of how to use various toolkits available in Matplotlib. + +.. toctree:: + :maxdepth: 1 + + axisartist + axes_grid + mplot3d diff --git a/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/mplot3d.rst b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/mplot3d.rst new file mode 100644 index 0000000000000000000000000000000000000000..2551c065ea462c196059c80c4b5898368235b6ba --- /dev/null +++ b/testbed/matplotlib__matplotlib/galleries/users_explain/toolkits/mplot3d.rst @@ -0,0 +1,160 @@ + + +.. redirect-from:: /tutorials/toolkits/mplot3d + +.. _mplot3d: + +=================== +The mplot3d toolkit +=================== + +Generating 3D plots using the mplot3d toolkit. + +This tutorial showcases various 3D plots. Click on the figures to see each full +gallery example with the code that generates the figures. + +.. contents:: + :backlinks: none + +3D Axes (of class `.Axes3D`) are created by passing the ``projection="3d"`` +keyword argument to `.Figure.add_subplot`:: + + import matplotlib.pyplot as plt + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + +Multiple 3D subplots can be added on the same figure, as for 2D subplots. + +.. figure:: /gallery/mplot3d/images/sphx_glr_subplot3d_001.png + :target: /gallery/mplot3d/subplot3d.html + :align: center + +.. versionchanged:: 3.2.0 + Prior to Matplotlib 3.2.0, it was necessary to explicitly import the + :mod:`mpl_toolkits.mplot3d` module to make the '3d' projection to + `.Figure.add_subplot`. + +See the :ref:`toolkit_mplot3d-faq` for more information about the mplot3d +toolkit. + +.. _plot3d: + +Line plots +========== +See `.Axes3D.plot` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_lines3d_001.png + :target: /gallery/mplot3d/lines3d.html + :align: center + +.. _scatter3d: + +Scatter plots +============= +See `.Axes3D.scatter` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_scatter3d_001.png + :target: /gallery/mplot3d/scatter3d.html + :align: center + +.. _wireframe: + +Wireframe plots +=============== +See `.Axes3D.plot_wireframe` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_wire3d_001.png + :target: /gallery/mplot3d/wire3d.html + :align: center + +.. _surface: + +Surface plots +============= +See `.Axes3D.plot_surface` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_surface3d_001.png + :target: /gallery/mplot3d/surface3d.html + :align: center + +.. _trisurface: + +Tri-Surface plots +================= +See `.Axes3D.plot_trisurf` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_trisurf3d_001.png + :target: /gallery/mplot3d/trisurf3d.html + :align: center + +.. _contour3d: + +Contour plots +============= +See `.Axes3D.contour` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_contour3d_001.png + :target: /gallery/mplot3d/contour3d.html + :align: center + +.. _contourf3d: + +Filled contour plots +==================== +See `.Axes3D.contourf` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_contourf3d_001.png + :target: /gallery/mplot3d/contourf3d.html + :align: center + +.. versionadded:: 1.1.0 + The feature demoed in the second contourf3d example was enabled as a + result of a bugfix for version 1.1.0. + +.. _polygon3d: + +Polygon plots +============= +See `.Axes3D.add_collection3d` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_polys3d_001.png + :target: /gallery/mplot3d/polys3d.html + :align: center + +.. _bar3d: + +Bar plots +========= +See `.Axes3D.bar` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_bars3d_001.png + :target: /gallery/mplot3d/bars3d.html + :align: center + +.. _quiver3d: + +Quiver +====== +See `.Axes3D.quiver` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_quiver3d_001.png + :target: /gallery/mplot3d/quiver3d.html + :align: center + +.. _2dcollections3d: + +2D plots in 3D +============== +.. figure:: /gallery/mplot3d/images/sphx_glr_2dcollections3d_001.png + :target: /gallery/mplot3d/2dcollections3d.html + :align: center + +.. _text3d: + +Text +==== +See `.Axes3D.text` for API documentation. + +.. figure:: /gallery/mplot3d/images/sphx_glr_text3d_001.png + :target: /gallery/mplot3d/text3d.html + :align: center diff --git a/testbed/matplotlib__matplotlib/mplsetup.cfg.template b/testbed/matplotlib__matplotlib/mplsetup.cfg.template new file mode 100644 index 0000000000000000000000000000000000000000..30985b2e313d07f4ac04d2d0b1d4b6f60996cc67 --- /dev/null +++ b/testbed/matplotlib__matplotlib/mplsetup.cfg.template @@ -0,0 +1,38 @@ +# Rename this file to mplsetup.cfg to modify Matplotlib's build options. + +[libs] +# By default, Matplotlib builds with LTO, which may be slow if you re-compile +# often, and don't need the space saving/speedup. +# +#enable_lto = True +# +# By default, Matplotlib downloads and builds its own copies of FreeType and of +# Qhull. You may set the following to True to instead link against a system +# FreeType/Qhull. As an exception, Matplotlib defaults to the system version +# of FreeType on AIX. +# +#system_freetype = False +#system_qhull = False + +[packages] +# Some of Matplotlib's components are optional: the MacOSX backend (installed +# by default on MacOSX; requires the Cocoa headers included with XCode), and +# the test data (i.e., the baseline image files; not installed by default). +# You can control whether they are installed by uncommenting the following +# lines. Note that the MacOSX backend is never built on Linux or Windows, +# regardless of the config value. +# +#tests = False +#macosx = True + +[rc_options] +# User-configurable options +# +# Default backend, one of: Agg, Cairo, GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, +# MacOSX, Pdf, Ps, QtAgg, QtCairo, SVG, TkAgg, WX, WXAgg. +# +# The Agg, Ps, Pdf and SVG backends do not require external dependencies. Do +# not choose MacOSX if you have disabled the relevant extension modules. The +# default is determined by fallback. +# +#backend = Agg diff --git a/testbed/matplotlib__matplotlib/pyproject.toml b/testbed/matplotlib__matplotlib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d2e2f769b7efbc04aff10ab95a7978a3d9afaff4 --- /dev/null +++ b/testbed/matplotlib__matplotlib/pyproject.toml @@ -0,0 +1,142 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = [ + "certifi>=2020.06.20", + "numpy>=1.25", + "pybind11>=2.6", + "setuptools>=42", + "setuptools_scm>=7", +] + +[tool.isort] +known_pydata = "numpy, matplotlib.pyplot" +known_firstparty = "matplotlib,mpl_toolkits" +sections = "FUTURE,STDLIB,THIRDPARTY,PYDATA,FIRSTPARTY,LOCALFOLDER" +force_sort_within_sections = true + +[tool.ruff] +exclude = [ + ".git", + "build", + "doc/gallery", + "doc/tutorials", + "tools/gh_api.py", + ".tox", + ".eggs", +] +ignore = [ + "D100", + "D101", + "D102", + "D103", + "D104", + "D105", + "D106", + "D200", + "D202", + "D204", + "D205", + "D301", + "D400", + "D401", + "D403", + "D404", + "E741", + "F841", +] +line-length = 88 +select = [ + "D", + "E", + "F", + "W", +] + +# The following error codes are not supported by ruff v0.0.240 +# They are planned and should be selected once implemented +# even if they are deselected by default. +# These are primarily whitespace/corrected by autoformatters (which we don't use). +# See https://github.com/charliermarsh/ruff/issues/2402 for status on implementation +external = [ + "E122", + "E201", + "E202", + "E203", + "E221", + "E251", + "E261", + "E272", + "E302", + "E703", +] + +target-version = "py39" + +[tool.ruff.pydocstyle] +convention = "numpy" + +[tool.ruff.per-file-ignores] +"setup.py" = ["E402"] + +"doc/conf.py" = ["E402"] +"galleries/examples/animation/frame_grabbing_sgskip.py" = ["E402"] +"galleries/examples/lines_bars_and_markers/marker_reference.py" = ["E402"] +"galleries/examples/misc/print_stdout_sgskip.py" = ["E402"] +"galleries/examples/style_sheets/bmh.py" = ["E501"] +"galleries/examples/subplots_axes_and_figures/demo_constrained_layout.py" = ["E402"] +"galleries/examples/text_labels_and_annotations/custom_legends.py" = ["E402"] +"galleries/examples/ticks/date_concise_formatter.py" = ["E402"] +"galleries/examples/ticks/date_formatters_locators.py" = ["F401"] +"galleries/examples/user_interfaces/embedding_in_gtk3_panzoom_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/embedding_in_gtk3_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/embedding_in_gtk4_panzoom_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/embedding_in_gtk4_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/gtk3_spreadsheet_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/gtk4_spreadsheet_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/mpl_with_glade3_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/pylab_with_gtk3_sgskip.py" = ["E402"] +"galleries/examples/user_interfaces/pylab_with_gtk4_sgskip.py" = ["E402"] +"galleries/examples/userdemo/pgf_preamble_sgskip.py" = ["E402"] + +"lib/matplotlib/__init__.py" = ["E402", "F401"] +"lib/matplotlib/_animation_data.py" = ["E501"] +"lib/matplotlib/_api/__init__.py" = ["F401"] +"lib/matplotlib/axes/__init__.py" = ["F401", "F403"] +"lib/matplotlib/backends/backend_template.py" = ["F401"] +"lib/matplotlib/font_manager.py" = ["E501"] +"lib/matplotlib/image.py" = ["F401", "F403"] +"lib/matplotlib/pylab.py" = ["F401", "F403"] +"lib/matplotlib/pyplot.py" = ["F401", "F811"] +"lib/matplotlib/tests/test_mathtext.py" = ["E501"] +"lib/mpl_toolkits/axisartist/__init__.py" = ["F401"] +"lib/pylab.py" = ["F401", "F403"] + +"galleries/users_explain/artists/paths.py" = ["E402"] +"galleries/users_explain/artists/patheffects_guide.py" = ["E402"] +"galleries/users_explain/artists/transforms_tutorial.py" = ["E402", "E501"] +"galleries/users_explain/colors/colormaps.py" = ["E501"] +"galleries/users_explain/colors/colors.py" = ["E402"] +"galleries/tutorials/artists.py" = ["E402"] +"galleries/users_explain/axes/constrainedlayout_guide.py" = ["E402"] +"galleries/users_explain/axes/legend_guide.py" = ["E402"] +"galleries/users_explain/axes/tight_layout_guide.py" = ["E402"] +"galleries/users_explain/animations/animations.py" = ["E501"] +"galleries/tutorials/images.py" = ["E501"] +"galleries/tutorials/pyplot.py" = ["E402", "E501"] +"galleries/users_explain/text/annotations.py" = ["E402", "E501"] +"galleries/users_explain/text/mathtext.py" = ["E501"] +"galleries/users_explain/text/text_intro.py" = ["E402"] +"galleries/users_explain/text/text_props.py" = ["E501"] + +[tool.mypy] +exclude = [ + ".*/matplotlib/(sphinxext|backends|testing/jpl_units)", + ".*/mpl_toolkits", + # tinypages is used for testing the sphinx ext, + # stubtest will import and run, opening a figure if not excluded + ".*/tinypages", +] +ignore_missing_imports = true +enable_incomplete_feature = [ + "Unpack", +] diff --git a/testbed/matplotlib__matplotlib/pytest.ini b/testbed/matplotlib__matplotlib/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..68920f59be0179833ce700f5b1dc191063e8fe87 --- /dev/null +++ b/testbed/matplotlib__matplotlib/pytest.ini @@ -0,0 +1,12 @@ +# Because tests can be run from an installed copy, most of our Pytest +# configuration is in the `pytest_configure` function in +# `lib/matplotlib/testing/conftest.py`. This configuration file exists only to +# set a minimum pytest version and to prevent pytest from wasting time trying +# to check examples and documentation files that are not really tests. + +[pytest] +minversion = 7.0.0 + +testpaths = lib +python_files = test_*.py +junit_family = xunit2 diff --git a/testbed/matplotlib__matplotlib/setup.cfg b/testbed/matplotlib__matplotlib/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..9d4cf0e7b72c8b9432bfc241c5150ee172897705 --- /dev/null +++ b/testbed/matplotlib__matplotlib/setup.cfg @@ -0,0 +1,5 @@ +# NOTE: Matplotlib-specific configuration options have been moved to +# mplsetup.cfg.template. + +[metadata] +license_files = LICENSE/* diff --git a/testbed/matplotlib__matplotlib/setup.py b/testbed/matplotlib__matplotlib/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..de8976cb70d25d7c17d6faf79de2b8524ba2f1bb --- /dev/null +++ b/testbed/matplotlib__matplotlib/setup.py @@ -0,0 +1,364 @@ +""" +The Matplotlib build options can be modified with a mplsetup.cfg file. See +mplsetup.cfg.template for more information. +""" + +# NOTE: This file must remain Python 2 compatible for the foreseeable future, +# to ensure that we error out properly for people with outdated setuptools +# and/or pip. +import sys + +py_min_version = (3, 9) # minimal supported python version +since_mpl_version = (3, 8) # py_min_version is required since this mpl version + +if sys.version_info < py_min_version: + error = """ +Beginning with Matplotlib {0}, Python {1} or above is required. +You are using Python {2}. + +This may be due to an out of date pip. + +Make sure you have pip >= 9.0.1. +""".format('.'.join(str(n) for n in since_mpl_version), + '.'.join(str(n) for n in py_min_version), + '.'.join(str(n) for n in sys.version_info[:3])) + sys.exit(error) + +import os +from pathlib import Path +import shutil +import subprocess + +from setuptools import setup, find_namespace_packages, Distribution, Extension +import setuptools.command.build_ext +import setuptools.command.build_py +import setuptools.command.sdist + +# sys.path modified to find setupext.py during pyproject.toml builds. +sys.path.append(str(Path(__file__).resolve().parent)) + +import setupext +from setupext import print_raw, print_status + + +# These are the packages in the order we want to display them. +mpl_packages = [ + setupext.Matplotlib(), + setupext.Python(), + setupext.Platform(), + setupext.FreeType(), + setupext.Qhull(), + setupext.Tests(), + setupext.BackendMacOSX(), + ] + + +# From https://bugs.python.org/issue26689 +def has_flag(self, flagname): + """Return whether a flag name is supported on the specified compiler.""" + import tempfile + with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: + f.write('int main (int argc, char **argv) { return 0; }') + try: + self.compile([f.name], extra_postargs=[flagname]) + except Exception as exc: + # https://github.com/pypa/setuptools/issues/2698 + if type(exc).__name__ != "CompileError": + raise + return False + return True + + +class BuildExtraLibraries(setuptools.command.build_ext.build_ext): + def finalize_options(self): + # If coverage is enabled then need to keep the .o and .gcno files in a + # non-temporary directory otherwise coverage info not collected. + cppflags = os.getenv('CPPFLAGS') + if cppflags and '--coverage' in cppflags: + self.build_temp = 'build' + + self.distribution.ext_modules[:] = [ + ext + for package in good_packages + for ext in package.get_extensions() + ] + super().finalize_options() + + def add_optimization_flags(self): + """ + Add optional optimization flags to extension. + + This adds flags for LTO and hidden visibility to both compiled + extensions, and to the environment variables so that vendored libraries + will also use them. If the compiler does not support these flags, then + none are added. + """ + + env = os.environ.copy() + if sys.platform == 'win32': + return env + enable_lto = setupext.config.getboolean('libs', 'enable_lto', + fallback=None) + + def prepare_flags(name, enable_lto): + """ + Prepare *FLAGS from the environment. + + If set, return them, and also check whether LTO is disabled in each + one, raising an error if Matplotlib config explicitly enabled LTO. + """ + if name in os.environ: + if '-fno-lto' in os.environ[name]: + if enable_lto is True: + raise ValueError('Configuration enable_lto=True, but ' + '{0} contains -fno-lto'.format(name)) + enable_lto = False + return [os.environ[name]], enable_lto + return [], enable_lto + + _, enable_lto = prepare_flags('CFLAGS', enable_lto) # Only check lto. + cppflags, enable_lto = prepare_flags('CPPFLAGS', enable_lto) + cxxflags, enable_lto = prepare_flags('CXXFLAGS', enable_lto) + ldflags, enable_lto = prepare_flags('LDFLAGS', enable_lto) + + if enable_lto is False: + return env + + if has_flag(self.compiler, '-fvisibility=hidden'): + for ext in self.extensions: + ext.extra_compile_args.append('-fvisibility=hidden') + cppflags.append('-fvisibility=hidden') + if has_flag(self.compiler, '-fvisibility-inlines-hidden'): + for ext in self.extensions: + if self.compiler.detect_language(ext.sources) != 'cpp': + continue + ext.extra_compile_args.append('-fvisibility-inlines-hidden') + cxxflags.append('-fvisibility-inlines-hidden') + ranlib = 'RANLIB' in env + if not ranlib and self.compiler.compiler_type == 'unix': + try: + result = subprocess.run(self.compiler.compiler + + ['--version'], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True) + except Exception: + pass + else: + version = result.stdout.lower() + if 'gcc' in version: + ranlib = shutil.which('gcc-ranlib') + elif 'clang' in version: + if sys.platform == 'darwin': + ranlib = True + else: + ranlib = shutil.which('llvm-ranlib') + if ranlib and has_flag(self.compiler, '-flto'): + for ext in self.extensions: + ext.extra_compile_args.append('-flto') + cppflags.append('-flto') + ldflags.append('-flto') + # Needed so FreeType static library doesn't lose its LTO objects. + if isinstance(ranlib, str): + env['RANLIB'] = ranlib + + env['CPPFLAGS'] = ' '.join(cppflags) + env['CXXFLAGS'] = ' '.join(cxxflags) + env['LDFLAGS'] = ' '.join(ldflags) + + return env + + def build_extensions(self): + if (self.compiler.compiler_type == 'msvc' and + os.environ.get('MPL_DISABLE_FH4')): + # Disable FH4 Exception Handling implementation so that we don't + # require VCRUNTIME140_1.dll. For more details, see: + # https://devblogs.microsoft.com/cppblog/making-cpp-exception-handling-smaller-x64/ + # https://github.com/joerick/cibuildwheel/issues/423#issuecomment-677763904 + for ext in self.extensions: + ext.extra_compile_args.append('/d2FH4-') + + env = self.add_optimization_flags() + for package in good_packages: + package.do_custom_build(env) + # Make sure we don't accidentally use too modern C++ constructs, even + # though modern compilers default to enabling them. Enabling this for + # a single platform is enough; also only do this for C++-only + # extensions as clang refuses to compile C/ObjC with -std=c++11. + if sys.platform != "win32": + for ext in self.distribution.ext_modules[:]: + if not any(src.endswith((".c", ".m")) for src in ext.sources): + ext.extra_compile_args.append("-std=c++11") + return super().build_extensions() + + def build_extension(self, ext): + # When C coverage is enabled, the path to the object file is saved. + # Since we re-use source files in multiple extensions, libgcov will + # complain at runtime that it is trying to save coverage for the same + # object file at different timestamps (since each source is compiled + # again for each extension). Thus, we need to use unique temporary + # build directories to store object files for each extension. + orig_build_temp = self.build_temp + self.build_temp = os.path.join(self.build_temp, ext.name) + try: + super().build_extension(ext) + finally: + self.build_temp = orig_build_temp + + +def update_matplotlibrc(path): + # If packagers want to change the default backend, insert a `#backend: ...` + # line. Otherwise, use the default `##backend: Agg` which has no effect + # even after decommenting, which allows _auto_backend_sentinel to be filled + # in at import time. + template_lines = path.read_text(encoding="utf-8").splitlines(True) + backend_line_idx, = [ # Also asserts that there is a single such line. + idx for idx, line in enumerate(template_lines) + if "#backend:" in line] + template_lines[backend_line_idx] = ( + "#backend: {}\n".format(setupext.options["backend"]) + if setupext.options["backend"] + else "##backend: Agg\n") + path.write_text("".join(template_lines), encoding="utf-8") + + +class BuildPy(setuptools.command.build_py.build_py): + def run(self): + super().run() + if not getattr(self, 'editable_mode', False): + update_matplotlibrc( + Path(self.build_lib, "matplotlib/mpl-data/matplotlibrc")) + + +class Sdist(setuptools.command.sdist.sdist): + def make_release_tree(self, base_dir, files): + super().make_release_tree(base_dir, files) + update_matplotlibrc( + Path(base_dir, "lib/matplotlib/mpl-data/matplotlibrc")) + +# Start with type hint data +# Will be further filled below by the various components. +package_data = {"matplotlib": ["py.typed", "**/*.pyi"]} + +# If the user just queries for information, don't bother figuring out which +# packages to build or install. +if not (any('--' + opt in sys.argv + for opt in Distribution.display_option_names + ['help']) + or 'clean' in sys.argv): + # Go through all of the packages and figure out which ones we are + # going to build/install. + print_raw() + print_raw("Edit mplsetup.cfg to change the build options; " + "suppress output with --quiet.") + print_raw() + print_raw("BUILDING MATPLOTLIB") + + good_packages = [] + for package in mpl_packages: + try: + message = package.check() + except setupext.Skipped as e: + print_status(package.name, "no [{e}]".format(e=e)) + continue + if message is not None: + print_status(package.name, + "yes [{message}]".format(message=message)) + good_packages.append(package) + + print_raw() + + # Now collect all of the information we need to build all of the packages. + for package in good_packages: + # Extension modules only get added in build_ext, as numpy will have + # been installed (as setup_requires) at that point. + data = package.get_package_data() + for key, val in data.items(): + package_data.setdefault(key, []) + package_data[key] = list(set(val + package_data[key])) + +setup( # Finally, pass this all along to setuptools to do the heavy lifting. + name="matplotlib", + description="Python plotting package", + author="John D. Hunter, Michael Droettboom", + author_email="matplotlib-users@python.org", + url="https://matplotlib.org", + download_url="https://matplotlib.org/stable/users/installing/index.html", + project_urls={ + 'Documentation': 'https://matplotlib.org', + 'Source Code': 'https://github.com/matplotlib/matplotlib', + 'Bug Tracker': 'https://github.com/matplotlib/matplotlib/issues', + 'Forum': 'https://discourse.matplotlib.org/', + 'Donate': 'https://numfocus.org/donate-to-matplotlib' + }, + long_description=Path("README.md").read_text(encoding="utf-8"), + long_description_content_type="text/markdown", + license="PSF", + platforms="any", + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Framework :: Matplotlib', + 'Intended Audience :: Science/Research', + 'Intended Audience :: Education', + 'License :: OSI Approved :: Python Software Foundation License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Topic :: Scientific/Engineering :: Visualization', + ], + + package_dir={"": "lib"}, + packages=find_namespace_packages( + where="lib", + exclude=["*baseline_images*", "*tinypages*", "*mpl-data*", "*web_backend*"], + ), + py_modules=["pylab"], + # Dummy extension to trigger build_ext, which will swap it out with + # real extensions that can depend on numpy for the build. + ext_modules=[Extension("", [])], + package_data=package_data, + + python_requires='>={}'.format('.'.join(str(n) for n in py_min_version)), + # When updating the list of dependencies, add an api_changes/development + # entry and also update the following places: + # - lib/matplotlib/__init__.py (matplotlib._check_versions()) + # - requirements/testing/minver.txt + # - doc/devel/dependencies.rst + # - .github/workflows/tests.yml + # - environment.yml + install_requires=[ + "contourpy>=1.0.1", + "cycler>=0.10", + "fonttools>=4.22.0", + "kiwisolver>=1.0.1", + "numpy>=1.21", + "packaging>=20.0", + "pillow>=6.2.0", + "pyparsing>=2.3.1", + "python-dateutil>=2.7", + ] + ( + # Installing from a git checkout that is not producing a wheel. + ["setuptools_scm>=7"] if ( + Path(__file__).with_name(".git").exists() and + os.environ.get("CIBUILDWHEEL", "0") != "1" + ) else [] + ), + extras_require={ + ':python_version<"3.10"': [ + "importlib-resources>=3.2.0", + ], + }, + use_scm_version={ + "version_scheme": "release-branch-semver", + "local_scheme": "node-and-date", + "write_to": "lib/matplotlib/_version.py", + "parentdir_prefix_version": "matplotlib-", + "fallback_version": "0.0+UNKNOWN", + }, + cmdclass={ + "build_ext": BuildExtraLibraries, + "build_py": BuildPy, + "sdist": Sdist, + }, +) diff --git a/testbed/matplotlib__matplotlib/setupext.py b/testbed/matplotlib__matplotlib/setupext.py new file mode 100644 index 0000000000000000000000000000000000000000..9f78d88c87e81bd46bf328c048e84f6bd193d95f --- /dev/null +++ b/testbed/matplotlib__matplotlib/setupext.py @@ -0,0 +1,798 @@ +import configparser +import functools +import hashlib +from io import BytesIO +import logging +import os +from pathlib import Path +import platform +import shlex +import shutil +import subprocess +import sys +import sysconfig +import tarfile +from tempfile import TemporaryDirectory +import textwrap +import urllib.request + +from pybind11.setup_helpers import Pybind11Extension +from setuptools import Distribution, Extension + +_log = logging.getLogger(__name__) + + +def _get_xdg_cache_dir(): + """ + Return the `XDG cache directory`__. + + __ https://specifications.freedesktop.org/basedir-spec/latest/ + """ + cache_dir = os.environ.get('XDG_CACHE_HOME') + if not cache_dir: + cache_dir = os.path.expanduser('~/.cache') + if cache_dir.startswith('~/'): # Expansion failed. + return None + return Path(cache_dir, 'matplotlib') + + +def _get_hash(data): + """Compute the sha256 hash of *data*.""" + hasher = hashlib.sha256() + hasher.update(data) + return hasher.hexdigest() + + +@functools.cache +def _get_ssl_context(): + import certifi + import ssl + return ssl.create_default_context(cafile=certifi.where()) + + +def get_from_cache_or_download(url, sha): + """ + Get bytes from the given url or local cache. + + Parameters + ---------- + url : str + The url to download. + sha : str + The sha256 of the file. + + Returns + ------- + BytesIO + The file loaded into memory. + """ + cache_dir = _get_xdg_cache_dir() + + if cache_dir is not None: # Try to read from cache. + try: + data = (cache_dir / sha).read_bytes() + except OSError: + pass + else: + if _get_hash(data) == sha: + return BytesIO(data) + + # jQueryUI's website blocks direct downloads from urllib.request's + # default User-Agent, but not (for example) wget; so I don't feel too + # bad passing in an empty User-Agent. + with urllib.request.urlopen( + urllib.request.Request(url, headers={"User-Agent": ""}), + context=_get_ssl_context()) as req: + data = req.read() + + file_sha = _get_hash(data) + if file_sha != sha: + raise Exception( + f"The downloaded file does not match the expected sha. {url} was " + f"expected to have {sha} but it had {file_sha}") + + if cache_dir is not None: # Try to cache the downloaded file. + try: + cache_dir.mkdir(parents=True, exist_ok=True) + with open(cache_dir / sha, "xb") as fout: + fout.write(data) + except OSError: + pass + + return BytesIO(data) + + +def get_and_extract_tarball(urls, sha, dirname): + """ + Obtain a tarball (from cache or download) and extract it. + + Parameters + ---------- + urls : list[str] + URLs from which download is attempted (in order of attempt), if the + tarball is not in the cache yet. + sha : str + SHA256 hash of the tarball; used both as a cache key (by + `get_from_cache_or_download`) and to validate a downloaded tarball. + dirname : path-like + Directory where the tarball is extracted. + """ + toplevel = Path("build", dirname) + if not toplevel.exists(): # Download it or load it from cache. + try: + import certifi # noqa + except ImportError as e: + raise ImportError( + f"`certifi` is unavailable ({e}) so unable to download any of " + f"the following: {urls}.") from None + + Path("build").mkdir(exist_ok=True) + for url in urls: + try: + tar_contents = get_from_cache_or_download(url, sha) + break + except Exception: + pass + else: + raise OSError( + f"Failed to download any of the following: {urls}. " + f"Please download one of these urls and extract it into " + f"'build/' at the top-level of the source repository.") + print(f"Extracting {urllib.parse.urlparse(url).path}") + with tarfile.open(fileobj=tar_contents, mode="r:gz") as tgz: + if os.path.commonpath(tgz.getnames()) != dirname: + raise OSError( + f"The downloaded tgz file was expected to have {dirname} " + f"as sole top-level directory, but that is not the case") + tgz.extractall("build") + return toplevel + + +# SHA256 hashes of the FreeType tarballs +_freetype_hashes = { + '2.6.1': + '0a3c7dfbda6da1e8fce29232e8e96d987ababbbf71ebc8c75659e4132c367014', + '2.6.2': + '8da42fc4904e600be4b692555ae1dcbf532897da9c5b9fb5ebd3758c77e5c2d4', + '2.6.3': + '7942096c40ee6fea882bd4207667ad3f24bff568b96b10fd3885e11a7baad9a3', + '2.6.4': + '27f0e38347a1850ad57f84fc4dfed68ba0bc30c96a6fa6138ef84d485dd9a8d7', + '2.6.5': + '3bb24add9b9ec53636a63ea8e867ed978c4f8fdd8f1fa5ccfd41171163d4249a', + '2.7': + '7b657d5f872b0ab56461f3bd310bd1c5ec64619bd15f0d8e08282d494d9cfea4', + '2.7.1': + '162ef25aa64480b1189cdb261228e6c5c44f212aac4b4621e28cf2157efb59f5', + '2.8': + '33a28fabac471891d0523033e99c0005b95e5618dc8ffa7fa47f9dadcacb1c9b', + '2.8.1': + '876711d064a6a1bd74beb18dd37f219af26100f72daaebd2d86cb493d7cd7ec6', + '2.9': + 'bf380e4d7c4f3b5b1c1a7b2bf3abb967bda5e9ab480d0df656e0e08c5019c5e6', + '2.9.1': + 'ec391504e55498adceb30baceebd147a6e963f636eb617424bcfc47a169898ce', + '2.10.0': + '955e17244e9b38adb0c98df66abb50467312e6bb70eac07e49ce6bd1a20e809a', + '2.10.1': + '3a60d391fd579440561bf0e7f31af2222bc610ad6ce4d9d7bd2165bca8669110', + '2.11.1': + 'f8db94d307e9c54961b39a1cc799a67d46681480696ed72ecf78d4473770f09b' +} +# This is the version of FreeType to use when building a local version. It +# must match the value in lib/matplotlib.__init__.py, and the cache path in +# `.circleci/config.yml`. Also update the docs in +# `docs/devel/dependencies.rst`. +TESTING_VERSION_OF_FREETYPE = '2.6.1' +if sys.platform.startswith('win') and platform.machine() == 'ARM64': + # older versions of freetype are not supported for win/arm64 + # Matplotlib tests will not pass + LOCAL_FREETYPE_VERSION = '2.11.1' +else: + LOCAL_FREETYPE_VERSION = TESTING_VERSION_OF_FREETYPE + +LOCAL_FREETYPE_HASH = _freetype_hashes.get(LOCAL_FREETYPE_VERSION, 'unknown') + +# Also update the cache path in `.circleci/config.yml`. +# Also update the docs in `docs/devel/dependencies.rst`. +LOCAL_QHULL_VERSION = '2020.2' +LOCAL_QHULL_HASH = ( + 'b5c2d7eb833278881b952c8a52d20179eab87766b00b865000469a45c1838b7e') + + +# Matplotlib build options, which can be altered using mplsetup.cfg +mplsetup_cfg = os.environ.get('MPLSETUPCFG') or 'mplsetup.cfg' +config = configparser.ConfigParser() +if os.path.exists(mplsetup_cfg): + config.read(mplsetup_cfg) +options = { + 'backend': config.get('rc_options', 'backend', fallback=None), + 'system_freetype': config.getboolean( + 'libs', 'system_freetype', + fallback=sys.platform.startswith(('aix', 'os400')) + ), + 'system_qhull': config.getboolean( + 'libs', 'system_qhull', fallback=sys.platform.startswith('os400') + ), +} + + +if '-q' in sys.argv or '--quiet' in sys.argv: + def print_raw(*args, **kwargs): pass # Suppress our own output. +else: + print_raw = print + + +def print_status(package, status): + initial_indent = "%12s: " % package + indent = ' ' * 18 + print_raw(textwrap.fill(status, width=80, + initial_indent=initial_indent, + subsequent_indent=indent)) + + +@functools.cache # We only need to compute this once. +def get_pkg_config(): + """ + Get path to pkg-config and set up the PKG_CONFIG environment variable. + """ + if sys.platform == 'win32': + return None + pkg_config = os.environ.get('PKG_CONFIG') or 'pkg-config' + if shutil.which(pkg_config) is None: + print( + "IMPORTANT WARNING:\n" + " pkg-config is not installed.\n" + " Matplotlib may not be able to find some of its dependencies.") + return None + pkg_config_path = sysconfig.get_config_var('LIBDIR') + if pkg_config_path is not None: + pkg_config_path = os.path.join(pkg_config_path, 'pkgconfig') + try: + os.environ['PKG_CONFIG_PATH'] += ':' + pkg_config_path + except KeyError: + os.environ['PKG_CONFIG_PATH'] = pkg_config_path + return pkg_config + + +def pkg_config_setup_extension( + ext, package, + atleast_version=None, alt_exec=None, default_libraries=()): + """Add parameters to the given *ext* for the given *package*.""" + + # First, try to get the flags from pkg-config. + + pkg_config = get_pkg_config() + cmd = [pkg_config, package] if pkg_config else alt_exec + if cmd is not None: + try: + if pkg_config and atleast_version: + subprocess.check_call( + [*cmd, f"--atleast-version={atleast_version}"]) + # Use sys.getfilesystemencoding() to allow round-tripping + # when passed back to later subprocess calls; do not use + # locale.getpreferredencoding() which universal_newlines=True + # would do. + cflags = shlex.split( + os.fsdecode(subprocess.check_output([*cmd, "--cflags"]))) + libs = shlex.split( + os.fsdecode(subprocess.check_output([*cmd, "--libs"]))) + except (OSError, subprocess.CalledProcessError): + pass + else: + ext.extra_compile_args.extend(cflags) + ext.extra_link_args.extend(libs) + return + + # If that fails, fall back on the defaults. + + # conda Windows header and library paths. + # https://github.com/conda/conda/issues/2312 re: getting the env dir. + if sys.platform == 'win32': + conda_env_path = (os.getenv('CONDA_PREFIX') # conda >= 4.1 + or os.getenv('CONDA_DEFAULT_ENV')) # conda < 4.1 + if conda_env_path and os.path.isdir(conda_env_path): + conda_env_path = Path(conda_env_path) + ext.include_dirs.append(str(conda_env_path / "Library/include")) + ext.library_dirs.append(str(conda_env_path / "Library/lib")) + + # Default linked libs. + ext.libraries.extend(default_libraries) + + +class Skipped(Exception): + """ + Exception thrown by `SetupPackage.check` to indicate that a package should + be skipped. + """ + + +class SetupPackage: + + def check(self): + """ + If the package should be installed, return an informative string, or + None if no information should be displayed at all. + + If the package should be skipped, raise a `Skipped` exception. + + If a missing build dependency is fatal, call `sys.exit`. + """ + + def get_package_data(self): + """ + Get a package data dictionary to add to the configuration. + These are merged into to the *package_data* list passed to + `setuptools.setup`. + """ + return {} + + def get_extensions(self): + """ + Return or yield a list of C extensions (`distutils.core.Extension` + objects) to add to the configuration. These are added to the + *extensions* list passed to `setuptools.setup`. + """ + return [] + + def do_custom_build(self, env): + """ + If a package needs to do extra custom things, such as building a + third-party library, before building an extension, it should + override this method. + """ + + +class OptionalPackage(SetupPackage): + default_config = True + + def check(self): + """ + Check whether ``mplsetup.cfg`` requests this package to be installed. + + May be overridden by subclasses for additional checks. + """ + if config.getboolean("packages", self.name, + fallback=self.default_config): + return "installing" + else: # Configuration opt-out by user + raise Skipped("skipping due to configuration") + + +class Platform(SetupPackage): + name = "platform" + + def check(self): + return sys.platform + + +class Python(SetupPackage): + name = "python" + + def check(self): + return sys.version + + +def _pkg_data_helper(pkg, subdir): + """Glob "lib/$pkg/$subdir/**/*", returning paths relative to "lib/$pkg".""" + base = Path("lib", pkg) + return [str(path.relative_to(base)) for path in (base / subdir).rglob("*")] + + +class Matplotlib(SetupPackage): + name = "matplotlib" + + def get_package_data(self): + return { + 'matplotlib': [ + 'mpl-data/matplotlibrc', + *_pkg_data_helper('matplotlib', 'mpl-data'), + *_pkg_data_helper('matplotlib', 'backends/web_backend'), + '*.dll', # Only actually matters on Windows. + ], + } + + def get_extensions(self): + # agg + ext = Extension( + "matplotlib.backends._backend_agg", [ + "src/py_converters.cpp", + "src/_backend_agg.cpp", + "src/_backend_agg_wrapper.cpp", + ]) + add_numpy_flags(ext) + add_libagg_flags_and_sources(ext) + FreeType.add_flags(ext) + yield ext + # c_internal_utils + ext = Extension( + "matplotlib._c_internal_utils", ["src/_c_internal_utils.c"], + libraries=({ + "linux": ["dl"], + "win32": ["ole32", "shell32", "user32"], + }.get(sys.platform, []))) + yield ext + # ft2font + ext = Extension( + "matplotlib.ft2font", [ + "src/ft2font.cpp", + "src/ft2font_wrapper.cpp", + "src/py_converters.cpp", + ]) + FreeType.add_flags(ext) + add_numpy_flags(ext) + add_libagg_flags(ext) + yield ext + # image + ext = Extension( + "matplotlib._image", [ + "src/_image_wrapper.cpp", + "src/py_converters.cpp", + ]) + add_numpy_flags(ext) + add_libagg_flags_and_sources(ext) + yield ext + # path + ext = Extension( + "matplotlib._path", [ + "src/py_converters.cpp", + "src/_path_wrapper.cpp", + ]) + add_numpy_flags(ext) + add_libagg_flags_and_sources(ext) + yield ext + # qhull + ext = Extension( + "matplotlib._qhull", ["src/_qhull_wrapper.cpp"], + define_macros=[("MPL_DEVNULL", os.devnull)]) + add_numpy_flags(ext) + Qhull.add_flags(ext) + yield ext + # tkagg + ext = Extension( + "matplotlib.backends._tkagg", [ + "src/_tkagg.cpp", + ], + include_dirs=["src"], + # psapi library needed for finding Tcl/Tk at run time. + libraries={"linux": ["dl"], "win32": ["comctl32", "psapi"], + "cygwin": ["comctl32", "psapi"]}.get(sys.platform, []), + extra_link_args={"win32": ["-mwindows"]}.get(sys.platform, [])) + add_numpy_flags(ext) + add_libagg_flags(ext) + yield ext + # tri + ext = Pybind11Extension( + "matplotlib._tri", [ + "src/tri/_tri.cpp", + "src/tri/_tri_wrapper.cpp", + ], + cxx_std=11) + yield ext + # ttconv + ext = Pybind11Extension( + "matplotlib._ttconv", [ + "src/_ttconv.cpp", + "extern/ttconv/pprdrv_tt.cpp", + "extern/ttconv/pprdrv_tt2.cpp", + "extern/ttconv/ttutil.cpp", + ], + include_dirs=["extern"], + cxx_std=11) + yield ext + + +class Tests(OptionalPackage): + name = "tests" + default_config = False + + def get_package_data(self): + return { + 'matplotlib': [ + *_pkg_data_helper('matplotlib', 'tests/baseline_images'), + *_pkg_data_helper('matplotlib', 'tests/tinypages'), + 'tests/cmr10.pfb', + 'tests/Courier10PitchBT-Bold.pfb', + 'tests/mpltest.ttf', + 'tests/test_*.ipynb', + ], + 'mpl_toolkits': [ + *_pkg_data_helper('mpl_toolkits', + 'axes_grid1/tests/baseline_images'), + *_pkg_data_helper('mpl_toolkits', + 'axisartist/tests/baseline_images'), + *_pkg_data_helper('mpl_toolkits', + 'mplot3d/tests/baseline_images'), + ] + } + + +def add_numpy_flags(ext): + import numpy as np + ext.include_dirs.append(np.get_include()) + ext.define_macros.extend([ + # Ensure that PY_ARRAY_UNIQUE_SYMBOL is uniquely defined for each + # extension. + ('PY_ARRAY_UNIQUE_SYMBOL', + 'MPL_' + ext.name.replace('.', '_') + '_ARRAY_API'), + ('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION'), + # Allow NumPy's printf format specifiers in C++. + ('__STDC_FORMAT_MACROS', 1), + ]) + + +def add_libagg_flags(ext): + # We need a patched Agg not available elsewhere, so always use the vendored + # version. + ext.include_dirs.insert(0, "extern/agg24-svn/include") + + +def add_libagg_flags_and_sources(ext): + # We need a patched Agg not available elsewhere, so always use the vendored + # version. + ext.include_dirs.insert(0, "extern/agg24-svn/include") + agg_sources = [ + "agg_bezier_arc.cpp", + "agg_curves.cpp", + "agg_image_filters.cpp", + "agg_trans_affine.cpp", + "agg_vcgen_contour.cpp", + "agg_vcgen_dash.cpp", + "agg_vcgen_stroke.cpp", + "agg_vpgen_segmentator.cpp", + ] + ext.sources.extend( + os.path.join("extern", "agg24-svn", "src", x) for x in agg_sources) + + +def get_ccompiler(): + """ + Return a new CCompiler instance. + + CCompiler used to be constructible via `distutils.ccompiler.new_compiler`, + but this API was removed as part of the distutils deprecation. Instead, + we trick setuptools into instantiating it by creating a dummy Distribution + with a list of extension modules that claims to be truthy, but is actually + empty, and then running the Distribution's build_ext command. (If using + a plain empty ext_modules, build_ext would early-return without doing + anything.) + """ + + class L(list): + def __bool__(self): + return True + + build_ext = Distribution({"ext_modules": L()}).get_command_obj("build_ext") + build_ext.finalize_options() + build_ext.run() + return build_ext.compiler + + +class FreeType(SetupPackage): + name = "freetype" + + @classmethod + def add_flags(cls, ext): + # checkdep_freetype2.c immediately aborts the compilation either with + # "foo.h: No such file or directory" if the header is not found, or an + # appropriate error message if the header indicates a too-old version. + ext.sources.insert(0, 'src/checkdep_freetype2.c') + if options.get('system_freetype'): + pkg_config_setup_extension( + # FreeType 2.3 has libtool version 9.11.3 as can be checked + # from the tarball. For FreeType>=2.4, there is a conversion + # table in docs/VERSIONS.txt in the FreeType source tree. + ext, 'freetype2', + atleast_version='9.11.3', + alt_exec=['freetype-config'], + default_libraries=['freetype']) + ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'system')) + else: + src_path = Path('build', f'freetype-{LOCAL_FREETYPE_VERSION}') + # Statically link to the locally-built freetype. + ext.include_dirs.insert(0, str(src_path / 'include')) + ext.extra_objects.insert( + 0, str((src_path / 'objs/.libs/libfreetype').with_suffix( + '.lib' if sys.platform == 'win32' else '.a'))) + ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'local')) + if sys.platform == 'darwin': + name = ext.name.split('.')[-1] + ext.extra_link_args.append( + f'-Wl,-exported_symbol,_PyInit_{name}') + + def do_custom_build(self, env): + # We're using a system freetype + if options.get('system_freetype'): + return + + tarball = f'freetype-{LOCAL_FREETYPE_VERSION}.tar.gz' + src_path = get_and_extract_tarball( + urls=[ + (f'https://downloads.sourceforge.net/project/freetype' + f'/freetype2/{LOCAL_FREETYPE_VERSION}/{tarball}'), + (f'https://download.savannah.gnu.org/releases/freetype' + f'/{tarball}'), + (f'https://download.savannah.gnu.org/releases/freetype' + f'/freetype-old/{tarball}') + ], + sha=LOCAL_FREETYPE_HASH, + dirname=f'freetype-{LOCAL_FREETYPE_VERSION}', + ) + + libfreetype = (src_path / "objs/.libs/libfreetype").with_suffix( + ".lib" if sys.platform == "win32" else ".a") + if libfreetype.is_file(): + return # Bail out because we have already built FreeType. + + print(f"Building freetype in {src_path}") + if sys.platform != 'win32': # compilation on non-windows + env = { + **{ + var: value + for var, value in sysconfig.get_config_vars().items() + if var in {"CC", "CFLAGS", "CXX", "CXXFLAGS", "LD", + "LDFLAGS"} + }, + **env, + } + configure_ac = Path(src_path, "builds/unix/configure.ac") + if ((src_path / "autogen.sh").exists() + and not configure_ac.exists()): + print(f"{configure_ac} does not exist. " + f"Using sh autogen.sh to generate.") + subprocess.check_call( + ["sh", "./autogen.sh"], env=env, cwd=src_path) + env["CFLAGS"] = env.get("CFLAGS", "") + " -fPIC" + configure = [ + "./configure", "--with-zlib=no", "--with-bzip2=no", + "--with-png=no", "--with-harfbuzz=no", "--enable-static", + "--disable-shared" + ] + host = sysconfig.get_config_var('HOST_GNU_TYPE') + if host is not None: # May be unset on PyPy. + configure.append(f"--host={host}") + subprocess.check_call(configure, env=env, cwd=src_path) + if 'GNUMAKE' in env: + make = env['GNUMAKE'] + elif 'MAKE' in env: + make = env['MAKE'] + else: + try: + output = subprocess.check_output(['make', '-v'], + stderr=subprocess.DEVNULL) + except subprocess.CalledProcessError: + output = b'' + if b'GNU' not in output and b'makepp' not in output: + make = 'gmake' + else: + make = 'make' + subprocess.check_call([make], env=env, cwd=src_path) + else: # compilation on windows + shutil.rmtree(src_path / "objs", ignore_errors=True) + base_path = Path( + f"build/freetype-{LOCAL_FREETYPE_VERSION}/builds/windows" + ) + vc = 'vc2010' + sln_path = base_path / vc / "freetype.sln" + # https://developercommunity.visualstudio.com/comments/190992/view.html + (sln_path.parent / "Directory.Build.props").write_text( + "" + "" + "" + # WindowsTargetPlatformVersion must be given on a single line. + "$(" + "[Microsoft.Build.Utilities.ToolLocationHelper]" + "::GetLatestSDKTargetPlatformVersion('Windows', '10.0')" + ")" + "" + "", + encoding="utf-8") + # It is not a trivial task to determine PlatformToolset to plug it + # into msbuild command, and Directory.Build.props will not override + # the value in the project file. + # The DefaultPlatformToolset is from Microsoft.Cpp.Default.props + with open(base_path / vc / "freetype.vcxproj", 'r+b') as f: + toolset_repl = b'PlatformToolset>$(DefaultPlatformToolset)<' + vcxproj = f.read().replace(b'PlatformToolset>v100<', + toolset_repl) + assert toolset_repl in vcxproj, ( + 'Upgrading Freetype might break this') + f.seek(0) + f.truncate() + f.write(vcxproj) + + cc = get_ccompiler() + cc.initialize() + # On setuptools versions that use "local" distutils, + # ``cc.spawn(["msbuild", ...])`` no longer manages to locate the + # right executable, even though they are correctly on the PATH, + # because only the env kwarg to Popen() is updated, and not + # os.environ["PATH"]. Instead, use shutil.which to walk the PATH + # and get absolute executable paths. + with TemporaryDirectory() as tmpdir: + dest = Path(tmpdir, "path") + cc.spawn([ + sys.executable, "-c", + "import pathlib, shutil, sys\n" + "dest = pathlib.Path(sys.argv[1])\n" + "dest.write_text(shutil.which('msbuild'))\n", + str(dest), + ]) + msbuild_path = dest.read_text() + msbuild_platform = ( + "ARM64" if platform.machine() == "ARM64" else + "x64" if platform.architecture()[0] == "64bit" else + "Win32") + # Freetype 2.10.0+ support static builds. + msbuild_config = ( + "Release Static" + if [*map(int, LOCAL_FREETYPE_VERSION.split("."))] >= [2, 10] + else "Release" + ) + + cc.spawn([msbuild_path, str(sln_path), + "/t:Clean;Build", + f"/p:Configuration={msbuild_config};" + f"Platform={msbuild_platform}"]) + # Move to the corresponding Unix build path. + libfreetype.parent.mkdir() + # Be robust against change of FreeType version. + lib_paths = Path(src_path / "objs").rglob('freetype*.lib') + # Select FreeType library for required platform + lib_path, = [ + p for p in lib_paths + if msbuild_platform in p.resolve().as_uri() + ] + print(f"Copying {lib_path} to {libfreetype}") + shutil.copy2(lib_path, libfreetype) + + +class Qhull(SetupPackage): + name = "qhull" + _extensions_to_update = [] + + @classmethod + def add_flags(cls, ext): + if options.get("system_qhull"): + ext.libraries.append("qhull_r") + else: + cls._extensions_to_update.append(ext) + + def do_custom_build(self, env): + if options.get('system_qhull'): + return + + toplevel = get_and_extract_tarball( + urls=["http://www.qhull.org/download/qhull-2020-src-8.0.2.tgz"], + sha=LOCAL_QHULL_HASH, + dirname=f"qhull-{LOCAL_QHULL_VERSION}", + ) + shutil.copyfile(toplevel / "COPYING.txt", "LICENSE/LICENSE_QHULL") + + for ext in self._extensions_to_update: + qhull_path = Path(f'build/qhull-{LOCAL_QHULL_VERSION}/src') + ext.include_dirs.insert(0, str(qhull_path)) + ext.sources.extend( + map(str, sorted(qhull_path.glob('libqhull_r/*.c')))) + if sysconfig.get_config_var("LIBM") == "-lm": + ext.libraries.extend("m") + + +class BackendMacOSX(OptionalPackage): + name = 'macosx' + + def check(self): + if sys.platform != 'darwin': + raise Skipped("Mac OS-X only") + return super().check() + + def get_extensions(self): + ext = Extension( + 'matplotlib.backends._macosx', [ + 'src/_macosx.m' + ]) + ext.extra_compile_args.extend(['-Werror']) + ext.extra_link_args.extend(['-framework', 'Cocoa']) + if platform.python_implementation().lower() == 'pypy': + ext.extra_compile_args.append('-DPYPY=1') + yield ext diff --git a/testbed/matplotlib__matplotlib/tox.ini b/testbed/matplotlib__matplotlib/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..fc84792691609a234e51f3cc764a115811d200b5 --- /dev/null +++ b/testbed/matplotlib__matplotlib/tox.ini @@ -0,0 +1,27 @@ +# Tox (http://tox.testrun.org/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +envlist = py38, py39, py310 + +[testenv] +changedir = /tmp +setenv = + MPLCONFIGDIR={envtmpdir}/.matplotlib + PIP_USER = 0 + PIP_ISOLATED = 1 +usedevelop = True +commands = + pytest --pyargs matplotlib {posargs} +deps = + pytest + +[testenv:pytz] +changedir = /tmp +commands = + pytest -m pytz {toxinidir} +deps = + pytest + pytz diff --git a/testbed/minio__minio-py/.github/workflows/pythonpackage-linux.yml b/testbed/minio__minio-py/.github/workflows/pythonpackage-linux.yml new file mode 100644 index 0000000000000000000000000000000000000000..b32210bc8fb8b5ce8e42d43c6536074dd837af41 --- /dev/null +++ b/testbed/minio__minio-py/.github/workflows/pythonpackage-linux.yml @@ -0,0 +1,56 @@ +name: Python package + +on: + pull_request: + branches: + - master + push: + branches: + - master + +jobs: + build: + name: Test on python ${{ matrix.python-version }} and ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + max-parallel: 3 + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [ubuntu-latest] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip setuptools + pip install urllib3 certifi pytz pyflakes faker nose + - name: Run check + run: | + export PATH=${HOME}/.local/bin:${PATH} + make check + - name: Test with nosetests + run: | + pyflakes minio/*.py || true + python setup.py install + python setup.py nosetests + - name: Test with functional tests + env: + MINT_MODE: full + SERVER_ENDPOINT: localhost:9000 + ACCESS_KEY: minio + SECRET_KEY: minio123 + ENABLE_HTTPS: 1 + MINIO_ACCESS_KEY: minio + MINIO_SECRET_KEY: minio123 + SSL_CERT_FILE: /tmp/minio-config/certs/public.crt + run: | + wget --quiet -O /tmp/minio https://dl.min.io/server/minio/release/linux-amd64/minio + chmod +x /tmp/minio + mkdir -p /tmp/minio-config/certs/ + cp tests/certs/* /tmp/minio-config/certs/ + /tmp/minio -C /tmp/minio-config server /tmp/fs{1...4} & + python tests/functional/tests.py diff --git a/testbed/minio__minio-py/.github/workflows/pythonpackage-windows.yml b/testbed/minio__minio-py/.github/workflows/pythonpackage-windows.yml new file mode 100644 index 0000000000000000000000000000000000000000..4b9cdc4a67beab7354c2635235c80137422127d4 --- /dev/null +++ b/testbed/minio__minio-py/.github/workflows/pythonpackage-windows.yml @@ -0,0 +1,52 @@ +name: Python package + +on: + pull_request: + branches: + - master + push: + branches: + - master + +jobs: + build: + name: Test on python ${{ matrix.python-version }} and ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + max-parallel: 3 + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [windows-latest] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip setuptools + pip install urllib3 certifi pytz pyflakes faker nose + - name: Test with nosetests + run: | + $ErrorActionPreference = 'continue' + pyflakes minio/*.py + python setup.py install + python setup.py nosetests + - name: Test with functional tests + env: + MINT_MODE: full + SERVER_ENDPOINT: localhost:9000 + ACCESS_KEY: minio + SECRET_KEY: minio123 + ENABLE_HTTPS: 1 + MINIO_ACCESS_KEY: minio + MINIO_SECRET_KEY: minio123 + run: | + New-Item -ItemType Directory -Path "$env:temp/minio-config/certs/" + Copy-Item -Path tests\certs\* -Destination "$env:temp/minio-config/certs/" + Invoke-WebRequest -Uri https://dl.minio.io/server/minio/release/windows-amd64/minio.exe -OutFile $HOME/minio.exe + Start-Process -NoNewWindow -FilePath "$HOME/minio.exe" -ArgumentList "-C", "$env:temp/minio-config", "server", "$env:temp/fs{1...4}" + $env:SSL_CERT_FILE = "$env:temp/minio-config/certs/public.crt" + python tests/functional/tests.py diff --git a/testbed/minio__minio-py/.gitignore b/testbed/minio__minio-py/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7eaa52982be7962d017c1d3d8dc708775c76fc32 --- /dev/null +++ b/testbed/minio__minio-py/.gitignore @@ -0,0 +1,28 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg +*~ +.#* +.vscode +#* diff --git a/testbed/minio__minio-py/CNAME b/testbed/minio__minio-py/CNAME new file mode 100644 index 0000000000000000000000000000000000000000..e3775f9e95372f728a4d9c258099b3c76fb6df11 --- /dev/null +++ b/testbed/minio__minio-py/CNAME @@ -0,0 +1 @@ +minio-py.min.io \ No newline at end of file diff --git a/testbed/minio__minio-py/CONTRIBUTING.md b/testbed/minio__minio-py/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..3c1fe44d842d0bb542d2ab147da05e31ffc4d2c8 --- /dev/null +++ b/testbed/minio__minio-py/CONTRIBUTING.md @@ -0,0 +1,20 @@ +### Setup your minio-py Github Repository +Fork [minio-py upstream](https://github.com/minio/minio-py/fork) source repository to your own personal repository. + +```sh +$ git clone https://github.com/$USER_ID/minio-py +$ cd minio-py +$ python setup.py install +... +``` + +### Developer Guidelines + +``minio-py`` welcomes your contribution. To make the process as seamless as possible, we ask for the following: + +* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes. + - Fork it + - Create your feature branch (git checkout -b my-new-feature) + - Commit your changes (git commit -am 'Add some feature') + - Push to the branch (git push origin my-new-feature) + - Create new Pull Request diff --git a/testbed/minio__minio-py/LICENSE b/testbed/minio__minio-py/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8f71f43fee3f78649d238238cbde51e6d7055c82 --- /dev/null +++ b/testbed/minio__minio-py/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/testbed/minio__minio-py/MAINTAINERS.md b/testbed/minio__minio-py/MAINTAINERS.md new file mode 100644 index 0000000000000000000000000000000000000000..cdaae45daa5b81ceb95aadb8ab315e6f5b0fb242 --- /dev/null +++ b/testbed/minio__minio-py/MAINTAINERS.md @@ -0,0 +1,81 @@ +# For maintainers only + +## Responsibilities +Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522) + +### Setup your minio-py Github Repository +Fork [minio-py upstream](https://github.com/minio/minio-py/fork) source repository to your own personal repository. +```sh +$ git clone git@github.com:minio/minio-py +$ cd minio-py +$ pip install urllib3 certifi pytz pyflakes faker twine +``` + +### Modify package version +```sh +$ cat minio/__init__.py +... +... +__version__ = '2.2.5' +... +... + +``` + +### Build and verify +Run `./tests/unit_test.sh` and `./tests/functional_test.sh` to verify the SDK. +```sh +$ ./tests/unit_test.sh +$ ./tests/functional_test.sh all +$ python setup.py sdist bdist bdist_wheel +``` + +### Publishing new packages + +#### Setup your pypirc +Create a new `pypirc` + +```sh +$ cat >> $HOME/.pypirc << EOF +[distutils] +index-servers = + pypi + +[pypi] +username:minio +password:**REDACTED** +EOF + +``` + +#### Sign +Sign the release artifacts, this step requires you to have access to MinIO's trusted private key. +```sh +$ export GNUPGHOME=/media/${USER}/minio/trusted +$ gpg --detach-sign -a dist/minio-2.2.5.tar.gz +$ gpg --detach-sign -a dist/minio-2.2.5.linux-x86_64.tar.gz +$ gpg --detach-sign -a dist/minio-2.2.5-py2.py3-none-any.whl +``` + +#### Upload to pypi +Upload the signed release artifacts, please install twine v1.8.0+ for following steps to work properly. +```sh +$ twine upload dist/* +``` + +### Tag +Tag and sign your release commit, additionally this step requires you to have access to MinIO's trusted private key. +``` +$ export GNUPGHOME=/media/${USER}/minio/trusted +$ git tag -s 2.2.5 +$ git push +$ git push --tags +``` + +### Announce +Announce new release by adding release notes at https://github.com/minio/minio-py/releases from `trusted@min.io` account. Release notes requires two sections `highlights` and `changelog`. Highlights is a bulleted list of salient features in this release and Changelog contains list of all commits since the last release. + +To generate `changelog` +```sh +git log --no-color --pretty=format:'-%d %s (%cr) <%an>' .. +``` diff --git a/testbed/minio__minio-py/MANIFEST.in b/testbed/minio__minio-py/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..bf718a1c4ff62f8ee16c0d4447b75178021c7a87 --- /dev/null +++ b/testbed/minio__minio-py/MANIFEST.in @@ -0,0 +1,10 @@ +include LICENSE README* +recursive-include docs *.md +recursive-include examples *.py +recursive-include tests *.py *.sh *.crt *.key *.sample *.empty + +prune .github +prune Makefile +prune pylintrc +prune CONTRIBUTING.md +prune MAINTAINERS.md diff --git a/testbed/minio__minio-py/Makefile b/testbed/minio__minio-py/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..75f512240dd78ea95824f84dee1b32f6bf5acce0 --- /dev/null +++ b/testbed/minio__minio-py/Makefile @@ -0,0 +1,31 @@ +.PHONY: examples tests publish + +check: + @pip install --user --upgrade pylint + @if python --version | grep -qi 'python 3'; then pylint --reports=no --score=no --disable=R0401 minio/*py; fi + @if python --version | grep -qi 'python 3'; then pylint --reports=no --score=no minio/credentials minio/select tests/functional; fi + + @isort --diff --recursive . + + @pip install --user --upgrade autopep8 + @autopep8 --diff --exit-code *.py + @find minio -name "*.py" -exec autopep8 --diff --exit-code {} + + @find tests -name "*.py" -exec autopep8 --diff --exit-code {} + + @find examples -name "*.py" -exec autopep8 --diff --exit-code {} + + +apply: + @pip install --user --upgrade pylint + @isort --recursive . + + @pip install --user --upgrade autopep8 + @autopep8 --in-place *.py + @find minio -name "*.py" -exec autopep8 --in-place {} + + @find tests -name "*.py" -exec autopep8 --in-place {} + + @find examples -name "*.py" -exec autopep8 --in-place {} + + +publish: + python setup.py register + python setup.py sdist bdist bdist_wheel upload + +tests: + python setup.py nosetests diff --git a/testbed/minio__minio-py/README.md b/testbed/minio__minio-py/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9068807fdb110d22797f818c29eeaaaa96d9537 --- /dev/null +++ b/testbed/minio__minio-py/README.md @@ -0,0 +1,211 @@ +# MinIO Python Library for Amazon S3 Compatible Cloud Storage [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +The MinIO Python Client SDK provides simple APIs to access any Amazon S3 compatible object storage server. + +This quickstart guide will show you how to install the client SDK and execute an example python program. For a complete list of APIs and examples, please take a look at the [Python Client API Reference](https://docs.min.io/docs/python-client-api-reference) documentation. + +This document assumes that you have a working [Python](https://www.python.org/downloads/) setup in place. + +## Minimum Requirements + +- Python 3.6 or higher + +## Download from pip + +```sh +pip install minio +``` + +## Download from pip3 + +```sh +pip3 install minio +``` + +## Download from source + +```sh +git clone https://github.com/minio/minio-py +cd minio-py +python setup.py install +``` + +## Initialize MinIO Client + +You need four items in order to connect to MinIO object storage server. + +| Params | Description | +| :------- | :---- | +| endpoint | URL to object storage service. | +| access_key| Access key is like user ID that uniquely identifies your account. | +| secret_key| Secret key is the password to your account. | +|secure|Set this value to 'True' to enable secure (HTTPS) access.| + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True) +``` + +**NOTE on concurrent usage:** The `Minio` object is thread safe when using the Python `threading` library. Specifically, it is **NOT** safe to share it between multiple processes, for example when using `multiprocessing.Pool`. The solution is simply to create a new `Minio` object in each process, and not share it between processes. + + +## Quick Start Example - File Uploader +This example program connects to a MinIO object storage server, makes a bucket on the server and then uploads a file to the bucket. + +We will use the MinIO server running at [https://play.min.io](https://play.min.io) in this example. Feel free to use this service for testing and development. Access credentials shown in this example are open to the public. + +#### file-uploader.py + +```py +# Import MinIO library. +from minio import Minio +from minio.error import (ResponseError, BucketAlreadyOwnedByYou, + BucketAlreadyExists) + +# Initialize minioClient with an endpoint and access/secret keys. +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True) + +# Make a bucket with the make_bucket API call. +try: + minioClient.make_bucket("maylogs", location="us-east-1") +except BucketAlreadyOwnedByYou as err: + pass +except BucketAlreadyExists as err: + pass +except ResponseError as err: + raise + +# Put an object 'pumaserver_debug.log' with contents from 'pumaserver_debug.log'. +try: + minioClient.fput_object('maylogs', 'pumaserver_debug.log', '/tmp/pumaserver_debug.log') +except ResponseError as err: + print(err) + +``` + +#### Run file-uploader + +```bash +python file_uploader.py + +mc ls play/maylogs/ +[2016-05-27 16:41:37 PDT] 12MiB pumaserver_debug.log +``` + +## API Reference + +The full API Reference is available here. +* [Complete API Reference](https://docs.min.io/docs/python-client-api-reference) + +### API Reference : Bucket Operations + +* [`make_bucket`](https://docs.min.io/docs/python-client-api-reference#make_bucket) +* [`list_buckets`](https://docs.min.io/docs/python-client-api-reference#list_buckets) +* [`bucket_exists`](https://docs.min.io/docs/python-client-api-reference#bucket_exists) +* [`remove_bucket`](https://docs.min.io/docs/python-client-api-reference#remove_bucket) +* [`list_objects`](https://docs.min.io/docs/python-client-api-reference#list_objects) + +### API Reference : Bucket policy Operations + +* [`get_bucket_policy`](https://docs.min.io/docs/python-client-api-reference#get_bucket_policy) +* [`set_bucket_policy`](https://docs.min.io/docs/python-client-api-reference#set_bucket_policy) + +### API Reference : Bucket notification Operations + +* [`set_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#set_bucket_notification) +* [`get_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#get_bucket_notification) +* [`remove_all_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#remove_all_bucket_notification) +* [`listen_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#listen_bucket_notification) + +### API Reference : Default bucket encryption configuration Operations + +* [`put_bucket_encryption`](https://docs.min.io/docs/python-client-api-reference#put_bucket_encryption) +* [`get_bucket_encryption`](https://docs.min.io/docs/python-client-api-reference#get_bucket_encryption) +* [`delete_bucket_encryption`](https://docs.min.io/docs/python-client-api-reference#delete_bucket_encryption) + +### API Reference : File Object Operations + +* [`fput_object`](https://docs.min.io/docs/python-client-api-reference#fput_object) +* [`fget_object`](https://docs.min.io/docs/python-client-api-reference#fget_object) + +### API Reference : Object Operations + +* [`get_object`](https://docs.min.io/docs/python-client-api-reference#get_object) +* [`put_object`](https://docs.min.io/docs/python-client-api-reference#put_object) +* [`stat_object`](https://docs.min.io/docs/python-client-api-reference#stat_object) +* [`copy_object`](https://docs.min.io/docs/python-client-api-reference#copy_object) +* [`remove_object`](https://docs.min.io/docs/python-client-api-reference#remove_object) +* [`remove_objects`](https://docs.min.io/docs/python-client-api-reference#remove_objects) + +### API Reference : Presigned Operations + +* [`presigned_get_object`](https://docs.min.io/docs/python-client-api-reference#presigned_get_object) +* [`presigned_put_object`](https://docs.min.io/docs/python-client-api-reference#presigned_put_object) +* [`presigned_post_policy`](https://docs.min.io/docs/python-client-api-reference#presigned_post_policy) + +## Full Examples + +#### Full Examples : Bucket Operations + +* [make_bucket.py](https://github.com/minio/minio-py/blob/master/examples/make_bucket.py) +* [list_buckets.py](https://github.com/minio/minio-py/blob/master/examples/list_buckets.py) +* [bucket_exists.py](https://github.com/minio/minio-py/blob/master/examples/bucket_exists.py) +* [list_objects.py](https://github.com/minio/minio-py/blob/master/examples/list_objects.py) +* [remove_bucket.py](https://github.com/minio/minio-py/blob/master/examples/remove_bucket.py) + +#### Full Examples : Bucket policy Operations + +* [set_bucket_policy.py](https://github.com/minio/minio-py/blob/master/examples/set_bucket_policy.py) +* [get_bucket_policy.py](https://github.com/minio/minio-py/blob/master/examples/get_bucket_policy.py) + +#### Full Examples: Bucket notification Operations + +* [set_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/set_bucket_notification.py) +* [get_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/get_bucket_notification.py) +* [remove_all_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/remove_all_bucket_notification.py) +* [listen_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/listen_notification.py) + +#### Full Examples: Default bucket encryption configuration Operations + +* [put_bucket_encryption.py](https://github.com/minio/minio-py/blob/master/examples/put_bucket_encryption.py) +* [get_bucket_encryption.py](https://github.com/minio/minio-py/blob/master/examples/get_bucket_encryption.py) +* [delete_bucket_encryption.py](https://github.com/minio/minio-py/blob/master/examples/delete_bucket_encryption.py) + +#### Full Examples : File Object Operations + +* [fput_object.py](https://github.com/minio/minio-py/blob/master/examples/fput_object.py) +* [fget_object.py](https://github.com/minio/minio-py/blob/master/examples/fget_object.py) + +#### Full Examples : Object Operations + +* [get_object.py](https://github.com/minio/minio-py/blob/master/examples/get_object.py) +* [put_object.py](https://github.com/minio/minio-py/blob/master/examples/put_object.py) +* [stat_object.py](https://github.com/minio/minio-py/blob/master/examples/stat_object.py) +* [copy_object.py](https://github.com/minio/minio-py/blob/master/examples/copy_object.py) +* [remove_object.py](https://github.com/minio/minio-py/blob/master/examples/remove_object.py) +* [remove_objects.py](https://github.com/minio/minio-py/blob/master/examples/remove_objects.py) + +#### Full Examples : Presigned Operations + +* [presigned_get_object.py](https://github.com/minio/minio-py/blob/master/examples/presigned_get_object.py) +* [presigned_put_object.py](https://github.com/minio/minio-py/blob/master/examples/presigned_put_object.py) +* [presigned_post_policy.py](https://github.com/minio/minio-py/blob/master/examples/presigned_post_policy.py) + +## Explore Further + +* [Complete Documentation](https://docs.min.io) +* [MinIO Python SDK API Reference](https://docs.min.io/docs/python-client-api-reference) + +## Contribute + +[Contributors Guide](https://github.com/minio/minio-py/blob/master/CONTRIBUTING.md) + +[![PYPI](https://img.shields.io/pypi/v/minio.svg)](https://pypi.python.org/pypi/minio) diff --git a/testbed/minio__minio-py/README_zh_CN.md b/testbed/minio__minio-py/README_zh_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..2cf81332a474bf88afab99a05d9540a771f24065 --- /dev/null +++ b/testbed/minio__minio-py/README_zh_CN.md @@ -0,0 +1,198 @@ +# 适用于与Amazon S3兼容的云存储的MinIO Python Library [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +MinIO Python Client SDK提供简单的API来访问任何与Amazon S3兼容的对象存储服务。 + +本文我们将学习如何安装MinIO client SDK,并运行一个python的示例程序。对于完整的API以及示例,请参考[Python Client API Reference](https://docs.min.io/docs/python-client-api-reference)。 + +本文假设你已经有一个可运行的 [Python](https://www.python.org/downloads/)开发环境。 + +## 最低要求 + +- Python 3.4或更高版本 + +## 使用pip安装 + +```sh +pip install minio +``` + +## 使用源码安装 + +```sh +git clone https://github.com/minio/minio-py +cd minio-py +python setup.py install +``` + +## 初始化MinIO Client + +MinIO client需要以下4个参数来连接MinIO对象存储服务。 + +| 参数 | 描述 | +| :------- | :---- | +| endpoint | 对象存储服务的URL。 | +| access_key| Access key是唯一标识你的账户的用户ID。 | +| secret_key| Secret key是你账户的密码。 | +|secure| true代表使用HTTPS。 | + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True) +``` + + +## 示例-文件上传 +本示例连接到一个MinIO对象存储服务,创建一个存储桶并上传一个文件到存储桶中。 + +我们在本示例中使用运行在 [https://play.min.io](https://play.min.io) 上的MinIO服务,你可以用这个服务来开发和测试。示例中的访问凭据是公开的。 + +#### file-uploader.py + +```py +# 引入MinIO包。 +from minio import Minio +from minio.error import (ResponseError, BucketAlreadyOwnedByYou, + BucketAlreadyExists) + +# 使用endpoint、access key和secret key来初始化minioClient对象。 +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True) + +# 调用make_bucket来创建一个存储桶。 +try: + minioClient.make_bucket("maylogs", location="us-east-1") +except BucketAlreadyOwnedByYou as err: + pass +except BucketAlreadyExists as err: + pass +except ResponseError as err: + raise +else: + try: + minioClient.fput_object('maylogs', 'pumaserver_debug.log', '/tmp/pumaserver_debug.log') + except ResponseError as err: + print(err) +``` + +#### Run file-uploader + +```bash +python file_uploader.py + +mc ls play/maylogs/ +[2016-05-27 16:41:37 PDT] 12MiB pumaserver_debug.log +``` + +## API文档 + +完整的API文档在这里。 +* [完整API文档](https://docs.min.io/docs/python-client-api-reference) + +### API文档 : 操作存储桶 + +* [`make_bucket`](https://docs.min.io/docs/python-client-api-reference#make_bucket) +* [`list_buckets`](https://docs.min.io/docs/python-client-api-reference#list_buckets) +* [`bucket_exists`](https://docs.min.io/docs/python-client-api-reference#bucket_exists) +* [`remove_bucket`](https://docs.min.io/docs/python-client-api-reference#remove_bucket) +* [`list_objects`](https://docs.min.io/docs/python-client-api-reference#list_objects) +* [`list_objects_v2`](https://docs.min.io/docs/python-client-api-reference#list_objects_v2) +* [`list_incomplete_uploads`](https://docs.min.io/docs/python-client-api-reference#list_incomplete_uploads) + +### API文档 : 存储桶策略 + +* [`get_bucket_policy`](https://docs.min.io/docs/python-client-api-reference#get_bucket_policy) +* [`set_bucket_policy`](https://docs.min.io/docs/python-client-api-reference#set_bucket_policy) + +### API文档 : 存储桶通知 + +* [`set_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#set_bucket_notification) +* [`get_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#get_bucket_notification) +* [`remove_all_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#remove_all_bucket_notification) +* [`listen_bucket_notification`](https://docs.min.io/docs/python-client-api-reference#listen_bucket_notification) + +### API文档 : 操作文件对象 + +* [`fput_object`](https://docs.min.io/docs/python-client-api-reference#fput_object) +* [`fget_object`](https://docs.min.io/docs/python-client-api-reference#fget_object) + +### API文档 : 操作对象 + +* [`get_object`](https://docs.min.io/docs/python-client-api-reference#get_object) +* [`put_object`](https://docs.min.io/docs/python-client-api-reference#put_object) +* [`stat_object`](https://docs.min.io/docs/python-client-api-reference#stat_object) +* [`copy_object`](https://docs.min.io/docs/python-client-api-reference#copy_object) +* [`get_partial_object`](https://docs.min.io/docs/python-client-api-reference#get_partial_object) +* [`remove_object`](https://docs.min.io/docs/python-client-api-reference#remove_object) +* [`remove_objects`](https://docs.min.io/docs/python-client-api-reference#remove_objects) +* [`remove_incomplete_upload`](https://docs.min.io/docs/python-client-api-reference#remove_incomplete_upload) + +### API文档 : Presigned操作 + +* [`presigned_get_object`](https://docs.min.io/docs/python-client-api-reference#presigned_get_object) +* [`presigned_put_object`](https://docs.min.io/docs/python-client-api-reference#presigned_put_object) +* [`presigned_post_policy`](https://docs.min.io/docs/python-client-api-reference#presigned_post_policy) + +## 完整示例 + +#### 完整示例 : 操作存储桶 + +* [make_bucket.py](https://github.com/minio/minio-py/blob/master/examples/make_bucket.py) +* [list_buckets.py](https://github.com/minio/minio-py/blob/master/examples/list_buckets.py) +* [bucket_exists.py](https://github.com/minio/minio-py/blob/master/examples/bucket_exists.py) +* [list_objects.py](https://github.com/minio/minio-py/blob/master/examples/list_objects.py) +* [remove_bucket.py](https://github.com/minio/minio-py/blob/master/examples/remove_bucket.py) +* [list_incomplete_uploads.py](https://github.com/minio/minio-py/blob/master/examples/list_incomplete_uploads.py) + +#### 完整示例 : 存储桶策略 + +* [set_bucket_policy.py](https://github.com/minio/minio-py/blob/master/examples/set_bucket_policy.py) +* [get_bucket_policy.py](https://github.com/minio/minio-py/blob/master/examples/get_bucket_policy.py) + +#### 完整示例 : 存储桶通知 + +* [set_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/set_bucket_notification.py) +* [get_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/get_bucket_notification.py) +* [remove_all_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/remove_all_bucket_notification.py) +* [listen_bucket_notification.py](https://github.com/minio/minio-py/blob/master/examples/listen_notification.py) + +#### 完整示例 : 操作文件对象 + +* [fput_object.py](https://github.com/minio/minio-py/blob/master/examples/fput_object.py) +* [fget_object.py](https://github.com/minio/minio-py/blob/master/examples/fget_object.py) + +#### 完整示例 : 操作对象 + +* [get_object.py](https://github.com/minio/minio-py/blob/master/examples/get_object.py) +* [put_object.py](https://github.com/minio/minio-py/blob/master/examples/put_object.py) +* [stat_object.py](https://github.com/minio/minio-py/blob/master/examples/stat_object.py) +* [copy_object.py](https://github.com/minio/minio-py/blob/master/examples/copy_object.py) +* [get_partial_object.py](https://github.com/minio/minio-py/blob/master/examples/get_partial_object.py) +* [remove_object.py](https://github.com/minio/minio-py/blob/master/examples/remove_object.py) +* [remove_objects.py](https://github.com/minio/minio-py/blob/master/examples/remove_objects.py) +* [remove_incomplete_upload.py](https://github.com/minio/minio-py/blob/master/examples/remove_incomplete_upload.py) + +#### 完整示例 : Presigned操作 + +* [presigned_get_object.py](https://github.com/minio/minio-py/blob/master/examples/presigned_get_object.py) +* [presigned_put_object.py](https://github.com/minio/minio-py/blob/master/examples/presigned_put_object.py) +* [presigned_post_policy.py](https://github.com/minio/minio-py/blob/master/examples/presigned_post_policy.py) + +## 了解更多 + +* [完整文档](https://docs.min.io) +* [MinIO Python SDK API文档](https://docs.min.io/docs/python-client-api-reference) + +## 贡献 + +[贡献指南](https://github.com/minio/minio-py/blob/master/docs/zh_CN/CONTRIBUTING.md) + +[![PYPI](https://img.shields.io/pypi/v/minio.svg)](https://pypi.python.org/pypi/minio) +[![Build Status](https://travis-ci.org/minio/minio-py.svg)](https://travis-ci.org/minio/minio-py) +[![Build status](https://ci.appveyor.com/api/projects/status/1d05e6nvxcelmrak?svg=true)](https://ci.appveyor.com/project/harshavardhana/minio-py) diff --git a/testbed/minio__minio-py/docs/API.md b/testbed/minio__minio-py/docs/API.md new file mode 100644 index 0000000000000000000000000000000000000000..5a6da598e96a64d4bab83104e5b88273fff1529e --- /dev/null +++ b/testbed/minio__minio-py/docs/API.md @@ -0,0 +1,1240 @@ +# Python Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## Initialize MinIO Client object. + +## MinIO + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio( + 'play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True, +) +``` + +## AWS S3 + +```py +from minio import Minio +from minio.error import ResponseError + +s3Client = Minio( + 's3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY', + secure=True, +) +``` + +| Bucket operations | Object operations | Presigned operations | Bucket policy/notification/encryption operations | +|:----------------------------------------------------------|:--------------------------------------------------|:--------------------------------------------------|:--------------------------------------------------------------------| +| [`make_bucket`](#make_bucket) | [`get_object`](#get_object) | [`presigned_get_object`](#presigned_get_object) | [`get_bucket_policy`](#get_bucket_policy) | +| [`list_buckets`](#list_buckets) | [`put_object`](#put_object) | [`presigned_put_object`](#presigned_put_object) | [`set_bucket_policy`](#set_bucket_policy) | +| [`bucket_exists`](#bucket_exists) | [`copy_object`](#copy_object) | [`presigned_post_policy`](#presigned_post_policy) | [`delete_bucket_policy`](#delete_bucket_policy) | +| [`remove_bucket`](#remove_bucket) | [`stat_object`](#stat_object) | | [`get_bucket_notification`](#get_bucket_notification) | +| [`list_objects`](#list_objects) | [`remove_object`](#remove_object) | | [`set_bucket_notification`](#set_bucket_notification) | +| [`get_bucket_versioning`](#get_bucket_versioning) | [`remove_objects`](#remove_objects) | | [`remove_all_bucket_notification`](#remove_all_bucket_notification) | +| [`set_bucket_versioning`](#set_bucket_versioning) | [`fput_object`](#fput_object) | | [`listen_bucket_notification`](#listen_bucket_notification) | +| [`delete_bucket_replication`](#delete_bucket_replication) | [`fget_object`](#fget_object) | | [`get_bucket_encryption`](#get_bucket_encryption) | +| [`get_bucket_replication`](#get_bucket_replication) | [`select_object_content`](#select_object_content) | | [`remove_all_bucket_notification`](#remove_all_bucket_notification) | +| [`set_bucket_replication`](#set_bucket_replication) | | | [`put_bucket_encryption`](#put_bucket_encryption) | +| [`delete_bucket_lifecycle`](#delete_bucket_lifecycle) | | | [`delete_bucket_encryption`](#delete_bucket_encryption) | +| [`get_bucket_lifecycle`](#get_bucket_lifecycle) | | | | +| [`set_bucket_lifecycle`](#set_bucket_lifecycle) | | | | + +## 1. Constructor + + + +### Minio(endpoint, access_key=None, secret_key=None, session_token=None, secure=True, region=None, http_client=None, credentials=None) +| | +|---------------------------------------------------------------------------------------------------------------------------------------| +| `Minio(endpoint, access_key=None, secret_key=None, session_token=None, secure=True, region=None, http_client=None, credentials=None)` | +| Initializes a new client object. | + +__Parameters__ + +| Param | Type | Description | +|:----------------|:----------------------------------|:---------------------------------------------------------------------------------| +| `endpoint` | _str_ | Hostname of a S3 service. | +| `access_key` | _str_ | (Optional) Access key (aka user ID) of your account in S3 service. | +| `secret_key` | _str_ | (Optional) Secret Key (aka password) of your account in S3 service. | +| `session_token` | _str_ | (Optional) Session token of your account in S3 service. | +| `secure` | _bool_ | (Optional) Flag to indicate to use secure (TLS) connection to S3 service or not. | +| `region` | _str_ | (Optional) Region name of buckets in S3 service. | +| `http_client` | _urllib3.poolmanager.PoolManager_ | (Optional) Customized HTTP client. | +| `credentials` | _minio.credentials.Credentials_ | (Optional) Credentials of your account in S3 service. | + + +**NOTE on concurrent usage:** The `Minio` object is thread safe when using the Python `threading` library. Specifically, it is **NOT** safe to share it between multiple processes, for example when using `multiprocessing.Pool`. The solution is simply to create a new `Minio` object in each process, and not share it between processes. + +__Example__ + +### MinIO + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio( + 'play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', +) +``` + +> NOTE: If there is a corporate proxy, specify a custom httpClient using *urllib3.ProxyManager* as shown below: + +```py +from minio import Minio +from minio.error import ResponseError +import urllib3 + +httpClient = urllib3.ProxyManager( + 'https://proxy_host.sampledomain.com:8119/', + timeout=urllib3.Timeout.DEFAULT_TIMEOUT, + cert_reqs='CERT_REQUIRED', + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ) +) + +minioClient = Minio( + 'your_hostname.sampledomain.com:9000', + access_key='ACCESS_KEY', + secret_key='SECRET_KEY', + secure=True, + http_client=httpClient, +) +``` + +### AWS S3 + +```py +from minio import Minio +from minio.error import ResponseError + +s3Client = Minio( + 's3.amazonaws.com', + access_key='ACCESS_KEY', + secret_key='SECRET_KEY', +) +``` + +## 2. Bucket operations + + + +### make_bucket(self, bucket_name, location='us-east-1', object_lock=False) + +Create a bucket with region and object lock. + +__Parameters__ + +| Param | Type | Description | +|---------------|--------|---------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `location` | _str_ | Region in which the bucket will be created. | +| `object_lock` | _bool_ | Flag to set object-lock feature. | + +__Example__ + +```py +minio.make_bucket('foo') +minio.make_bucket('foo', 'us-west-1') +minio.make_bucket('foo', 'us-west-1', object_lock=True) +``` + + + +### list_buckets() + +List information of all accessible buckets. + +__Parameters__ + +| Return | +|:-----------------------------------------| +| An iterator contains bucket information. | + +__Example__ + +```py +bucket_list = minio.list_buckets() +for bucket in bucket_list: + print(bucket.name, bucket.creation_date) +``` + + + +### bucket_exists(bucket_name) + +Check if a bucket exists. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:--------------------| +| `bucket_name` | _str_ | Name of the bucket. | + +__Example__ + +```py +found = minio.bucket_exists("my-bucketname") +if found: + print("my-bucketname exists") +else: + print("my-bucketname does not exist") +``` + + + +### remove_bucket(bucket_name) + +Remove an empty bucket. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:--------------------| +| `bucket_name` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.remove_bucket("my-bucketname") +``` + + + +### list_objects(bucket_name, prefix=None, recursive=False, include_version=False) + +Lists object information of a bucket using S3 API version 1, optionally for prefix recursively. + +__Parameters__ + +| Param | Type | Description | +|:------------------|:-------|:-----------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `prefix` | _str_ | Object name starts with prefix. | +| `recursive` | _bool_ | List recursively than directory structure emulation. | +| `include_version` | _bool_ | Flag to control whether include object versions. | + +__Return Value__ + +| Return | +|:----------------------------------------------------------| +| An iterator contains object information as _minio.Object_ | + +__Example__ + +```py +# List objects information. +objects = minio.list_objects('foo') +for object in objects: + print(object) + +# List objects information whose names starts with 'hello/'. +objects = minio.list_objects('foo', prefix='hello/') +for object in objects: + print(object) + +# List objects information recursively. +objects = minio.list_objects('foo', recursive=True) +for object in objects: + print(object) + +# List objects information recursively whose names starts with +# 'hello/'. +objects = minio.list_objects( + 'foo', prefix='hello/', recursive=True, +) +for object in objects: + print(object) + +# List objects information recursively after object name +# 'hello/world/1'. +objects = minio.list_objects( + 'foo', recursive=True, start_after='hello/world/1', +) +for object in objects: + print(object) +``` + + + +### get_bucket_policy(bucket_name) + +Get bucket policy configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:--------------------------------------------| +| Bucket policy configuration as JSON string. | + +__Example__ + +```py +config = minio.get_bucket_policy("my-bucketname") +``` + + + +### set_bucket_policy(bucket_name, policy) + +Set bucket policy configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``Policy`` | _str_ | Bucket policy configuration as JSON string. | + +__Example__ + +```py +minio.set_bucket_policy("my-bucketname", config) +``` + + + +### delete_bucket_policy(bucket_name) + +Delete bucket policy configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.delete_bucket_policy("my-bucketname") +``` + + + +### get_bucket_notification(bucket_name) + +Get notification configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:--------------------------------------| +| Notification configuration as _dict_. | + +__Example__ + +```py +config = minio.get_bucket_notification("my-bucketname") +``` + + + +### set_bucket_notification(bucket_name, notification) + +Set notification configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:-----------------|:-------|:---------------------------------------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``notification`` | _dict_ | Non-empty dictionary with the structure specified below. | + +The `notification` argument has the following structure: + +* (dict) -- + * __TopicConfigurations__ (list) -- Optional list of service + configuration items specifying AWS SNS Topics as the target of the + notification. + * __QueueConfigurations__ (list) -- Optional list of service + configuration items specifying AWS SQS Queues as the target of the + notification. + * __CloudFunctionconfigurations__ (list) -- Optional list of service + configuration items specifying AWS Lambda Cloud functions as the + target of the notification. + +At least one of the above items needs to be specified in the +`notification` argument. + +The "service configuration item" alluded to above has the following structure: + +* (dict) -- + * __Id__ (string) -- Optional Id for the configuration item. If not + specified, it is auto-generated by the server. + * __Arn__ (string) -- Specifies the particular Topic/Queue/Cloud + Function identifier. + * __Events__ (list) -- A non-empty list of event-type strings from: + _'s3:ReducedRedundancyLostObject'_, + _'s3:ObjectCreated:*'_, + _'s3:ObjectCreated:Put'_, + _'s3:ObjectCreated:Post'_, + _'s3:ObjectCreated:Copy'_, + _'s3:ObjectCreated:CompleteMultipartUpload'_, + _'s3:ObjectRemoved:*'_, + _'s3:ObjectRemoved:Delete'_, + _'s3:ObjectRemoved:DeleteMarkerCreated'_ + * __Filter__ (dict) -- An optional dictionary container of object + key name based filter rules. + * __Key__ (dict) -- Dictionary container of object key name prefix + and suffix filtering rules. + * __FilterRules__ (list) -- A list of containers that specify + the criteria for the filter rule. + * (dict) -- A dictionary container of key value pairs that + specify a single filter rule. + * __Name__ (string) -- Object key name with value 'prefix' + or 'suffix'. + * __Value__ (string) -- Specify the value of the + prefix/suffix to which the rule applies. + +__Example__ + +```py +config = { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix', + 'Value': 'abc' + } + ] + } + } + } + ], + 'TopicConfigurations': [ + { + 'Arn': 'arn2', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ], + 'CloudFunctionConfigurations': [ + { + 'Arn': 'arn3', + 'Events': ['s3:ObjectRemoved:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ] +} + +minio.set_bucket_notification("my-bucketname", config) +``` + + + +### remove_all_bucket_notification(bucket_name) + +Remove notification configuration of a bucket. On success, S3 service stops notification of events previously set of the bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.remove_all_bucket_notification("my-bucketname") +``` + + + +### listen_bucket_notification(bucket_name, prefix='', suffix='', events=('s3:ObjectCreated:*', 's3:ObjectRemoved:*', 's3:ObjectAccessed:*')) + +Listen events of object prefix and suffix of a bucket. Caller should iterate returned iterator to read new events. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:-------|:--------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `prefix` | _str_ | Listen events of object starts with prefix. | +| `suffix` | _str_ | Listen events of object ends with suffix. | +| `events` | _list_ | Events to listen. | + +```py +iter = minio.listen_bucket_notification( + "my-bucketname", + events=('s3:ObjectCreated:*', 's3:ObjectAccessed:*'), +) +for events in iter: + print(events) +``` + + + +### get_bucket_encryption(bucket_name) + +Get encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:------------------------------------| +| Encryption configuration as _dict_. | + +__Example__ + +```py +config = minio.get_bucket_encryption("my-bucketname") +``` + + + +### put_bucket_encryption(bucket_name, encryption_configuration) + +Set encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------|:--------------------------------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``enc_config`` | _dict_ | Encryption configuration as dictionary to be set. | + +__Example__ + +```py +# Sample default encryption configuration +config = { + 'ServerSideEncryptionConfiguration':{ + 'Rule': [ + {'ApplyServerSideEncryptionByDefault': {'SSEAlgorithm': 'AES256'}} + ] + } +} + +minio.put_bucket_encryption("my-bucketname", config) +``` + + + +### delete_bucket_encryption(bucket_name) + +Delete encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.delete_bucket_encryption("my-bucketname") +``` + + + +### get_bucket_versioning(bucket_name) + +Get versioning configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +config = minio.get_bucket_versioning("my-bucketname") +print(config.status) +``` + + + +### set_bucket_versioning(bucket_name, config) + +Set versioning configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------------------|:--------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _VersioningConfig_ | Versioning configuration. | + +__Example__ + +```py +minio.set_bucket_versioning("my-bucketname", VersioningConfig(ENABLED)) +``` + + + +### delete_bucket_replication(bucket_name) + +Delete replication configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.delete_bucket_replication("my-bucketname") +``` + + + +### get_bucket_replication(bucket_name) + +Get replication configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:----------------------------------------| +| _ReplicationConfig_ object. | + +__Example__ + +```py +config = minio.get_bucket_replication("my-bucketname") +``` + + + +### set_bucket_replication(bucket_name, config) + +Set replication configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:--------------------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _ReplicationConfig_ | Replication configuration. | + +__Example__ + +```py +config = ReplicationConfig( + "REPLACE-WITH-ACTUAL-ROLE", + [ + Rule( + Destination( + "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", + ), + ENABLED, + delete_marker_replication=DeleteMarkerReplication( + DISABLED, + ), + rule_filter=Filter( + AndOperator( + "TaxDocs", + {"key1": "value1", "key2": "value2"}, + ), + ), + rule_id="rule1", + priority=1, + ), + ], +) +minio.set_bucket_replication("my-bucketname", config) +``` + + + +### delete_bucket_lifecycle(bucket_name) + +Delete lifecycle configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +minio.delete_bucket_lifecycle("my-bucketname") +``` + + + +### get_bucket_lifecycle(bucket_name) + +Get lifecycle configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:--------------------------| +| _LifecycleConfig_ object. | + + +__Example__ + +```py +config = minio.get_bucket_lifecycle("my-bucketname") +``` + + + +### set_bucket_lifecycle(bucket_name, config) + +Set lifecycle configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------------------|:-------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _LifecycleConfig_ | Lifecycle configuration. | + +__Example__ + +```py +config = LifecycleConfig( + [ + Rule( + ENABLED, + rule_filter=Filter(prefix="documents/"), + rule_id="rule1", + transition=Transition(days=30, storage_class="GLACIER"), + ), + Rule( + ENABLED, + rule_filter=Filter(prefix="logs/"), + rule_id="rule2", + expiration=Expiration(days=365), + ), + ], +) +minio.set_bucket_lifecycle("my-bucketname", config) +``` + +## 3. Object operations + + + +### get_object(bucket_name, object_name, offset=0, length=0, request_headers=None, sse=None, version_id=None, extra_query_params=None) + +Gets data from offset to length of an object. Returned response should be closed after use to release network resources. To reuse the connection, it's required to call `response.release_conn()` explicitly. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-----------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `offset` | _int_ | Start byte position of object data. | +| `length` | _int_ | Number of bytes of object data from offset. | +| `request_headers` | _dict_ | Any additional headers to be added with GET request. | +| `sse` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version-ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:----------------------------------------| +| _urllib3.response.HTTPResponse_ object. | + +__Example__ + +```py +// Get entire object data. + try: + response = minio.get_object('foo', 'bar') + // Read data from response. +finally: + response.close() + response.release_conn() + +// Get object data for offset/length. +try: + response = minio.get_object('foo', 'bar', 2, 4) + // Read data from response. +finally: + response.close() + response.release_conn() +``` + + + +### select_object_content(bucket_name, object_name, opts) + +Select content of an object by SQL expression. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:----------------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `request` | _SelectRequest_ | Select request. | + +__Return Value__ + +| Return | +|:-------------------------------------------------------------------------------------| +| A reader contains requested records and progress information as _SelectObjectReader_ | + +__Example__ + +```py +request = SelectRequest( + "select * from s3object", + CSVInputSerialization(), + CSVOutputSerialization(), + request_progress=True, +) +data = client.select_object_content('my-bucket', 'my-object', request) +with open('my-record-file', 'w') as record_data: + for d in data.stream(10*1024): + record_data.write(d) + # Get the stats + print(data.stats()) +``` + + + +### fget_object(bucket_name, object_name, file_path, request_headers=None, sse=None, version_id=None, extra_query_params=None) + +Downloads data of an object to file. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-----------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `file_path` | _str_ | Name of file to download. | +| `request_headers` | _dict_ | Any additional headers to be added with GET request. | +| `sse` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version-ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:-------------------------------| +| Object information as _Object_ | + +__Example__ + +```py +minio.fget_object('foo', 'bar', 'localfile') +minio.fget_object( + 'foo', 'bar', 'localfile', version_id='VERSION-ID', +) +``` + + + +### copy_object(bucket_name, object_name, object_source, conditions=None, source_sse=None, sse=None, metadata=None) + +Create an object by server-side copying data from another object. In this API maximum supported source object size is 5GiB. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-----------------|:----------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `object_source` | _str_ | Source object to be copied. | +| `conditions` | _CopyConditions_ | Collection of supported CopyObject conditions. | +| `source_sse` | _SseCustomerKey_ | Server-side encryption customer key of source object. | +| `sse` | _Sse_ | Server-side encryption of destination object. | +| `metadata` | _dict_ | Any user-defined metadata to be copied along with destination object. | + +__Return Value__ + +| Return | +|:----------------------------| +| _ObjectWriteResult_ object. | + +__Example__ + +```py +import time +from datetime import datetime +from minio import CopyConditions + +minio.copy_object( + "my-bucketname", + "my-objectname", + "my-source-bucketname/my-source-objectname", +) + +minio.copy_object( + "my-bucketname", + "my-objectname", + "my-source-bucketname/my-source-objectname" + "?versionId=b6602757-7c9c-449b-937f-fed504d04c94", +) + +copy_conditions = CopyConditions() +# Set modified condition, copy object modified since 2014 April. +t = (2014, 4, 0, 0, 0, 0, 0, 0, 0) +mod_since = datetime.utcfromtimestamp(time.mktime(t)) +copy_conditions.set_modified_since(mod_since) + +# Set unmodified condition, copy object unmodified since 2014 April. +copy_conditions.set_unmodified_since(mod_since) + +# Set matching ETag condition, copy object which matches the following ETag. +copy_conditions.set_match_etag("31624deb84149d2f8ef9c385918b653a") + +# Set matching ETag except condition, copy object which does not match the following ETag. +copy_conditions.set_match_etag_except("31624deb84149d2f8ef9c385918b653a") + +# Set metadata, which will be copied along with the destination object. +metadata = {"test-key": "test-data"} + +result = minioClient.copy_object( + "my-bucketname", + "my-objectname", + "my-source-bucketname/my-source-objectname", + copy_conditions,metadata=metadata, +) +print(result.object_name, result.version_id) +``` + + + +### put_object(bucket_name, object_name, data, length, content_type='application/octet-stream', metadata=None, sse=None, progress=None, part_size=DEFAULT_PART_SIZE) + +Uploads data from a stream to an object in a bucket. + +__Parameters__ + +| Param | Type | Description | +|:---------------|:---------------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `data` | _io.RawIOBase_ | Contains object data. | +| `content_type` | _str_ | Content type of the object. | +| `metadata` | _dict_ | Any additional metadata to be uploaded along with your PUT request. | +| `sse` | _Sse_ | Server-side encryption. | +| `progress` | _threading_ | A progress object. | +| `part_size` | _int_ | Multipart part size. | + +__Return Value__ + +| Return | +|:----------------------------------| +| etag and version ID if available. | + +__Example__ +```py +file_stat = os.stat('hello.txt') +with open('hello.txt', 'rb') as data: + minio.put_object( + 'foo', 'bar', data, file_stat.st_size, 'text/plain', + ) +``` + + + +### fput_object(bucket_name, object_name, file_path, content_type='application/octet-stream', metadata=None, sse=None, progress=None, part_size=DEFAULT_PART_SIZE) + +Uploads data from a file to an object in a bucket. + +| Param | Type | Description | +|:---------------|:------------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `file_path` | _str_ | Name of file to upload. | +| `content_type` | _str_ | Content type of the object. | +| `metadata` | _dict_ | Any additional metadata to be uploaded along with your PUT request. | +| `sse` | _Sse_ | Server-side encryption. | +| `progress` | _threading_ | A progress object. | +| `part_size` | _int_ | Multipart part size. | + +__Return Value__ + +| Return | +|:----------------------------------| +| etag and version ID if available. | + +__Example__ + +```py +minio.fput_object('foo', 'bar', 'filepath', 'text/plain') +``` + + + +### stat_object(bucket_name, object_name, sse=None, version_id=None, extra_query_params=None) + +Get object information and metadata of an object. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `sse` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:---------| +| Object information as _Object_ | + +__Example__ + +```py +stat = minio.stat_object("my-bucketname", "my-objectname") +``` + + + +### remove_object(bucket_name, object_name, version_id=None) + +Remove an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +minio.remove_object("my-bucketname", "my-objectname") +minio.remove_object( + "my-bucketname", + "my-objectname", + version_id="13f88b18-8dcd-4c83-88f2-8631fdb6250c", +) +``` + + + +### remove_objects(bucket_name, objects_iter) + +Remove multiple objects. + +__Parameters__ + +| Param | Type | Description | +|:---------------|:-------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `objects_iter` | _list_ | An iterable type python object providing object names for deletion. | + +__Return Value__ + +| Return | +|:----------------------------------------| +| An iterator contains _MultiDeleteError_ | + +__Example__ + +```py +minio.remove_objects( + "my-bucketname", + [ + "my-objectname1", + "my-objectname2", + ("my-objectname3", "13f88b18-8dcd-4c83-88f2-8631fdb6250c"), + ], +) +``` + +## 4. Presigned operations + + + +### presigned_get_object(bucket_name, object_name, expires=timedelta(days=7), response_headers=None, request_date=None, version_id=None, extra_query_params=None) + +Get presigned URL of an object to download its data with expiry time and custom request parameters. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:---------------------|:---------------------------------------------------------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `expires` | _datetime.timedelta_ | Expiry in seconds; defaults to 7 days. | +| `response_headers` | _dict_ | Optional response_headers argument to specify response fields like date, size, type of file, data about server, etc. | +| `request_date` | _datetime.datetime_ | Optional request_date argument to specify a different request date. Default is current date. | +| `version_id` | _str_ | Version ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:-----------| +| URL string | + +__Example__ + +```py +# Get presigned URL string to download 'my-objectname' in +# 'my-bucketname' with default expiry. +url = minio.presigned_get_object("my-bucketname", "my-objectname") +print(url) + +# Get presigned URL string to download 'my-objectname' in +# 'my-bucketname' with two hours expiry. +url = minio.presigned_get_object( + "my-bucketname", "my-objectname", expires=timedelta(hours=2), +) +print(url) +``` + + + +### presigned_put_object(bucket_name, object_name, expires=timedelta(days=7)) + +Get presigned URL of an object to upload data with expiry time and custom request parameters. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:---------------------|:---------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `expires` | _datetime.timedelta_ | Expiry in seconds; defaults to 7 days. | + +__Return Value__ + +| Return | +|:-----------| +| URL string | + +__Example__ + +```py +# Get presigned URL string to upload data to 'my-objectname' in +# 'my-bucketname' with default expiry. +url = minio.presigned_put_object("my-bucketname", "my-objectname") +print(url) + +# Get presigned URL string to upload data to 'my-objectname' in +# 'my-bucketname' with two hours expiry. +url = minio.presigned_put_object( + "my-bucketname", "my-objectname", expires=timedelta(hours=2), +) +print(url) +``` + + + +### presigned_post_policy(post_policy) + +Get form-data of PostPolicy of an object to upload its data using POST method. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:-------------|:-------------| +| `post_policy` | _PostPolicy_ | Post policy. | + +__Return Value__ + +| Return | +|:----------------------------| +| Form-data containing _dict_ | + +__Example__ + +Create policy: + +```py +post_policy = PostPolicy() +post_policy.set_bucket_name('bucket_name') + +# set object prefix for object upload. +post_policy.set_key_startswith('objectPrefix/') + +# set expiry to 10 days. +expires_date = datetime.utcnow()+timedelta(days=10) +post_policy.set_expires(expires_date) + +# set content length for incoming uploads. +post_policy.set_content_length_range(10, 1024) + +# set content-type to allow only text. +post_policy.set_content_type('text/plain') + +form_data = presigned_post_policy(post_policy) +print(form_data) +``` + +## 5. Explore Further + +- [MinIO Golang Client SDK Quickstart Guide](https://docs.min.io/docs/golang-client-quickstart-guide) +- [MinIO Java Client SDK Quickstart Guide](https://docs.min.io/docs/java-client-quickstart-guide) +- [MinIO JavaScript Client SDK Quickstart Guide](https://docs.min.io/docs/javascript-client-quickstart-guide) diff --git a/testbed/minio__minio-py/docs/zh_CN/API.md b/testbed/minio__minio-py/docs/zh_CN/API.md new file mode 100644 index 0000000000000000000000000000000000000000..3147418944a906083b6a460ad9acd7d272edb4ee --- /dev/null +++ b/testbed/minio__minio-py/docs/zh_CN/API.md @@ -0,0 +1,1049 @@ +# Python Client API文档 [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## 初使化MinIO Client对象。 + +## MinIO + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', + secure=True) +``` + +## AWS S3 + +```py +from minio import Minio +from minio.error import ResponseError + +s3Client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY', + secure=True) +``` + + + +|操作存储桶 | 操作对象| Presigned操作 | 存储桶策略/通知 +|:---|:---|:---|:---| +| [`make_bucket`](#make_bucket) | [`get_object`](#get_object) | [`presigned_get_object`](#presigned_get_object) | [`get_bucket_policy`](#get_bucket_policy) | +| [`list_buckets`](#list_buckets) | [`put_object`](#put_object) | [`presigned_put_object`](#presigned_put_object) | [`set_bucket_policy`](#set_bucket_policy) | +| [`bucket_exists`](#bucket_exists) | [`copy_object`](#copy_object) | [`presigned_post_policy`](#presigned_post_policy) | [`get_bucket_notification`](#get_bucket_notification) | +| [`remove_bucket`](#remove_bucket) | [`stat_object`](#stat_object) | | [`set_bucket_notification`](#set_bucket_notification) | +| [`list_objects`](#list_objects) | [`remove_object`](#remove_object) | | [`remove_all_bucket_notification`](#remove_all_bucket_notification) | +| [`list_objects_v2`](#list_objects_v2) | [`remove_objects`](#remove_objects) | | [`listen_bucket_notification`](#listen_bucket_notification) | +| [`list_incomplete_uploads`](#list_incomplete_uploads) | [`remove_incomplete_upload`](#remove_incomplete_upload) | | | +| | [`fput_object`](#fput_object) | | | +| | [`fget_object`](#fget_object) | | | +| | [`get_partial_object`](#get_partial_object) | | | + +## 1. 构造函数 + + +### Minio(endpoint, access_key=None, secret_key=None, secure=True, region=None, http_client=None) + +| | +|---| +| `Minio(endpoint, access_key=None, secret_key=None, secure=True, region=None, http_client=None)` | +| 初使化一个新的client对象。 | + +参数 + + +|参数 | 类型 |描述 | +|:---|:---|:---| +| `endpoint` | _string_ | S3兼容对象存储服务endpoint。 | +| `access_key` | _string_ | 对象存储的Access key。(如果是匿名访问则可以为空)。 | +| `secret_key` | _string_ | 对象存储的Secret key。(如果是匿名访问则可以为空)。 | +| `secure` |_bool_ | 设为`True`代表启用HTTPS。 (默认是`True`)。 | +| `region` |_string_ | 设置该值以覆盖自动发现存储桶region。 (可选,默认值是`None`)。 | +| `http_client` |_urllib3.poolmanager.PoolManager_ | 设置该值以使用自定义的http client,而不是默认的http client。(可选,默认值是`None`)。 | + +__示例__ + +### MinIO + +```py +from minio import Minio +from minio.error import ResponseError + +minioClient = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG') +``` + +```py +from minio import Minio +from minio.error import ResponseError +import urllib3 + +httpClient = urllib3.ProxyManager( + 'https://proxy_host.sampledomain.com:8119/' + timeout=urllib3.Timeout.DEFAULT_TIMEOUT, + cert_reqs='CERT_REQUIRED', + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504] + ) + ) +minioClient = Minio('your_hostname.sampledomain.com:9000', + access_key='ACCESS_KEY', + secret_key='SECRET_KEY', + secure=True, + http_client=httpClient) +``` + +### AWS S3 + +```py +from minio import Minio +from minio.error import ResponseError + +s3Client = Minio('s3.amazonaws.com', + access_key='ACCESS_KEY', + secret_key='SECRET_KEY') +``` + +## 2. 操作存储桶 + + +### make_bucket(bucket_name, location='us-east-1') +创建一个存储桶。 + +参数 + +|参数 | 类型 |描述 | +|---|---|---| +|`bucket_name` | _string_ | 存储桶名称。 | +| `location` | _string_ | 存储桶被创建的region(地区),默认是us-east-1(美国东一区),下面列举的是其它合法的值: | +| | |us-east-1 | +| | |us-west-1 | +| | |us-west-2 | +| | |eu-west-1 | +| | | eu-central-1| +| | | ap-southeast-1| +| | | ap-northeast-1| +| | | ap-southeast-2| +| | | sa-east-1| +| | | cn-north-1| + +__示例__ + +```py +try: + minioClient.make_bucket("mybucket", location="us-east-1") +except ResponseError as err: + print(err) +``` + + +### list_buckets() +列出所有的存储桶。 + +参数 + +|返回值 | 类型 |描述 | +|:---|:---|:---| +|``bucketList`` |_function_ |所有存储桶的list。 | +|``bucket.name`` |_string_ |存储桶名称。 | +|``bucket.creation_date`` |_time_ |存储桶的创建时间。 | + +__示例__ + +```py +buckets = minioClient.list_buckets() +for bucket in buckets: + print(bucket.name, bucket.creation_date) +``` + + +### bucket_exists(bucket_name) +检查存储桶是否存在。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_|存储桶名称。 | + +__示例__ + +```py +try: + print(minioClient.bucket_exists("mybucket")) +except ResponseError as err: + print(err) +``` + + +### remove_bucket(bucket_name) +删除存储桶。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | + +__示例__ + +```py +try: + minioClient.remove_bucket("mybucket") +except ResponseError as err: + print(err) +``` + + +### list_objects(bucket_name, prefix=None, recursive=False) +列出存储桶中所有对象。 + +参数 + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ | 存储桶名称。 | +|``prefix`` | _string_ |用于过滤的对象名称前缀。可选项,默认为None。 | +|``recursive`` | _bool_ |`True`代表递归查找,`False`代表类似文件夹查找,以'/'分隔,不查子文件夹。(可选,默认值是`False`)。 | + +__返回值__ + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``object`` |_Object_ | 该存储桶中所有对象的Iterator,对象的格式如下: | + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``object.bucket_name`` | _string_ | 对象所在存储桶的名称。| +|``object.object_name`` | _string_ | 对象的名称。| +|``object.is_dir`` | _bool_ | `True`代表列举的对象是文件夹(对象前缀), `False`与之相反。| +|``object.size`` | _int_ | 对象的大小。| +|``object.etag`` | _string_ | 对象的etag值。| +|``object.last_modified`` |_datetime.datetime_ | 最后修改时间。| +|``object.content_type`` | _string_ | 对象的content-type。| +|``object.metadata`` | _dict_ | 对象的其它元数据。| + + +__示例__ + +```py +# List all object paths in bucket that begin with my-prefixname. +objects = minioClient.list_objects('mybucket', prefix='my-prefixname', + recursive=True) +for obj in objects: + print(obj.bucket_name, obj.object_name.encode('utf-8'), obj.last_modified, + obj.etag, obj.size, obj.content_type) +``` + + +### list_objects_v2(bucket_name, prefix=None, recursive=False) +使用V2版本API列出一个存储桶中的对象。 + +参数 + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ | 存储桶名称。 | +|``prefix`` | _string_ |用于过滤的对象名称前缀。可选项,默认为None。 | +|``recursive`` | _bool_ |`True`代表递归查找,`False`代表类似文件夹查找,以'/'分隔,不查子文件夹。(可选,默认值是`False`)。 | + +__返回值__ + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``object`` |_Object_ | 该存储桶中所有对象的Iterator,对象的格式如下: | + +| 参数 | 类型 | 描述 | +|:---|:---|:---| +|``object.bucket_name`` | _string_ | 对象所在存储桶的名称。| +|``object.object_name`` | _string_ | 对象的名称。| +|``object.is_dir`` | _bool_ | `True`代表列举的对象是文件夹(对象前缀), `False`与之相反。| +|``object.size`` | _int_ | 对象的大小。| +|``object.etag`` | _string_ | 对象的etag值。| +|``object.last_modified`` |_datetime.datetime_ | 最后修改时间。| +|``object.content_type`` | _string_ | 对象的content-type。| +|``object.metadata`` | _dict_ | 对象的其它元数据。| + + +__示例__ + +```py +# List all object paths in bucket that begin with my-prefixname. +objects = minioClient.list_objects_v2('mybucket', prefix='my-prefixname', + recursive=True) +for obj in objects: + print(obj.bucket_name, obj.object_name.encode('utf-8'), obj.last_modified, + obj.etag, obj.size, obj.content_type) +``` + + +### list_incomplete_uploads(bucket_name, prefix, recursive=False) +列出存储桶中未完整上传的对象。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_|存储桶名称。| +|``prefix`` |_string_ |用于过滤的对象名称前缀。 | +|``recursive`` |_bool_ |`True`代表递归查找,`False`代表类似文件夹查找,以'/'分隔,不查子文件夹。(可选,默认值是`False`)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``multipart_obj`` | _Object_ |multipart对象的Iterator,格式如下:| + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``multipart_obj.object_name`` | _string_ |未完整上传的对象的名称。| +|``multipart_obj.upload_id`` | _string_ |未完整上传的对象的上传ID。| +|``multipart_obj.size`` | _int_ |未完整上传的对象的大小。| + +__示例__ + + +```py +# List all object paths in bucket that begin with my-prefixname. +uploads = minioClient.list_incomplete_uploads('mybucket', + prefix='my-prefixname', + recursive=True) +for obj in uploads: + print(obj.bucket_name, obj.object_name, obj.upload_id, obj.size) +``` + + +### get_bucket_policy(bucket_name, prefix) +获取存储桶的当前策略。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |存储桶名称。| +|``prefix`` |_string_ |对象的名称前缀。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``Policy`` | _minio.policy.Policy_ |Policy枚举:Policy.READ_ONLY,Policy.WRITE_ONLY,Policy.READ_WRITE或 Policy.NONE。 | + +__示例__ + + +```py +# Get current policy of all object paths in bucket that begin with my-prefixname. +policy = minioClient.get_bucket_policy('mybucket', + 'my-prefixname') +print(policy) +``` + + +### set_bucket_policy(bucket_name, prefix, policy) + +给指定的存储桶设置存储桶策略。如果`prefix`不为空,则该存储桶策略仅对匹配这个指定前缀的对象生效。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |存储桶名称。| +|``prefix`` |_string_ | 对象的名称前缀。 | +|``Policy`` | _minio.policy.Policy_ |Policy枚举:Policy.READ_ONLY,Policy.WRITE_ONLY,Policy.READ_WRITE或 Policy.NONE。 | + + +__示例__ + + +```py +# Set policy Policy.READ_ONLY to all object paths in bucket that begin with my-prefixname. +minioClient.set_bucket_policy('mybucket', + 'my-prefixname', + Policy.READ_ONLY) +``` + + +### get_bucket_notification(bucket_name) + +获取存储桶上的通知配置。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |存储桶名称。| + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``notification`` | _dict_ | 如果没有通知配置,则返回一个空的dictionary,否则就和set_bucket_notification的参数结构一样。 | + +__示例__ + + +```py +# Get the notifications configuration for a bucket. +notification = minioClient.get_bucket_notification('mybucket') +# If no notification is present on the bucket: +# notification == {} +``` + + +### set_bucket_notification(bucket_name, notification) + +给存储桶设置通知配置。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |存储桶名称。| +|``notification`` | _dict_ |非空dictionary,内部结构格式如下:| + +`notification`参数格式如下: + +* (dict) -- + * __TopicConfigurations__ (list) -- 服务配置项目的可选列表,指定了AWS SNS Topics做为通知的目标。 + * __QueueConfigurations__ (list) -- 服务配置项目的可选列表,指定了AWS SQS Queues做为通知的目标。 + * __CloudFunctionconfigurations__ (list) -- 服务配置项目的可选列表,指定了AWS Lambda Cloud functions做为通知的目标。 + +以上项目中至少有一项需要在`notification`参数中指定。 + +上面提到的“服务配置项目”具有以下结构: + +* (dict) -- + * __Id__ (string) -- 配置项的可选ID,如果不指定,服务器自动生成。 + * __Arn__ (string) -- 指定特定的Topic/Queue/Cloud Function identifier。 + * __Events__ (list) -- 一个含有事件类型字符串的非空列表,事件类型取值如下: + _'s3:ReducedRedundancyLostObject'_, + _'s3:ObjectCreated:*'_, + _'s3:ObjectCreated:Put'_, + _'s3:ObjectCreated:Post'_, + _'s3:ObjectCreated:Copy'_, + _'s3:ObjectCreated:CompleteMultipartUpload'_, + _'s3:ObjectRemoved:*'_, + _'s3:ObjectRemoved:Delete'_, + _'s3:ObjectRemoved:DeleteMarkerCreated'_ + * __Filter__ (dict) -- 一个可选的dictionary容器,里面含有基于键名称过滤的规则的对象。 + * __Key__ (dict) -- dictionary容器,里面含有基于键名称前缀和后缀过滤的规则的对象。 + * __FilterRules__ (list) -- 指定过滤规则标准的容器列表。 + * (dict) -- 键值对的dictionary容器,指定单个的过滤规则。 + * __Name__ (string) -- 对象的键名称,值为“前缀”或“后缀”。 + * __Value__ (string) -- 指定规则适用的值。 + + +没有返回值。如果目标服务报错,会抛出`ResponseError`。如果有验证错误,会抛出`InvalidArgumentError`或者`TypeError`。输入参数的configuration不能为空 - 为了删除存储桶上的通知配置,参考`remove_all_bucket_notification()` API。 + +__示例__ + + +```py +notification = { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix', + 'Value': 'abc' + } + ] + } + } + } + ], + 'TopicConfigurations': [ + { + 'Arn': 'arn2', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ], + 'CloudFunctionConfigurations': [ + { + 'Arn': 'arn3', + 'Events': ['s3:ObjectRemoved:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ] +} + + +try: + minioClient.set_bucket_notification('mybucket', notification) +except ResponseError as err: + # handle error response from service. + print(err) +except (ArgumentError, TypeError) as err: + # should happen only during development. Fix the notification argument + print(err) +``` + + +### remove_all_bucket_notification(bucket_name) + +删除存储桶上配置的所有通知。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |存储桶名称。| + +没有返回值,如果操作失败会抛出 `ResponseError` 异常。 + +__示例__ + + +```py +# Remove all the notifications config for a bucket. +minioClient.remove_all_bucket_notification('mybucket') +``` + + +### listen_bucket_notification(bucket_name, prefix, suffix, events) + +监听存储桶上的通知,可以额外提供前缀、后缀和时间类型来进行过滤。使用该API前不需要先设置存储桶通知。这是一个MinIO的扩展API,MinIO Server会基于过来的请求使用唯一标识符自动注册或者注销。 + +当通知发生时,产生事件,调用者需要遍历读取这些事件。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ |监听事件通知的存储桶名称。| +|``prefix`` | _string_ | 过滤通知的对象名称前缀。| +|``suffix`` | _string_ | 过滤通知的对象名称后缀。| +|``events`` | _list_ | 启用特定事件类型的通知。 | + +完整示例请看 [这里](https://raw.githubusercontent.com/minio/minio-py/master/examples/listen_notification.py)。 + +```py +# Put a file with default content-type. +events = minioClient.listen_bucket_notification('my-bucket', 'my-prefix/', + '.my-suffix', + ['s3:ObjectCreated:*', + 's3:ObjectRemoved:*', + 's3:ObjectAccessed:*']) +for event in events: + print event +``` + +## 3. 操作对象 + +### get_object(bucket_name, object_name, request_headers=None) +下载一个对象。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``request_headers`` |_dict_ |额外的请求头信息 (可选,默认为None)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``object`` | _urllib3.response.HTTPResponse_ |http streaming reader。 | + +__示例__ + + +```py +# Get a full object. +try: + data = minioClient.get_object('mybucket', 'myobject') + with open('my-testfile', 'wb') as file_data: + for d in data.stream(32*1024): + file_data.write(d) +except ResponseError as err: + print(err) +``` + + +### get_partial_object(bucket_name, object_name, offset=0, length=0, request_headers=None) +下载一个对象的指定区间的字节数组。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``offset`` |_int_ |``offset`` 是起始字节的位置 | +|``length`` |_int_ |``length``是要读取的长度 (可选,如果无值则代表读到文件结尾)。 | +|``request_headers`` |_dict_ |额外的请求头信息 (可选,默认为None)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``object`` | _urllib3.response.HTTPResponse_ |http streaming reader。 | + +__示例__ + +```py +# Offset the download by 2 bytes and retrieve a total of 4 bytes. +try: + data = minioClient.get_partial_object('mybucket', 'myobject', 2, 4) + with open('my-testfile', 'wb') as file_data: + for d in data: + file_data.write(d) +except ResponseError as err: + print(err) +``` + + +### fget_object(bucket_name, object_name, file_path, request_headers=None) +下载并将文件保存到本地。 + +参数 + + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``file_path`` |_dict_ | 对象数据要写入的本地文件路径。 | +|``request_headers`` |_dict_ |额外的请求头信息 (可选,默认为None)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``obj``|_Object_ |对象的统计信息,格式如下: | + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``obj.size``|_int_ | 对象的大小。 | +|``obj.etag``|_string_| 对象的etag值。| +|``obj.content_type``|_string_ | 对象的Content-Type。| +|``obj.last_modified``|_time.time_ | 最后修改时间。| +|``obj.metadata`` |_dict_ | 对象的其它元数据。 | + +__示例__ + +```py +# Get a full object and prints the original object stat information. +try: + print(minioClient.fget_object('mybucket', 'myobject', '/tmp/myobject')) +except ResponseError as err: + print(err) +``` + + +### copy_object(bucket_name, object_name, object_source, copy_conditions=None, metadata=None) + 拷贝对象存储服务上的源对象到一个新对象。 + +注意:本API支持的最大文件大小是5GB。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |新对象的存储桶名称。 | +|``object_name`` |_string_ | 新对象的名称。 | +|``object_source`` |_string_ |要拷贝的源对象的存储桶名称+对象名称。 | +|``copy_conditions`` |_CopyConditions_ | 拷贝操作需要满足的一些条件(可选,默认为None)。 | + + +__示例__ + +以下所有条件都是允许的,并且可以组合使用。 + +```py +import time +from datetime import datetime +from minio import CopyConditions + +copy_conditions = CopyConditions() +# Set modified condition, copy object modified since 2014 April. +t = (2014, 4, 0, 0, 0, 0, 0, 0, 0) +mod_since = datetime.utcfromtimestamp(time.mktime(t)) +copy_conditions.set_modified_since(mod_since) + +# Set unmodified condition, copy object unmodified since 2014 April. +copy_conditions.set_unmodified_since(mod_since) + +# Set matching ETag condition, copy object which matches the following ETag. +copy_conditions.set_match_etag("31624deb84149d2f8ef9c385918b653a") + +# Set matching ETag except condition, copy object which does not match the following ETag. +copy_conditions.set_match_etag_except("31624deb84149d2f8ef9c385918b653a") + +# Set metadata +metadata = {"test-key": "test-data"} + +try: + copy_result = minioClient.copy_object("mybucket", "myobject", + "/my-sourcebucketname/my-sourceobjectname", + copy_conditions,metadata=metadata) + print(copy_result) +except ResponseError as err: + print(err) +``` + + +### put_object(bucket_name, object_name, data, length, content_type='application/octet-stream', metadata=None) +添加一个新的对象到对象存储服务。 + +注意:本API支持的最大文件大小是5TB。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``data`` |_io.RawIOBase_ |任何实现了io.RawIOBase的python对象。 | +|``length`` |_int_ |对象的总长度。 | +|``content_type`` |_string_ | 对象的Content type。(可选,默认是“application/octet-stream”)。 | +|``metadata`` |_dict_ | 其它元数据。(可选,默认是None)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``etag``|_string_ |对象的etag值。 | + +__示例__ + +单个对象的最大大小限制在5TB。put_object在对象大于5MiB时,自动使用multiple parts方式上传。这样,当上传失败时,客户端只需要上传未成功的部分即可(类似断点上传)。上传的对象使用MD5SUM签名进行完整性验证。 + +```py +import os +# Put a file with default content-type, upon success prints the etag identifier computed by server. +try: + with open('my-testfile', 'rb') as file_data: + file_stat = os.stat('my-testfile') + print(minioClient.put_object('mybucket', 'myobject', + file_data, file_stat.st_size)) +except ResponseError as err: + print(err) + +# Put a file with 'application/csv'. +try: + with open('my-testfile.csv', 'rb') as file_data: + file_stat = os.stat('my-testfile.csv') + minioClient.put_object('mybucket', 'myobject.csv', file_data, + file_stat.st_size, content_type='application/csv') +except ResponseError as err: + print(err) +``` + + +### fput_object(bucket_name, object_name, file_path, content_type='application/octet-stream', metadata=None) +通过文件上传到对象中。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``file_path`` |_string_ |本地文件的路径,会将该文件的内容上传到对象存储服务上。 | +|``content_type`` |_string_ | 对象的Content type(可选,默认是“application/octet-stream”)。 | +|``metadata`` |_dict_ | 其它元数据(可选,默认是None)。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``etag``|_string_ |对象的etag值。 | + +__示例__ + +单个对象的最大大小限制在5TB。fput_object在对象大于5MiB时,自动使用multiple parts方式上传。这样,当上传失败时,客户端只需要上传未成功的部分即可(类似断点上传)。上传的对象使用MD5SUM签名进行完整性验证。 + +```py +# Put an object 'myobject' with contents from '/tmp/otherobject', upon success prints the etag identifier computed by server. +try: + print(minioClient.fput_object('mybucket', 'myobject', '/tmp/otherobject')) +except ResponseError as err: + print(err) + +# Put on object 'myobject.csv' with contents from +# '/tmp/otherobject.csv' as 'application/csv'. +try: + print(minioClient.fput_object('mybucket', 'myobject.csv', + '/tmp/otherobject.csv', + content_type='application/csv')) +except ResponseError as err: + print(err) +``` + + +### stat_object(bucket_name, object_name) +获取对象的元数据。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |名称名称。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``obj``|_Object_ |对象的统计信息,格式如下: | + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``obj.size``|_int_ |对象的大小。 | +|``obj.etag``|_string_|对象的etag值。| +|``obj.content_type``|_string_ | 对象的Content-Type。 | +|``obj.last_modified``|_time.time_ | UTC格式的最后修改时间。| +|``obj.metadata`` |_dict_ | 对象的其它元数据信息。 | + + +__示例__ + + +```py +# Fetch stats on your object. +try: + print(minioClient.stat_object('mybucket', 'myobject')) +except ResponseError as err: + print(err) +``` + + +### remove_object(bucket_name, object_name) +删除一个对象。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | + +__示例__ + + +```py +# Remove an object. +try: + minioClient.remove_object('mybucket', 'myobject') +except ResponseError as err: + print(err) +``` + + +### remove_objects(bucket_name, objects_iter) +删除存储桶中的多个对象。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` | _string_ | 存储桶名称。 | +|``objects_iter`` | _list_ , _tuple_ or _iterator_ | 多个对象名称的列表数据。 | + +__返回值__ + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``delete_error_iterator`` | _iterator_ of _MultiDeleteError_ instances | 删除失败的错误信息iterator,格式如下: | + +_注意_ + +1. 由于上面的方法是延迟计算(lazy evaluation),默认是不计算的,所以上面返回的iterator必须被evaluated(比如:使用循环)。 + +2. 该iterator只有在执行删除操作出现错误时才不为空,每一项都包含删除报错的对象的错误信息。 + +该iterator产生的每一个删除错误信息都有如下结构: + +|参数 |类型 |描述 | +|:---|:---|:---| +|``MultiDeleteError.object_name`` | _string_ | 删除报错的对象名称。 | +|``MultiDeleteError.error_code`` | _string_ | 错误码。 | +|``MultiDeleteError.error_message`` | _string_ | 错误信息。 | + +__示例__ + + +```py +# Remove multiple objects in a single library call. +try: + objects_to_delete = ['myobject-1', 'myobject-2', 'myobject-3'] + # force evaluation of the remove_objects() call by iterating over + # the returned value. + for del_err in minioClient.remove_objects('mybucket', objects_to_delete): + print("Deletion Error: {}".format(del_err)) +except ResponseError as err: + print(err) +``` + + +### remove_incomplete_upload(bucket_name, object_name) +删除一个未完整上传的对象。 + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | + +__示例__ + + +```py +# Remove an partially uploaded object. +try: + minioClient.remove_incomplete_upload('mybucket', 'myobject') +except ResponseError as err: + print(err) +``` + +## 4. Presigned操作 + + +### presigned_get_object(bucket_name, object_name, expiry=timedelta(days=7)) +生成一个用于HTTP GET操作的presigned URL。浏览器/移动客户端可以在即使存储桶为私有的情况下也可以通过这个URL进行下载。这个presigned URL可以有一个过期时间,默认是7天。 + + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``expiry`` | _datetime.datetime_ |过期时间,单位是秒,默认是7天。 | +|``response_headers`` | _dictionary_ |额外的响应头 (比如:`response-content-type`、`response-content-disposition`)。 | + +__示例__ + + +```py +from datetime import timedelta + +# presigned get object URL for object name, expires in 2 days. +try: + print(minioClient.presigned_get_object('mybucket', 'myobject', expires=timedelta(days=2))) +# Response error is still possible since internally presigned does get bucket location. +except ResponseError as err: + print(err) +``` + + +### presigned_put_object(bucket_name, object_name, expires=timedelta(days=7)) +生成一个用于HTTP PUT操作的presigned URL。浏览器/移动客户端可以在即使存储桶为私有的情况下也可以通过这个URL进行上传。这个presigned URL可以有一个过期时间,默认是7天。 + +注意:你可以通过只指定对象名称上传到S3。 + + +参数 + +|参数 | 类型 |描述 | +|:---|:---|:---| +|``bucket_name`` |_string_ |存储桶名称。 | +|``object_name`` |_string_ |对象名称。 | +|``expiry`` | _datetime.datetime_ |过期时间,单位是秒,默认是7天。 | + +__示例__ + +```py +from datetime import timedelta + +# presigned Put object URL for an object name, expires in 3 days. +try: + print(minioClient.presigned_put_object('mybucket', + 'myobject', + expires=timedelta(days=3))) +# Response error is still possible since internally presigned does get +# bucket location. +except ResponseError as err: + print(err) +``` + + +### presigned_post_policy(PostPolicy) +允许给POST操作的presigned URL设置策略条件。这些策略包括比如,接收对象上传的存储桶名称,名称前缀,过期策略。 + +创建policy: + +```py +from datetime import datetime, timedelta + +from minio import PostPolicy +post_policy = PostPolicy() + +# Apply upload policy restrictions: + +# set bucket name location for uploads. +post_policy.set_bucket_name('mybucket') +# set key prefix for all incoming uploads. +post_policy.set_key_startswith('myobject') +# set content length for incoming uploads. +post_policy.set_content_length_range(10, 1024) +# set content-type to allow only text +post_policy.set_content_type('text/plain') + +# set expiry 10 days into future. +expires_date = datetime.utcnow()+timedelta(days=10) +post_policy.set_expires(expires_date) +``` +获得POST表单的键值对形式的对象: + +```py +try: + signed_form_data = minioClient.presigned_post_policy(post_policy) +except ResponseError as err: + print(err) +``` + + +使用`curl`POST你的数据: + + +```py +curl_str = 'curl -X POST {0}'.format(signed_form_data[0]) +curl_cmd = [curl_str] +for field in signed_form_data[1]: + curl_cmd.append('-F {0}={1}'.format(field, signed_form_data[1][field])) + +# print curl command to upload files. +curl_cmd.append('-F file=@') +print(' '.join(curl_cmd)) +``` + +## 5. 了解更多 + +- [MinIO Golang Client SDK快速入门](https://docs.min.io/docs/golang-client-quickstart-guide) +- [MinIO Java Client SDK快速入门](https://docs.min.io/docs/java-client-quickstart-guide) +- [MinIO JavaScript Client SDK快速入门](https://docs.min.io/docs/javascript-client-quickstart-guide) diff --git a/testbed/minio__minio-py/docs/zh_CN/CONTRIBUTING.md b/testbed/minio__minio-py/docs/zh_CN/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..92fe2b18bdcaeb6cf4c6ecefc5c09b519466b384 --- /dev/null +++ b/testbed/minio__minio-py/docs/zh_CN/CONTRIBUTING.md @@ -0,0 +1,20 @@ +### 设置你的minio-py Github仓库 +Fork [minio-py upstream](https://github.com/minio/minio-py/fork)源码仓库到你自己的仓库。 + +```sh +$ git clone https://github.com/$USER_ID/minio-py +$ cd minio-py +$ python setup.py install +... +``` + +### 开发者指南 + +``minio-py``欢迎你的贡献。为了让大家配合的更加默契,我们做出如下约定: + +* fork项目并修改,我们鼓励大家使用pull requests进行代码相关的讨论。 + - Fork项目 + - 创建你的特性分支 (git checkout -b my-new-feature) + - Commit你的修改(git commit -am 'Add some feature') + - Push到远程分支(git push origin my-new-feature) + - 创建一个Pull Request diff --git a/testbed/minio__minio-py/examples/bucket_exists.py b/testbed/minio__minio-py/examples/bucket_exists.py new file mode 100644 index 0000000000000000000000000000000000000000..a07d647a5c71fe1d7c99d8bcc5b3d03f6eaf5ada --- /dev/null +++ b/testbed/minio__minio-py/examples/bucket_exists.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +try: + print(client.bucket_exists('my-bucketname')) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/copy_object.py b/testbed/minio__minio-py/examples/copy_object.py new file mode 100644 index 0000000000000000000000000000000000000000..b3191da8d3ed91e315c76f31fb6cf559e261db87 --- /dev/null +++ b/testbed/minio__minio-py/examples/copy_object.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2016-2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-testfile, my-bucketname and +# my-objectname are dummy values, please replace them with original values. + +from datetime import datetime, timezone + +from minio import CopyConditions, Minio + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEY', + secret_key='YOUR-SECRETKEY') + +# copy an object from a bucket to another. +result = client.copy_object( + "my-bucket", + "my-object", + "/my-sourcebucket/my-sourceobject", +) +print(result.object_name, result.version_id) + +# copy an object with condition. +copy_conditions = CopyConditions() +# Set modified condition, copy object modified since 1st April 2014. +mod_since = datetime(2014, 4, 1, tzinfo=timezone.utc) +copy_conditions.set_modified_since(mod_since) + +# Set unmodified condition, copy object unmodified since 1st April 2014. +# copy_conditions.set_unmodified_since(mod_since) + +# Set matching ETag condition, copy object which matches the following ETag. +# copy_conditions.set_match_etag("31624deb84149d2f8ef9c385918b653a") + +# Set matching ETag except condition, copy object which does not match the +# following ETag. +# copy_conditions.set_match_etag_except("31624deb84149d2f8ef9c385918b653a") +result = client.copy_object( + "my-bucket", + "my-object", + "/my-sourcebucket/my-sourceobject", + copy_conditions, +) +print(result.object_name, result.version_id) + +# copy an object from a bucket with replacing metadata. +metadata = {"test_meta_key": "test_meta_value"} +result = client.copy_object( + "my-bucket", + "my-object", + "/my-sourcebucket/my-sourceobject", + metadata=metadata, +) +print(result.object_name, result.version_id) diff --git a/testbed/minio__minio-py/examples/delete_bucket_lifecycle.py b/testbed/minio__minio-py/examples/delete_bucket_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..ececb49d3c69668e7d834cc0d8c8870d9cc76c16 --- /dev/null +++ b/testbed/minio__minio-py/examples/delete_bucket_lifecycle.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +client.delete_bucket_lifecycle("my-bucketname") diff --git a/testbed/minio__minio-py/examples/delete_bucket_replication.py b/testbed/minio__minio-py/examples/delete_bucket_replication.py new file mode 100644 index 0000000000000000000000000000000000000000..e28f04558d2b22b81be2405dbe8338eca0c8c58d --- /dev/null +++ b/testbed/minio__minio-py/examples/delete_bucket_replication.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +client.delete_bucket_replication("my-bucketname") diff --git a/testbed/minio__minio-py/examples/fget_object.py b/testbed/minio__minio-py/examples/fget_object.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c550a325cea84cf0ce324fe85cdcfe738a67a4 --- /dev/null +++ b/testbed/minio__minio-py/examples/fget_object.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-objectname +# are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Get a full object +try: + client.fget_object('my-bucketname', 'my-objectname', 'filepath') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/fput_object.py b/testbed/minio__minio-py/examples/fput_object.py new file mode 100644 index 0000000000000000000000000000000000000000..f80a115f574b261c67259e268301839a14de2d1c --- /dev/null +++ b/testbed/minio__minio-py/examples/fput_object.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname, my-objectname +# and my-filepath dummy values, please replace them with original values. + +from examples.progress import Progress +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Put an object 'my-objectname' with contents from 'my-filepath' +try: + client.fput_object('my-bucketname', 'my-objectname', 'my-filepath') +except ResponseError as err: + print(err) + +# Put an object 'my-objectname-csv' with contents from +# 'my-filepath.csv' as 'application/csv'. +try: + client.fput_object('my-bucketname', 'my-objectname-csv', + 'my-filepath.csv', content_type='application/csv') +except ResponseError as err: + print(err) + +# Put an object 'my-objectname-csv' with progress. +progress = Progress() +try: + client.fput_object('my-bucketname', 'my-objectname', + 'my-filepath', progress=progress) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/get_bucket_encryption.py b/testbed/minio__minio-py/examples/get_bucket_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..78377a5f452f5e6eb6f626a5e1f97dcb19de8129 --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_encryption.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY', + secure=True) + +try: + # Get current policy of bucket 'my-bucketname'. + print(client.get_bucket_encryption('my-bucketname')) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/get_bucket_lifecycle.py b/testbed/minio__minio-py/examples/get_bucket_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..7bab30fbec5f39fb6661e82f4483214b41e8688f --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_lifecycle.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +config = client.get_bucket_lifecycle("my-bucketname") diff --git a/testbed/minio__minio-py/examples/get_bucket_notification.py b/testbed/minio__minio-py/examples/get_bucket_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..84e9bbd037b58278c98e83d764796f7b2289acaa --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_notification.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +try: + # Get the notifications configuration for a bucket. + notification = client.get_bucket_notification('my-bucketname') + # If no notification is present on the bucket: + # notification == {} +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/get_bucket_policy.py b/testbed/minio__minio-py/examples/get_bucket_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1ef7e81930a63815bd17b50edcae053500ea32 --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_policy.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', secure=True, + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Make a new bucket +try: + # Get current policy of bucket 'my-bucketname'. + print(client.get_bucket_policy('my-bucketname')) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/get_bucket_replication.py b/testbed/minio__minio-py/examples/get_bucket_replication.py new file mode 100644 index 0000000000000000000000000000000000000000..4c688802b6afec13863c7c9e6f058cac96410a57 --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_replication.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +config = client.get_bucket_replication("my-bucketname") diff --git a/testbed/minio__minio-py/examples/get_bucket_versioning.py b/testbed/minio__minio-py/examples/get_bucket_versioning.py new file mode 100644 index 0000000000000000000000000000000000000000..4e41412876d2430c2e9b228fc3d7366bf215b32c --- /dev/null +++ b/testbed/minio__minio-py/examples/get_bucket_versioning.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +config = client.get_bucket_versioning("my-bucketname") +print(config.status) diff --git a/testbed/minio__minio-py/examples/get_object.py b/testbed/minio__minio-py/examples/get_object.py new file mode 100644 index 0000000000000000000000000000000000000000..93ba6a9216753ce416382f71da7d1b7587dd2676 --- /dev/null +++ b/testbed/minio__minio-py/examples/get_object.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname, my-objectname +# and my-testfile are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Get a full object +try: + data = client.get_object('my-bucketname', 'my-objectname') + with open('my-testfile', 'wb') as file_data: + for d in data.stream(32*1024): + file_data.write(d) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/list_buckets.py b/testbed/minio__minio-py/examples/list_buckets.py new file mode 100644 index 0000000000000000000000000000000000000000..193ff1fdaa33ce079d7c41d9cb4dd37a7a6efae8 --- /dev/null +++ b/testbed/minio__minio-py/examples/list_buckets.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID and YOUR-SECRETACCESSKEY are +# dummy values, please replace them with original values. + +from minio import Minio + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +buckets = client.list_buckets() + +for bucket in buckets: + print(bucket.name, bucket.creation_date) diff --git a/testbed/minio__minio-py/examples/list_objects.py b/testbed/minio__minio-py/examples/list_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..d76a7b1200522e2ba1d72a769c2ba867ce70a64d --- /dev/null +++ b/testbed/minio__minio-py/examples/list_objects.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-prefixname +# are dummy values, please replace them with original values. + +from minio import Minio + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# List all object paths in bucket that begin with my-prefixname. +objects = client.list_objects('my-bucketname', prefix='my-prefixname', + recursive=True) +for obj in objects: + print(obj.bucket_name, obj.object_name.encode('utf-8'), obj.last_modified, + obj.etag, obj.size, obj.content_type) + +# List all object paths in bucket that begin with my-prefixname using +# API V1 listing API. +objects = client.list_objects('my-bucketname', prefix='my-prefixname', + recursive=True, use_api_v1=True) +for obj in objects: + print(obj.bucket_name, obj.object_name.encode('utf-8'), obj.last_modified, + obj.etag, obj.size, obj.content_type) diff --git a/testbed/minio__minio-py/examples/listen_notification.py b/testbed/minio__minio-py/examples/listen_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..8a89f3d0d4640b4b521fa8b13dda419a9963e927 --- /dev/null +++ b/testbed/minio__minio-py/examples/listen_notification.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-testfile, my-bucketname and +# my-objectname are dummy values, please replace them with original values. + +from minio import Minio + +client = Minio('play.min.io', + access_key='Q3AM3UQ867SPQQA43P2F', + secret_key='zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG') + +# Put a file with default content-type. +events = client.listen_bucket_notification('my-bucket', 'my-prefix/', + '.my-suffix', + ['s3:ObjectCreated:*', + 's3:ObjectRemoved:*', + 's3:ObjectAccessed:*']) +for event in events: + print(event) diff --git a/testbed/minio__minio-py/examples/make_bucket.py b/testbed/minio__minio-py/examples/make_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c51122b110624241e648d0430b9eb3faea174a --- /dev/null +++ b/testbed/minio__minio-py/examples/make_bucket.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Make a new bucket +try: + client.make_bucket('my-bucketname') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/minio_with_assume_role_provider.py b/testbed/minio__minio-py/examples/minio_with_assume_role_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3d54d8ef91f732f67c824b1f6c8143906e833c --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_assume_role_provider.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import AssumeRoleProvider + +# STS endpoint usually point to MinIO server. +sts_endpoint = "http://STS-HOST:STS-PORT/" + +# Access key to fetch credentials from STS endpoint. +access_key = "YOUR-ACCESSKEY" + +# Secret key to fetch credentials from STS endpoint. +secret_key = "YOUR-SECRETACCESSKEY" + +# Role ARN if available. +role_arn = "ROLE-ARN" + +# Role session name if available. +role_session_name = "ROLE-SESSION-NAME" + +# External ID if available. +external_id = "EXTERNAL-ID" + +# Policy if available. +policy = "POLICY" + +# Region if available. +region = "REGION" + +provider = AssumeRoleProvider( + sts_endpoint, + access_key, + secret_key, + policy=policy, + region=region, + role_arn=role_arn, + role_session_name=role_session_name, + external_id=external_id, +) + +client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_aws_config_provider.py b/testbed/minio__minio-py/examples/minio_with_aws_config_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..204ef16107e15bd531c2c31e4e8ea22ac15d92d8 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_aws_config_provider.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import AWSConfigProvider + +client = Minio('s3.amazonaws.com', credentials=AWSConfigProvider()) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_chained_provider.py b/testbed/minio__minio-py/examples/minio_with_chained_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..dc955531c430f0003ba1bea9ee443c76e5653c59 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_chained_provider.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# A Chain credentials provider, provides a way of chaining multiple providers +# together and will pick the first available using priority order of the +# 'providers' list + +from minio import Minio +from minio.credentials import (AWSConfigProvider, ChainedProvider, + EnvAWSProvider, IamAwsProvider) + +client = Minio( + 's3.amazonaws.com', + credentials=ChainedProvider( + [ + IamAwsProvider(), + AWSConfigProvider(), + EnvAWSProvider(), + ] + ) +) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_client_grants_provider.py b/testbed/minio__minio-py/examples/minio_with_client_grants_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..c25097fccd3f80c2fd8cbcc4e33f62a1ce348a59 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_client_grants_provider.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import json + +import urllib3 + +from minio import Minio +from minio.credentials import ClientGrantsProvider + + +def get_jwt(client_id, client_secret, idp_client_id, idp_endpoint): + res = urllib3.PoolManager().request( + "POST", + idp_endpoint, + fields={ + "username": client_id, + "password": client_secret, + "grant_type": "password", + "client_id": idp_client_id, + }, + ) + + return json.loads(res.data.encode()) + + +# IDP endpoint. +idp_endpoint = ( + "https://IDP-HOST:IDP-PORT/auth/realms/master" + "/protocol/openid-connect/token" +) + +# Client-ID to fetch JWT. +client_id = "USER-ID" + +# Client secret to fetch JWT. +client_secret = "PASSWORD" + +# Client-ID of MinIO service on IDP. +idp_client_id = "MINIO-CLIENT-ID" + +# STS endpoint usually point to MinIO server. +sts_endpoint = "http://STS-HOST:STS-PORT/" + +provider = ClientGrantsProvider( + lambda: get_jwt(client_id, client_secret, idp_client_id, idp_endpoint), + sts_endpoint, +) + +client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_env_aws_provider.py b/testbed/minio__minio-py/examples/minio_with_env_aws_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..98e90209d27cbf518b9d98fd589e1c134235a9a0 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_env_aws_provider.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import EnvAWSProvider + +client = Minio('s3.amazonaws.com', credentials=EnvAWSProvider()) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_env_minio_provider.py b/testbed/minio__minio-py/examples/minio_with_env_minio_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..076d3b68ce5fb25f1756b636ad133702423faef2 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_env_minio_provider.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import EnvMinioProvider + +client = Minio("MINIO-HOST:MINIO-PORT", credentials=EnvMinioProvider()) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_iam_aws_provider.py b/testbed/minio__minio-py/examples/minio_with_iam_aws_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..7db88fbd65c208925f41e37fcf383388e4e7569a --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_iam_aws_provider.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import IamAwsProvider + +client = Minio('s3.amazonaws.com', credentials=IamAwsProvider()) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_ldap_identity_provider.py b/testbed/minio__minio-py/examples/minio_with_ldap_identity_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..047ac691c168c3d1ff202335a825d158bcbb9970 --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_ldap_identity_provider.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import LdapIdentityProvider + +# STS endpoint usually point to MinIO server. +sts_endpoint = "http://STS-HOST:STS-PORT/" + +# LDAP username. +ldap_username = "LDAP-USERNAME" + +# LDAP password. +ldap_password = "LDAP-PASSWORD" + +provider = LdapIdentityProvider(sts_endpoint, ldap_username, ldap_password) + +client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_minio_client_config_provider.py b/testbed/minio__minio-py/examples/minio_with_minio_client_config_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6aeb51a41ebda706b51494afa527dd802c6c2b --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_minio_client_config_provider.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from minio import Minio +from minio.credentials import MinioClientConfigProvider + +client = Minio( + "MINIO-HOST:MINIO-PORT", credentials=MinioClientConfigProvider(), +) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/minio_with_web_identity_provider.py b/testbed/minio__minio-py/examples/minio_with_web_identity_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a9d989fdcc1f6f2c5d54166419aa9f7239678d --- /dev/null +++ b/testbed/minio__minio-py/examples/minio_with_web_identity_provider.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import json + +import urllib3 + +from minio import Minio +from minio.credentials import WebIdentityProvider + + +def get_jwt(client_id, client_secret, idp_client_id, idp_endpoint): + res = urllib3.PoolManager().request( + "POST", + idp_endpoint, + fields={ + "username": client_id, + "password": client_secret, + "grant_type": "password", + "client_id": idp_client_id, + }, + ) + + return json.loads(res.data.encode()) + + +# IDP endpoint. +idp_endpoint = ( + "https://IDP-HOST:IDP-PORT/auth/realms/master" + "/protocol/openid-connect/token" +) + +# Client-ID to fetch JWT. +client_id = "USER-ID" + +# Client secret to fetch JWT. +client_secret = "PASSWORD" + +# Client-ID of MinIO service on IDP. +idp_client_id = "MINIO-CLIENT-ID" + +# STS endpoint usually point to MinIO server. +sts_endpoint = "http://STS-HOST:STS-PORT/" + +# Role ARN if available. +role_arn = "ROLE-ARN" + +# Role session name if available. +role_session_name = "ROLE-SESSION-NAME" + +provider = WebIdentityProvider( + lambda: get_jwt(client_id, client_secret, idp_client_id, idp_endpoint), + sts_endpoint, + role_arn=role_arn, + role_session_name=role_session_name, +) + +client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) + +# Get information of an object. +stat = client.stat_object("my-bucketname", "my-objectname") +print(stat) diff --git a/testbed/minio__minio-py/examples/presigned_get_object.py b/testbed/minio__minio-py/examples/presigned_get_object.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8a13abdc7cfdd8b08e990a4dfbbff838b95fc5 --- /dev/null +++ b/testbed/minio__minio-py/examples/presigned_get_object.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-objectname +# are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# presigned get object URL for object name, expires in 7 days. +try: + print(client.presigned_get_object('my-bucketname', 'my-objectname')) +# Response error is still possible since internally presigned does get +# bucket location. +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/presigned_post_policy.py b/testbed/minio__minio-py/examples/presigned_post_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb99abbd23704b7fabc525d32c7ac9433a0fbdb --- /dev/null +++ b/testbed/minio__minio-py/examples/presigned_post_policy.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: my-bucketname, my-objectname, YOUR-ACCESSKEYID, and +# YOUR-SECRETACCESSKEY are dummy values, please replace them with original +# values. + +from datetime import datetime, timedelta + +from minio import Minio, PostPolicy +from minio.error import ResponseError + +post_policy = PostPolicy() +# set bucket name location for uploads. +post_policy.set_bucket_name('my-bucketname') +# set key prefix for all incoming uploads. +post_policy.set_key_startswith('my-objectname') +# set content length for incoming uploads. +post_policy.set_content_length_range(10, 1024) + +# set expiry 10 days into future. +expires_date = datetime.utcnow() + timedelta(days=10) +post_policy.set_expires(expires_date) + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +try: + url, signed_form_data = client.presigned_post_policy(post_policy) + + curl_cmd = ( + ['curl -X POST {0}'.format(url)] + + ['-F {0}={1}'.format(k, v) for k, v in signed_form_data.items()] + + ['-F file=@'] + ) + + # print curl command to upload files. + print(' '.join(curl_cmd)) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/presigned_put_object.py b/testbed/minio__minio-py/examples/presigned_put_object.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c7fdf0b6fadcf116579ac8b5919fe711e03f54 --- /dev/null +++ b/testbed/minio__minio-py/examples/presigned_put_object.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-objectname +# are dummy values, please replace them with original values. + +import datetime + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# presigned Put object URL for an object name, expires in 3 days. +try: + print(client.presigned_put_object('my-bucketname', + 'my-objectname', + datetime.timedelta(days=3))) +# Response error is still possible since internally presigned does get +# bucket location. +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/progress.py b/testbed/minio__minio-py/examples/progress.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5316f8bd73a2460fd8a26a0ef155109d002c5e --- /dev/null +++ b/testbed/minio__minio-py/examples/progress.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module implements a progress printer while communicating with MinIO server + +:copyright: (c) 2018 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +import sys +import time +from queue import Empty, Queue +from threading import Thread + +_BAR_SIZE = 20 +_KILOBYTE = 1024 +_FINISHED_BAR = '#' +_REMAINING_BAR = '-' + +_UNKNOWN_SIZE = '?' +_STR_MEGABYTE = ' MB' + +_HOURS_OF_ELAPSED = '%d:%02d:%02d' +_MINUTES_OF_ELAPSED = '%02d:%02d' + +_RATE_FORMAT = '%5.2f' +_PERCENTAGE_FORMAT = '%3d%%' +_HUMANINZED_FORMAT = '%0.2f' + +_DISPLAY_FORMAT = '|%s| %s/%s %s [elapsed: %s left: %s, %s MB/sec]' + +_REFRESH_CHAR = '\r' + + +class Progress(Thread): + """ + Constructs a :class:`Progress` object. + :param interval: Sets the time interval to be displayed on the screen. + :param stdout: Sets the standard output + + :return: :class:`Progress` object + """ + + def __init__(self, interval=1, stdout=sys.stdout): + Thread.__init__(self) + self.daemon = True + self.total_length = 0 + self.interval = interval + self.object_name = None + + self.last_printed_len = 0 + self.current_size = 0 + + self.display_queue = Queue() + self.initial_time = time.time() + self.stdout = stdout + self.start() + + def set_meta(self, total_length, object_name): + """ + Metadata settings for the object. This method called before uploading + object + :param total_length: Total length of object. + :param object_name: Object name to be showed. + """ + self.total_length = total_length + self.object_name = object_name + self.prefix = self.object_name + ': ' if self.object_name else '' + + def run(self): + displayed_time = 0 + while True: + try: + # display every interval secs + task = self.display_queue.get(timeout=self.interval) + except Empty: + elapsed_time = time.time() - self.initial_time + if elapsed_time > displayed_time: + displayed_time = elapsed_time + self.print_status(current_size=self.current_size, + total_length=self.total_length, + displayed_time=displayed_time, + prefix=self.prefix) + continue + + current_size, total_length = task + displayed_time = time.time() - self.initial_time + self.print_status(current_size=current_size, + total_length=total_length, + displayed_time=displayed_time, + prefix=self.prefix) + self.display_queue.task_done() + if current_size == total_length: + self.done_progress() + + def update(self, size): + """ + Update object size to be showed. This method called while uploading + :param size: Object size to be showed. The object size should be in + bytes. + """ + if not isinstance(size, int): + raise ValueError('{} type can not be displayed. ' + 'Please change it to Int.'.format(type(size))) + + self.current_size += size + self.display_queue.put((self.current_size, self.total_length)) + + def done_progress(self): + self.total_length = 0 + self.object_name = None + self.last_printed_len = 0 + self.current_size = 0 + + def print_status(self, current_size, total_length, displayed_time, prefix): + formatted_str = prefix + format_string( + current_size, total_length, displayed_time) + self.stdout.write(_REFRESH_CHAR + formatted_str + ' ' * + max(self.last_printed_len - len(formatted_str), 0)) + self.stdout.flush() + self.last_printed_len = len(formatted_str) + + +def seconds_to_time(seconds): + """ + Consistent time format to be displayed on the elapsed time in screen. + :param seconds: seconds + """ + minutes, seconds = divmod(int(seconds), 60) + hours, m = divmod(minutes, 60) + if hours: + return _HOURS_OF_ELAPSED % (hours, m, seconds) + else: + return _MINUTES_OF_ELAPSED % (m, seconds) + + +def format_string(current_size, total_length, elapsed_time): + """ + Consistent format to be displayed on the screen. + :param current_size: Number of finished object size + :param total_length: Total object size + :param elapsed_time: number of seconds passed since start + """ + + n_to_mb = current_size / _KILOBYTE / _KILOBYTE + elapsed_str = seconds_to_time(elapsed_time) + + rate = _RATE_FORMAT % ( + n_to_mb / elapsed_time) if elapsed_time else _UNKNOWN_SIZE + frac = float(current_size) / total_length + bar_length = int(frac * _BAR_SIZE) + bar = (_FINISHED_BAR * bar_length + + _REMAINING_BAR * (_BAR_SIZE - bar_length)) + percentage = _PERCENTAGE_FORMAT % (frac * 100) + left_str = ( + seconds_to_time( + elapsed_time / current_size * (total_length - current_size)) + if current_size else _UNKNOWN_SIZE) + + humanized_total = _HUMANINZED_FORMAT % ( + total_length / _KILOBYTE / _KILOBYTE) + _STR_MEGABYTE + humanized_n = _HUMANINZED_FORMAT % n_to_mb + _STR_MEGABYTE + + return _DISPLAY_FORMAT % (bar, humanized_n, humanized_total, percentage, + elapsed_str, left_str, rate) diff --git a/testbed/minio__minio-py/examples/put_and_get_encrypted_object.py b/testbed/minio__minio-py/examples/put_and_get_encrypted_object.py new file mode 100644 index 0000000000000000000000000000000000000000..931c8c45cec43b7aee7dde9491b3639b4a77eebf --- /dev/null +++ b/testbed/minio__minio-py/examples/put_and_get_encrypted_object.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +import base64 +import hashlib +from io import BytesIO + +from minio.api import Minio + +AWSAccessKeyId = '' +AWSSecretKey = '' + +STORAGE_ENDPOINT = 's3.amazonaws.com' +STORAGE_BUCKET = '' + + +def main(): + content = BytesIO(b'Hello again') + + key = b'32byteslongsecretkeymustprovided' + encryption_key = base64.b64encode(key).decode() + encryption_key_md5 = base64.b64encode(hashlib.md5(key).digest()).decode() + + minio = Minio(STORAGE_ENDPOINT, access_key=AWSAccessKeyId, + secret_key=AWSSecretKey) + + # Put object with special headers which encrypt object in S3 with provided + # key + minio.put_object( + STORAGE_BUCKET, 'test_crypt.txt', content, content.getbuffer().nbytes, + metadata={ + 'x-amz-server-side-encryption-customer-algorithm': 'AES256', + 'x-amz-server-side-encryption-customer-key': encryption_key, + 'x-amz-server-side-encryption-customer-key-MD5': encryption_key_md5 + }) + + # Get decrypted object with same headers + obj = minio.get_object( + STORAGE_BUCKET, 'test_crypt1.txt', + request_headers={ + 'x-amz-server-side-encryption-customer-algorithm': 'AES256', + 'x-amz-server-side-encryption-customer-key': encryption_key, + 'x-amz-server-side-encryption-customer-key-MD5': encryption_key_md5 + }) + + print(obj.read()) + + +if __name__ == '__main__': + main() diff --git a/testbed/minio__minio-py/examples/put_and_get_object_sse-c.py b/testbed/minio__minio-py/examples/put_and_get_object_sse-c.py new file mode 100644 index 0000000000000000000000000000000000000000..e07c25d278b4dbb40137aa9a271a9d4c0eead77c --- /dev/null +++ b/testbed/minio__minio-py/examples/put_and_get_object_sse-c.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from io import BytesIO + +from minio.api import Minio +from minio.sse import SseCustomerKey + +AWSAccessKeyId = 'YOUR-ACCESSKEYID' +AWSSecretKey = 'YOUR-SECRETACCESSKEY' + +STORAGE_ENDPOINT = 's3.amazonaws.com' +STORAGE_BUCKET = 'test-encryption-bucket' + + +def main(): + content = BytesIO(b'Hello again') + + minio = Minio(STORAGE_ENDPOINT, access_key=AWSAccessKeyId, + secret_key=AWSSecretKey) + + # Create an SSE-C object with a 32 byte customer_key + key = b'32byteslongsecretkeymustprovided' + ssec = SseCustomerKey(key) + + # Put object with SSE_C object passed as a param + minio.put_object(STORAGE_BUCKET, 'test_crypt.txt', content, + content.getbuffer().nbytes, sse=ssec) + + # Copy encrypted object on Server-Side from Source to Destination + obj = minio.copy_object(STORAGE_BUCKET, 'test_crypt_copy.txt', + STORAGE_BUCKET + '/test_crypt.txt', + source_sse=ssec, + sse=ssec) + + # Get decrypted object with SSE_C object passed in as param + obj = minio.get_object(STORAGE_BUCKET, 'test_crypt_copy.txt', + sse=ssec) + + print(obj.read()) + + +if __name__ == '__main__': + main() diff --git a/testbed/minio__minio-py/examples/put_object.py b/testbed/minio__minio-py/examples/put_object.py new file mode 100644 index 0000000000000000000000000000000000000000..308f9c7f6cd0ac80dcc766a45bbf5958a46db12d --- /dev/null +++ b/testbed/minio__minio-py/examples/put_object.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-testfile, my-bucketname and +# my-objectname are dummy values, please replace them with original values. + +import os + +from examples.progress import Progress +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Put a file with default content-type. +try: + with open('my-testfile', 'rb') as file_data: + file_stat = os.stat('my-testfile') + client.put_object('my-bucketname', 'my-objectname', + file_data, file_stat.st_size) +except ResponseError as err: + print(err) + +# Put a file with 'application/csv' +try: + with open('my-testfile.csv', 'rb') as file_data: + file_stat = os.stat('my-testfile.csv') + client.put_object('my-bucketname', 'my-objectname', file_data, + file_stat.st_size, content_type='application/csv') +except ResponseError as err: + print(err) + +# Put a file with progress. +progress = Progress() +try: + with open('my-testfile', 'rb') as file_data: + file_stat = os.stat('my-testfile') + client.put_object('my-bucketname', 'my-objectname', + file_data, file_stat.st_size, progress=progress) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/put_object_sse-kms.py b/testbed/minio__minio-py/examples/put_object_sse-kms.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ad10c4b073e2e8a362447b8d83214a6b0f69fb --- /dev/null +++ b/testbed/minio__minio-py/examples/put_object_sse-kms.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from io import BytesIO + +from minio.api import Minio +from minio.sse import SseKMS + +AWSAccessKeyId = 'YOUR-ACCESSKEYID' +AWSSecretKey = 'YOUR-SECRETACCESSKEY' + +STORAGE_ENDPOINT = 's3.amazonaws.com' +STORAGE_BUCKET = 'test-encryption-bucket' + + +def main(): + minio = Minio(STORAGE_ENDPOINT, access_key=AWSAccessKeyId, + secret_key=AWSSecretKey) + + content = BytesIO(b'Some Data to be stored') + + key_id = 'YOUR-KMS-KEY' + context = {'Key1': 'Value1', 'Key2': 'Value2'} + + # Create an SSE-KMS object with a Valid KMS key_id and context + sse_kms_obj = SseKMS(key_id, context) + + # Put object with special headers from SSE_C object which encrypt object in + # S3 with provided key + minio.put_object(STORAGE_BUCKET, 'test_crypt.txt', content, + content.getbuffer().nbytes, sse=sse_kms_obj) + + # Get decrypted object with same headers + obj = minio.get_object(STORAGE_BUCKET, 'test_crypt.txt') + + print(obj.read()) + + +if __name__ == '__main__': + main() diff --git a/testbed/minio__minio-py/examples/put_object_sse-s3.py b/testbed/minio__minio-py/examples/put_object_sse-s3.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ebfe048f6eae4af490b38b7bd40617f24b16af --- /dev/null +++ b/testbed/minio__minio-py/examples/put_object_sse-s3.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from io import BytesIO + +from minio.api import Minio +from minio.sse import SseS3 + +AWSAccessKeyId = 'YOUR-ACCESSKEYID' +AWSSecretKey = 'YOUR-SECRETACCESSKEY' + +STORAGE_ENDPOINT = 's3.amazonaws.com' +STORAGE_BUCKET = 'test-encryption-bucket' + + +def main(): + minio = Minio(STORAGE_ENDPOINT, access_key=AWSAccessKeyId, + secret_key=AWSSecretKey) + + content = BytesIO(b'Hello again') + + # Create an SSE_S3 object + sse_s3_obj = SseS3() + + # Put object with from SSE_S3 object which encrypt object in S3 with + # provided key + minio.put_object(STORAGE_BUCKET, 'test_crypt.txt', content, + content.getbuffer().nbytes, sse=sse_s3_obj) + + # Get decrypted object with same headers + obj = minio.get_object(STORAGE_BUCKET, 'test_crypt.txt') + + print(obj.read()) + + +if __name__ == '__main__': + main() diff --git a/testbed/minio__minio-py/examples/remove_all_bucket_notification.py b/testbed/minio__minio-py/examples/remove_all_bucket_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..0a222c8d31b51104c1004d79d08b2332fdb64377 --- /dev/null +++ b/testbed/minio__minio-py/examples/remove_all_bucket_notification.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +try: + # Remove all notification config for a bucket. + client.remove_all_bucket_notification('my-bucketname') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/remove_bucket.py b/testbed/minio__minio-py/examples/remove_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9ecbd77147ec624a5328e1fbad6568ac5b12b3 --- /dev/null +++ b/testbed/minio__minio-py/examples/remove_bucket.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Remove a bucket +# This operation will only work if your bucket is empty. +try: + client.remove_bucket('my-bucketname') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/remove_bucket_encryption.py b/testbed/minio__minio-py/examples/remove_bucket_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..b61860229b6e5ccba1c88885dbb9deabdbd7d411 --- /dev/null +++ b/testbed/minio__minio-py/examples/remove_bucket_encryption.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY', + secure=True) + +try: + # Delete default encryption configuration on bucket 'my-bucketname'. + client.delete_bucket_encryption('my-bucketname') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/remove_object.py b/testbed/minio__minio-py/examples/remove_object.py new file mode 100644 index 0000000000000000000000000000000000000000..3320e27079dfb1cb7b284a86af1394de86f10376 --- /dev/null +++ b/testbed/minio__minio-py/examples/remove_object.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-objectname +# are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Remove an object. +try: + client.remove_object('my-bucketname', 'my-objectname') +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/remove_objects.py b/testbed/minio__minio-py/examples/remove_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..aa47a68a26ecbff8b4f950a05760dc4dcf16c943 --- /dev/null +++ b/testbed/minio__minio-py/examples/remove_objects.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-prefix +# are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Remove a prefix recursively. +try: + names = map( + lambda x: x.object_name, + client.list_objects('my-bucketname', 'my-prefix', recursive=True) + ) + for err in client.remove_objects('my-bucketname', names): + print("Deletion Error: {}".format(err)) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/select_object_content.py b/testbed/minio__minio-py/examples/select_object_content.py new file mode 100644 index 0000000000000000000000000000000000000000..8ebfd1ed20815c35f458ed0cae5140c415395bf6 --- /dev/null +++ b/testbed/minio__minio-py/examples/select_object_content.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from minio import Minio +from minio.selectrequest import (CSVInputSerialization, CSVOutputSerialization, + SelectRequest) + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEY', + secret_key='YOUR-SECRETKEY') + +request = SelectRequest( + "select * from s3object", + CSVInputSerialization(), + CSVOutputSerialization(), + request_progress=True, +) +data = client.select_object_content('my-bucket', 'my-object', request) +with open('my-record-file', 'w') as record_data: + for d in data.stream(10*1024): + record_data.write(d) + # Get the stats + print(data.stats()) diff --git a/testbed/minio__minio-py/examples/set_bucket_encryption.py b/testbed/minio__minio-py/examples/set_bucket_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..daad2a9ab3f139902ea0cc98901846b37071b0b0 --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_encryption.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY', + secure=True) + +try: + # Set default encryption configuration for bucket 'my-bucketname' + ENC_CONFIG = { + 'ServerSideEncryptionConfiguration': { + 'Rule': [ + { + 'ApplyServerSideEncryptionByDefault': { + 'SSEAlgorithm': 'AES256' + } + } + ] + } + } + + client.put_bucket_encryption('my-bucketname', ENC_CONFIG) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/set_bucket_lifecycle.py b/testbed/minio__minio-py/examples/set_bucket_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..de9840f105104b4d993755b0484260a62bcc8145 --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_lifecycle.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.commonconfig import ENABLED, Filter +from minio.lifecycleconfig import Expiration, LifecycleConfig, Rule + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +config = LifecycleConfig( + [ + Rule( + ENABLED, + rule_filter=Filter(prefix="logs/"), + rule_id="rule2", + expiration=Expiration(days=365), + ), + ], +) +client.set_bucket_lifecycle("my-bucketname", config) diff --git a/testbed/minio__minio-py/examples/set_bucket_notification.py b/testbed/minio__minio-py/examples/set_bucket_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..17f6047e63c1ff613bd278aefc351d11dad06adb --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_notification.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ArgumentError, ResponseError + +client = Minio('s3.amazonaws.com', secure=True, + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +notification = { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix', + 'Value': 'abc' + } + ] + } + } + } + ], + 'TopicConfigurations': [ + { + 'Arn': 'arn2', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ], + 'CloudFunctionConfigurations': [ + { + 'Arn': 'arn3', + 'Events': ['s3:ObjectRemoved:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': '.jpg' + } + ] + } + } + } + ] +} + +try: + client.set_bucket_notification('my-bucketname', notification) +except ResponseError as err: + # handle error response from service. + print(err) +except (ArgumentError, TypeError) as err: + # should happen only during development. Fix the notification argument + print(err) diff --git a/testbed/minio__minio-py/examples/set_bucket_policy.py b/testbed/minio__minio-py/examples/set_bucket_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..38a40b52d86e531483d74e0994f1aeab3e078870 --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_policy.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +import json + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Make a new bucket +try: + # Set bucket policy to read-only for bucket 'my-bucketname' + policy_read_only = { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetBucketLocation", + "Resource": "arn:aws:s3:::my-bucketname" + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::my-bucketname" + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::my-bucketname/*" + } + ] + } + client.set_bucket_policy('my-bucketname', json.dumps(policy_read_only)) + + # Set bucket policy to read-write for bucket 'my-bucketname' + policy_read_write = { + "Version": "2012-10-17", + "Statement": [ + { + "Action": ["s3:GetBucketLocation"], + "Sid": "", + "Resource": ["arn:aws:s3:::my-bucketname"], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListBucket"], + "Sid": "", + "Resource": ["arn:aws:s3:::my-bucketname"], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListBucketMultipartUploads"], + "Sid": "", + "Resource": ["arn:aws:s3:::my-bucketname"], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListMultipartUploadParts", + "s3:GetObject", + "s3:AbortMultipartUpload", + "s3:DeleteObject", + "s3:PutObject"], + "Sid": "", + "Resource": ["arn:aws:s3:::my-bucketname/*"], + "Effect": "Allow", + "Principal": {"AWS": "*"} + } + ] + } + client.set_bucket_policy('my-bucketname', json.dumps(policy_read_write)) + + # Set bucket policy to write-only for bucket 'my-bucketname' + policy_write_only = { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetBucketLocation", + "Resource": "arn:aws:s3:::my-bucketname" + }, + {"Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:ListBucketMultipartUploads", + "Resource": "arn:aws:s3:::my-bucketname" + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": [ + "s3:ListMultipartUploadParts", + "s3:AbortMultipartUpload", + "s3:DeleteObject", + "s3:PutObject"], + "Resource":"arn:aws:s3:::my-bucketname/*" + } + ] + } + client.set_bucket_policy('my-bucketname', json.dumps(policy_write_only)) + +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/examples/set_bucket_replication.py b/testbed/minio__minio-py/examples/set_bucket_replication.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2133f87aff3c84dcda8bd52552acb023863107 --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_replication.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.commonconfig import DISABLED, ENABLED, AndOperator, Filter +from minio.replicationconfig import (DeleteMarkerReplication, Destination, + ReplicationConfig, Rule) + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +config = ReplicationConfig( + "REPLACE-WITH-ACTUAL-ROLE", + [ + Rule( + Destination( + "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", + ), + ENABLED, + delete_marker_replication=DeleteMarkerReplication( + DISABLED, + ), + rule_filter=Filter( + AndOperator( + "TaxDocs", + {"key1": "value1", "key2": "value2"}, + ), + ), + rule_id="rule1", + priority=1, + ), + ], +) +client.set_bucket_replication("my-bucketname", config) diff --git a/testbed/minio__minio-py/examples/set_bucket_versioning.py b/testbed/minio__minio-py/examples/set_bucket_versioning.py new file mode 100644 index 0000000000000000000000000000000000000000..78af5761f50d995c0c2bae905ade6baf85643972 --- /dev/null +++ b/testbed/minio__minio-py/examples/set_bucket_versioning.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage. +# Copyright (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are +# dummy values, please replace them with original values. + +from minio import Minio +from minio.commonconfig import ENABLED +from minio.versioningconfig import VersioningConfig + +client = Minio( + "play.min.io", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", +) + +client.set_bucket_versioning("my-bucketname", VersioningConfig(ENABLED)) diff --git a/testbed/minio__minio-py/examples/stat_object.py b/testbed/minio__minio-py/examples/stat_object.py new file mode 100644 index 0000000000000000000000000000000000000000..86ebcdda8b4e3099f48740bf7f2f1b0191463bb4 --- /dev/null +++ b/testbed/minio__minio-py/examples/stat_object.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-objectname +# are dummy values, please replace them with original values. + +from minio import Minio +from minio.error import ResponseError + +client = Minio('s3.amazonaws.com', + access_key='YOUR-ACCESSKEYID', + secret_key='YOUR-SECRETACCESSKEY') + +# Fetch stats on your object. +try: + print(client.stat_object('my-bucketname', 'my-objectname')) +except ResponseError as err: + print(err) diff --git a/testbed/minio__minio-py/minio/__init__.py b/testbed/minio__minio-py/minio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0925cfddf278f350b2872ba11e3fd922e26056 --- /dev/null +++ b/testbed/minio__minio-py/minio/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016, 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio - MinIO Python Library for Amazon S3 Compatible Cloud Storage +~~~~~~~~~~~~~~~~~~~~~ + + >>> import minio + >>> minio = Minio('https://s3.amazonaws.com') + >>> for bucket in minio.list_buckets(): + ... print(bucket.name) + +:copyright: (c) 2015, 2016, 2017 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. +""" + +__title__ = 'minio-py' +__author__ = 'MinIO, Inc.' +__version__ = '7.0.0' +__license__ = 'Apache 2.0' +__copyright__ = 'Copyright 2015, 2016, 2017, 2018, 2019, 2020 MinIO, Inc.' + +# pylint: disable=unused-import +from .api import Minio +from .copy_conditions import CopyConditions +from .definitions import Bucket, Object +from .error import InvalidResponseError, S3Error, ServerError +from .post_policy import PostPolicy diff --git a/testbed/minio__minio-py/minio/api.py b/testbed/minio__minio-py/minio/api.py new file mode 100644 index 0000000000000000000000000000000000000000..c01cfbf4534cbe0fba13d8307feb70c84a74d52c --- /dev/null +++ b/testbed/minio__minio-py/minio/api.py @@ -0,0 +1,2088 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2015, 2016, 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: disable=too-many-lines + +""" +minio.api +~~~~~~~~~~~~ + +This module implements the API. + +:copyright: (c) 2015, 2016, 2017 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from __future__ import absolute_import + +import itertools +import json +import os +import platform +from datetime import datetime, timedelta +from threading import Thread +from urllib.parse import urlunsplit +from xml.etree import ElementTree as ET + +import certifi +import dateutil.parser +import urllib3 + +from . import __title__, __version__ +from .credentials import StaticProvider +from .definitions import BaseURL, Object, ObjectWriteResult, Part +from .error import InvalidResponseError, S3Error, ServerError +from .helpers import (amzprefix_user_metadata, check_bucket_name, + check_non_empty_string, check_sse, check_ssec, + get_part_info, headers_to_strings, is_amz_header, + is_supported_header, is_valid_notification_config, + is_valid_policy_type, makedirs, md5sum_hash, quote, + read_part_data, sha256_hash, strptime_rfc3339) +from .lifecycleconfig import LifecycleConfig +from .parsers import (parse_error_response, parse_get_bucket_notification, + parse_list_buckets, parse_list_multipart_uploads, + parse_list_object_versions, parse_list_objects, + parse_list_objects_v2, parse_list_parts, + parse_multi_delete_response, + parse_multipart_upload_result, + parse_new_multipart_upload) +from .replicationconfig import ReplicationConfig +from .select import SelectObjectReader +from .selectrequest import SelectRequest +from .signer import (AMZ_DATE_FORMAT, SIGN_V4_ALGORITHM, get_credential_string, + post_presign_v4, presign_v4, sign_v4_s3) +from .sse import SseCustomerKey +from .thread_pool import ThreadPool +from .versioningconfig import VersioningConfig +from .xml import Element, SubElement, findtext, marshal, unmarshal +from .xml_marshal import (marshal_bucket_notifications, + marshal_complete_multipart, + xml_marshal_bucket_encryption, + xml_marshal_delete_objects, xml_to_dict) + +try: + from json.decoder import JSONDecodeError +except ImportError: + JSONDecodeError = ValueError + + +_DEFAULT_USER_AGENT = "MinIO ({os}; {arch}) {lib}/{ver}".format( + os=platform.system(), arch=platform.machine(), + lib=__title__, ver=__version__, +) + + +class Minio: # pylint: disable=too-many-public-methods + """ + Simple Storage Service (aka S3) client to perform bucket and object + operations. + + :param endpoint: Hostname of a S3 service. + :param access_key: Access key (aka user ID) of your account in S3 service. + :param secret_key: Secret Key (aka password) of your account in S3 service. + :param session_token: Session token of your account in S3 service. + :param secure: Flag to indicate to use secure (TLS) connection to S3 + service or not. + :param region: Region name of buckets in S3 service. + :param http_client: Customized HTTP client. + :param credentials: Credentials provider of your account in S3 service. + :return: :class:`Minio ` object + + Example:: + client = Minio('play.min.io') + client = Minio('s3.amazonaws.com', 'ACCESS_KEY', 'SECRET_KEY') + client = Minio('play.min.io', 'ACCESS_KEY', 'SECRET_KEY', + region='us-east-1') + + **NOTE on concurrent usage:** The `Minio` object is thread safe when using + the Python `threading` library. Specifically, it is **NOT** safe to share + it between multiple processes, for example when using + `multiprocessing.Pool`. The solution is simply to create a new `Minio` + object in each process, and not share it between processes. + + """ + + # pylint: disable=too-many-function-args + def __init__(self, endpoint, access_key=None, + secret_key=None, + session_token=None, + secure=True, + region=None, + http_client=None, + credentials=None): + # Validate http client has correct base class. + if http_client and not isinstance( + http_client, + urllib3.poolmanager.PoolManager): + raise ValueError( + "HTTP client should be instance of " + "`urllib3.poolmanager.PoolManager`" + ) + + self._region_map = dict() + self._base_url = BaseURL( + ("https://" if secure else "http://") + endpoint, + region, + ) + self._user_agent = _DEFAULT_USER_AGENT + self._trace_stream = None + if access_key: + credentials = StaticProvider(access_key, secret_key, session_token) + self._provider = credentials + + # Load CA certificates from SSL_CERT_FILE file if set + ca_certs = os.environ.get('SSL_CERT_FILE') or certifi.where() + self._http = http_client or urllib3.PoolManager( + timeout=urllib3.Timeout.DEFAULT_TIMEOUT, + maxsize=10, + cert_reqs='CERT_REQUIRED', + ca_certs=ca_certs, + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504] + ) + ) + + def _handle_redirect_response( + self, method, bucket_name, response, retry=False, + ): + """ + Handle redirect response indicates whether retry HEAD request + on failure. + """ + code, message = { + 301: ("PermanentRedirect", "Moved Permanently"), + 307: ("Redirect", "Temporary redirect"), + 400: ("BadRequest", "Bad request"), + }.get(response.status, (None, None)) + region = response.getheader("x-amz-bucket-region") + if message and region: + message += "; use region " + region + + if ( + retry and region and method == "HEAD" and bucket_name and + self._region_map.get(bucket_name) + ): + code, message = ("RetryHead", None) + + return code, message + + def _build_headers(self, host, headers, body, creds): + """Build headers with given parameters.""" + headers = headers or {} + md5sum_added = headers.get("Content-MD5") + headers["Host"] = host + headers["User-Agent"] = self._user_agent + sha256 = None + md5sum = None + + if body: + headers["Content-Length"] = str(len(body)) + if creds: + if self._base_url.is_https: + sha256 = "UNSIGNED-PAYLOAD" + md5sum = None if md5sum_added else md5sum_hash(body) + else: + sha256 = sha256_hash(body) + else: + md5sum = None if md5sum_added else md5sum_hash(body) + if md5sum: + headers["Content-MD5"] = md5sum + if sha256: + headers["x-amz-content-sha256"] = sha256 + if creds and creds.session_token: + headers["X-Amz-Security-Token"] = creds.session_token + date = datetime.utcnow() + headers["x-amz-date"] = date.strftime(AMZ_DATE_FORMAT) + return headers, date + + def _url_open( # pylint: disable=too-many-branches + self, + method, + region, + bucket_name=None, + object_name=None, + body=None, + headers=None, + query_params=None, + preload_content=True, + ): + """Execute HTTP request.""" + creds = self._provider.retrieve() if self._provider else None + trace_body = isinstance(body, str) + body = body.encode() if trace_body else body + url = self._base_url.build( + method, + region, + bucket_name=bucket_name, + object_name=object_name, + query_params=query_params, + ) + headers, date = self._build_headers(url.netloc, headers, body, creds) + if creds: + headers = sign_v4_s3( + method, + url, + region, + headers, + creds, + headers.get("x-amz-content-sha256"), + date, + ) + + if self._trace_stream: + self._trace_stream.write("---------START-HTTP---------\n") + self._trace_stream.write( + "{0} {1}{2}{3} HTTP/1.1\n".format( + method, + url.path, + "?" if url.query else "", + url.query or "", + ), + ) + self._trace_stream.write( + headers_to_strings(headers, titled_key=True), + ) + self._trace_stream.write("\n") + if trace_body: + self._trace_stream.write(body.decode()) + self._trace_stream.write("\n") + + response = self._http.urlopen( + method, + urlunsplit(url), + body=body, + headers=headers, + preload_content=preload_content, + ) + + if self._trace_stream: + self._trace_stream.write("HTTP/1.1 {0}\n".format(response.status)) + self._trace_stream.write( + headers_to_strings(response.getheaders()), + ) + self._trace_stream.write("\n") + + if response.status in [200, 204, 206]: + if self._trace_stream: + self._trace_stream.write("----------END-HTTP----------\n") + return response + + response.read(cache_content=True) + if not preload_content: + response.release_conn() + + if self._trace_stream and method != "HEAD" and response.data: + self._trace_stream.write(response.data.decode()) + self._trace_stream.write("\n") + + if ( + method != "HEAD" and + "application/xml" not in response.getheader( + "content-type", "", + ).split(";") + ): + if self._trace_stream: + self._trace_stream.write("----------END-HTTP----------\n") + raise InvalidResponseError( + response.status, + response.getheader("content-type"), + response.data.decode() if response.data else None, + ) + + if not response.data and method != "HEAD": + if self._trace_stream: + self._trace_stream.write("----------END-HTTP----------\n") + raise InvalidResponseError( + response.status, + response.getheader("content-type"), + None, + ) + + response_error = ( + parse_error_response(response) + if response.data else None + ) + + if self._trace_stream: + self._trace_stream.write("----------END-HTTP----------\n") + + error_map = { + 301: lambda: self._handle_redirect_response( + method, bucket_name, response, True, + ), + 307: lambda: self._handle_redirect_response( + method, bucket_name, response, True, + ), + 400: lambda: self._handle_redirect_response( + method, bucket_name, response, True, + ), + 403: lambda: ("AccessDenied", "Access denied"), + 404: lambda: ( + ("NoSuchKey", "Object does not exist") + if object_name + else ("NoSuchBucket", "Bucket does not exist") + if bucket_name + else ("ResourceNotFound", "Request resource not found") + ), + 405: lambda: ( + "MethodNotAllowed", + "The specified method is not allowed against this resource", + ), + 409: lambda: ( + ("NoSuchBucket", "Bucket does not exist") + if bucket_name + else ("ResourceConflict", "Request resource conflicts"), + ), + 501: lambda: ( + "MethodNotAllowed", + "The specified method is not allowed against this resource", + ), + } + + if not response_error: + func = error_map.get(response.status) + code, message = func() if func else (None, None) + if not code: + raise ServerError( + "server failed with HTTP status code {}".format( + response.status, + ), + ) + response_error = S3Error( + code, + message, + url.path, + response.getheader("x-amz-request-id"), + response.getheader("x-amz-id-2"), + response, + bucket_name=bucket_name, + object_name=object_name, + ) + + if response_error.code in ["NoSuchBucket", "RetryHead"]: + self._region_map.pop(bucket_name, None) + + raise response_error + + def _execute( + self, + method, + bucket_name=None, + object_name=None, + body=None, + headers=None, + query_params=None, + preload_content=True, + ): + """Execute HTTP request.""" + region = self._get_region(bucket_name, None) + + try: + return self._url_open( + method, + region, + bucket_name=bucket_name, + object_name=object_name, + body=body, + headers=headers, + query_params=query_params, + preload_content=preload_content, + ) + except S3Error as exc: + if exc.code != "RetryHead": + raise + + # Retry only once on RetryHead error. + try: + return self._url_open( + method, + region, + bucket_name=bucket_name, + object_name=object_name, + body=body, + headers=headers, + query_params=query_params, + preload_content=preload_content, + ) + except S3Error as exc: + if exc.code != "RetryHead": + raise + + code, message = self._handle_redirect_response( + method, bucket_name, exc.response, + ) + raise exc.copy(code, message) + + def _get_region(self, bucket_name, region): + """ + Return region of given bucket either from region cache or set in + constructor. + """ + + if region: + # Error out if region does not match with region passed via + # constructor. + if self._base_url.region and self._base_url.region != region: + raise ValueError( + "region must be {0}, but passed {1}".format( + self._base_url.region, region, + ), + ) + return region + + if self._base_url.region: + return self._base_url.region + + if not bucket_name or not self._provider: + return "us-east-1" + + region = self._region_map.get(bucket_name) + if region: + return region + + # Execute GetBucketLocation REST API to get region of the bucket. + response = self._url_open( + "GET", + "us-east-1", + bucket_name=bucket_name, + query_params={"location": ""}, + ) + + element = ET.fromstring(response.data.decode()) + if not element.text: + region = "us-east-1" + elif element.text == "EU": + region = "eu-west-1" + else: + region = element.text + + self._region_map[bucket_name] = region + return region + + def set_app_info(self, app_name, app_version): + """ + Set your application name and version to user agent header. + + :param app_name: Application name. + :param app_version: Application version. + + Example:: + client.set_app_info('my_app', '1.0.2') + """ + if not (app_name and app_version): + raise ValueError("Application name/version cannot be empty.") + + self._user_agent = "{0} {1}/{2}".format( + _DEFAULT_USER_AGENT, app_name, app_version, + ) + + def trace_on(self, stream): + """ + Enable http trace. + + :param output_stream: Stream for writing HTTP call tracing. + """ + if not stream: + raise ValueError('Input stream for trace output is invalid.') + # Save new output stream. + self._trace_stream = stream + + def trace_off(self): + """ + Disable HTTP trace. + """ + self._trace_stream = None + + def enable_accelerate_endpoint(self): + """Enables accelerate endpoint for Amazon S3 endpoint.""" + self._base_url.accelerate_host_flag = True + + def disable_accelerate_endpoint(self): + """Disables accelerate endpoint for Amazon S3 endpoint.""" + self._base_url.accelerate_host_flag = False + + def enable_dualstack_endpoint(self): + """Enables dualstack endpoint for Amazon S3 endpoint.""" + self._base_url.dualstack_host_flag = True + + def disable_dualstack_endpoint(self): + """Disables dualstack endpoint for Amazon S3 endpoint.""" + self._base_url.dualstack_host_flag = False + + def enable_virtual_style_endpoint(self): + """Enables virtual style endpoint.""" + self._base_url.virtual_style_flag = True + + def disable_virtual_style_endpoint(self): + """Disables virtual style endpoint.""" + self._base_url.virtual_style_flag = False + + def select_object_content(self, bucket_name, object_name, request): + """ + Select content of an object by SQL expression. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param request: :class:`SelectRequest ` object. + :return: A reader contains requested records and progress information. + + Example:: + request = SelectRequest( + "select * from s3object", + CSVInputSerialization(), + CSVOutputSerialization(), + request_progress=True, + ) + data = client.select_object_content('foo', 'test.csv', request) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + if not isinstance(request, SelectRequest): + raise ValueError("request must be SelectRequest type") + body = marshal(request) + response = self._execute( + "POST", + bucket_name=bucket_name, + object_name=object_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"select": "", "select-type": "2"}, + preload_content=False, + ) + return SelectObjectReader(response) + + def make_bucket(self, bucket_name, location=None, object_lock=False): + """ + Create a bucket with region and object lock. + + :param bucket_name: Name of the bucket. + :param location: Region in which the bucket will be created. + :param object_lock: Flag to set object-lock feature. + + Examples:: + minio.make_bucket('foo') + minio.make_bucket('foo', 'us-west-1') + minio.make_bucket('foo', 'us-west-1', object_lock=True) + """ + check_bucket_name(bucket_name, True) + if self._base_url.region: + # Error out if region does not match with region passed via + # constructor. + if location and self._base_url.region != location: + raise ValueError( + "region must be {0}, but passed {1}".format( + self._base_url.region, location, + ), + ) + location = location or "us-east-1" + headers = ( + {"x-amz-bucket-object-lock-enabled": "true"} + if object_lock else None + ) + + body = None + if location != "us-east-1": + element = Element("CreateBucketConfiguration") + SubElement(element, "LocationConstraint", location) + body = marshal(element) + self._url_open( + "PUT", + location, + bucket_name=bucket_name, + body=body, + headers=headers, + ) + self._region_map[bucket_name] = location + + def list_buckets(self): + """ + List information of all accessible buckets. + + :return: An iterator contains bucket information. + + Example:: + bucket_list = minio.list_buckets() + for bucket in bucket_list: + print(bucket.name, bucket.created_date) + """ + + response = self._execute("GET") + return parse_list_buckets(response.data) + + def bucket_exists(self, bucket_name): + """ + Check if a bucket exists. + + :param bucket_name: Name of the bucket. + :return: True if the bucket exists. + + Example:: + found = minio.bucket_exists("my-bucketname") + if found: + print("my-bucketname exists") + else: + print("my-bucketname does not exist") + """ + check_bucket_name(bucket_name) + try: + self._execute("HEAD", bucket_name) + return True + except S3Error as exc: + if exc.code != "NoSuchBucket": + raise + return False + + def remove_bucket(self, bucket_name): + """ + Remove an empty bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.remove_bucket("my-bucketname") + """ + check_bucket_name(bucket_name) + self._execute("DELETE", bucket_name) + self._region_map.pop(bucket_name, None) + + def get_bucket_policy(self, bucket_name): + """ + Get bucket policy configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: Bucket policy configuration as JSON string. + + Example:: + config = minio.get_bucket_policy("my-bucketname") + """ + check_bucket_name(bucket_name) + response = self._execute( + "GET", bucket_name, query_params={"policy": ""}, + ) + return response.data.decode() + + def delete_bucket_policy(self, bucket_name): + """ + Delete bucket policy configuration of a bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.delete_bucket_policy("my-bucketname") + """ + check_bucket_name(bucket_name) + self._execute("DELETE", bucket_name, query_params={"policy": ""}) + + def set_bucket_policy(self, bucket_name, policy): + """ + Set bucket policy configuration to a bucket. + + :param bucket_name: Name of the bucket. + :param policy: Bucket policy configuration as JSON string. + + Example:: + minio.set_bucket_policy("my-bucketname", config) + """ + check_bucket_name(bucket_name) + is_valid_policy_type(policy) + self._execute( + "PUT", + bucket_name, + body=policy, + headers={"Content-MD5": md5sum_hash(policy)}, + query_params={"policy": ""}, + ) + + def get_bucket_notification(self, bucket_name): + """ + Get notification configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: Notification configuration. + + Example:: + config = minio.get_bucket_notification("my-bucketname") + """ + check_bucket_name(bucket_name) + response = self._execute( + "GET", bucket_name, query_params={"notification": ""}, + ) + return parse_get_bucket_notification(response.data.decode()) + + def _set_bucket_notification(self, bucket_name, notifications): + """Execute SetBucketNotification API.""" + body = marshal_bucket_notifications(notifications) + self._execute( + "PUT", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"notification": ""}, + ) + + def set_bucket_notification(self, bucket_name, notifications): + """ + Set notification configuration of a bucket. + + :param bucket_name: Name of the bucket. + :param notifications: Notification configuration to be set. + + Example:: + minio.set_bucket_notification("my-bucketname", config) + """ + check_bucket_name(bucket_name) + is_valid_notification_config(notifications) + return self._set_bucket_notification(bucket_name, notifications) + + def remove_all_bucket_notification(self, bucket_name): + """ + Remove notification configuration of a bucket. On success, S3 service + stops notification of events previously set of the bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.remove_all_bucket_notification("my-bucketname") + """ + check_bucket_name(bucket_name) + return self._set_bucket_notification(bucket_name, {}) + + def put_bucket_encryption(self, bucket_name, enc_config): + """ + Set encryption configuration of a bucket. + + :param bucket_name: Name of the bucket. + :param enc_config: Encryption configuration as dictionary to be set. + + Example:: + minio.put_bucket_encryption("my-bucketname", config) + """ + check_bucket_name(bucket_name) + + # 'Rule' is a list, so we need to go through each one of + # its key/value pair and collect the encryption values. + rules = enc_config['ServerSideEncryptionConfiguration']['Rule'] + body = xml_marshal_bucket_encryption(rules) + self._execute( + "PUT", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"encryption": ""}, + ) + + def get_bucket_encryption(self, bucket_name): + """ + Get encryption configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: Encryption configuration. + + Example:: + config = minio.get_bucket_encryption("my-bucketname") + """ + check_bucket_name(bucket_name) + response = self._execute( + "GET", + bucket_name, + query_params={"encryption": ""}, + ) + return xml_to_dict(response.data.decode()) + + def delete_bucket_encryption(self, bucket_name): + """ + Delete encryption configuration of a bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.delete_bucket_encryption("my-bucketname") + """ + check_bucket_name(bucket_name) + self._execute( + "DELETE", + bucket_name, + query_params={"encryption": ""}, + ) + + def listen_bucket_notification(self, bucket_name, prefix='', suffix='', + events=('s3:ObjectCreated:*', + 's3:ObjectRemoved:*', + 's3:ObjectAccessed:*')): + """ + Listen events of object prefix and suffix of a bucket. Caller should + iterate returned iterator to read new events. + + :param bucket_name: Name of the bucket. + :param prefix: Listen events of object starts with prefix. + :param suffix: Listen events of object ends with suffix. + :param events: Events to listen. + :return: Iterator contains event records. + + Example:: + iter = minio.listen_bucket_notification( + "my-bucketname", + events=('s3:ObjectCreated:*', 's3:ObjectAccessed:*'), + ) + for events in iter: + print(events) + """ + check_bucket_name(bucket_name) + if self._base_url.is_aws_host: + raise ValueError( + "ListenBucketNotification API is not supported in Amazon S3", + ) + + while True: + response = self._execute( + "GET", + bucket_name, + query_params={ + "prefix": prefix or "", + "suffix": suffix or "", + "events": events, + }, + preload_content=False, + ) + + try: + for line in response.stream(): + line = line.strip() + if not line: + continue + if hasattr(line, 'decode'): + line = line.decode() + event = json.loads(line) + if event['Records']: + yield event + except JSONDecodeError: + pass # Ignore this exception. + finally: + response.close() + response.release_conn() + + def set_bucket_versioning(self, bucket_name, config): + """ + Set versioning configuration to a bucket. + + :param bucket_name: Name of the bucket. + :param config: :class:`VersioningConfig `. + + Example:: + minio.set_bucket_versioning( + "my-bucketname", VersioningConfig(ENABLED), + ) + """ + check_bucket_name(bucket_name) + if not isinstance(config, VersioningConfig): + raise ValueError("config must be VersioningConfig type") + body = marshal(config) + self._execute( + "PUT", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"versioning": ""}, + ) + + def get_bucket_versioning(self, bucket_name): + """ + Get versioning configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: :class:`VersioningConfig `. + + Example:: + config minio.get_bucket_versioning("my-bucketname") + print(config.status) + """ + check_bucket_name(bucket_name) + response = self._execute( + "GET", + bucket_name, + query_params={"versioning": ""}, + ) + return unmarshal(VersioningConfig, response.data.decode()) + + def fput_object(self, bucket_name, object_name, file_path, + content_type='application/octet-stream', + metadata=None, sse=None, progress=None, + part_size=0): + """ + Uploads data from a file to an object in a bucket. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param file_path: Name of file to upload. + :param content_type: Content type of the object. + :param metadata: Any additional metadata to be uploaded along + with your PUT request. + :param sse: Server-side encryption. + :param progress: A progress object + :param part_size: Multipart part size + :return: etag and version ID if available. + + Example:: + minio.fput_object('foo', 'bar', 'filepath', 'text/plain') + """ + + # Open file in 'read' mode. + with open(file_path, 'rb') as file_data: + file_size = os.stat(file_path).st_size + return self.put_object(bucket_name, object_name, file_data, + file_size, content_type, metadata, sse, + progress, part_size) + + def fget_object(self, bucket_name, object_name, file_path, + request_headers=None, sse=None, version_id=None, + extra_query_params=None, tmp_file_path=None): + """ + Downloads data of an object to file. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param file_path: Name of file to download. + :param request_headers: Any additional headers to be added with GET + request. + :param sse: Server-side encryption customer key. + :param version_id: Version-ID of the object. + :param extra_query_params: Extra query parameters for advanced usage. + :return: Object information. + + Example:: + minio.fget_object('foo', 'bar', 'localfile') + minio.fget_object( + 'foo', 'bar', 'localfile', version_id='VERSION-ID', + ) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + + if os.path.isdir(file_path): + raise ValueError("file {0} is a directory".format(file_path)) + + # Create top level directory if needed. + makedirs(os.path.dirname(file_path)) + + stat = self.stat_object( + bucket_name, + object_name, + sse, + version_id=version_id, + ) + + # Write to a temporary file "file_path.part.minio" before saving. + tmp_file_path = ( + tmp_file_path or file_path + "." + stat.etag + ".part.minio" + ) + try: + tmp_file_stat = os.stat(tmp_file_path) + except IOError: + tmp_file_stat = None # Ignore this error. + offset = tmp_file_stat.st_size if tmp_file_stat else 0 + if offset > stat.size: + os.remove(tmp_file_path) + offset = 0 + + try: + response = self.get_object( + bucket_name, + object_name, + offset=offset, + request_headers=request_headers, + sse=sse, + version_id=version_id, + extra_query_params=extra_query_params, + ) + with open(tmp_file_path, "ab") as tmp_file: + for data in response.stream(amt=1024*1024): + tmp_file.write(data) + if os.path.exists(file_path): + os.remove(file_path) # For windows compatibility. + os.rename(tmp_file_path, file_path) + return stat + finally: + if response: + response.close() + response.release_conn() + + def get_object(self, bucket_name, object_name, offset=0, length=0, + request_headers=None, sse=None, version_id=None, + extra_query_params=None): + """ + Get data of an object. Returned response should be closed after use to + release network resources. To reuse the connection, it's required to + call `response.release_conn()` explicitly. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param offset: Start byte position of object data. + :param length: Number of bytes of object data from offset. + :param request_headers: Any additional headers to be added with GET + request. + :param sse: Server-side encryption customer key. + :param version_id: Version-ID of the object. + :param extra_query_params: Extra query parameters for advanced usage. + :return: :class:`urllib3.response.HTTPResponse` object. + + Example:: + // Get entire object data. + try: + response = minio.get_object('foo', 'bar') + // Read data from response. + finally: + response.close() + response.release_conn() + + // Get object data for offset/length. + try: + response = minio.get_object('foo', 'bar', 2, 4) + // Read data from response. + finally: + response.close() + response.release_conn() + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + check_ssec(sse) + + headers = sse.headers() if sse else {} + headers.update(request_headers or {}) + + if offset or length: + headers['Range'] = 'bytes={}-{}'.format( + offset, offset + length - 1 if length else "") + + if version_id: + extra_query_params = extra_query_params or {} + extra_query_params["versionId"] = version_id + + return self._execute( + "GET", + bucket_name, + object_name, + headers=headers, + query_params=extra_query_params, + preload_content=False, + ) + + def copy_object(self, bucket_name, object_name, object_source, + conditions=None, source_sse=None, sse=None, metadata=None): + """ + Create an object by server-side copying data from another object. + In this API maximum supported source object size is 5GiB. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param object_source: Source object to be copied. + :param conditions: :class:`CopyConditions` object. Collection of + supported CopyObject conditions. + :param source_sse: Server-side encryption customer key of source + object. + :param sse: Server-side encryption of destination object. + :param metadata: Any user-defined metadata to be copied along with + destination object. + :return: :class:`ObjectWriteResult ` object. + + Example:: + minio.copy_object( + "my-bucketname", + "my-objectname", + "my-source-bucketname/my-source-objectname", + ) + minio.copy_object( + "my-bucketname", + "my-objectname", + "my-source-bucketname/my-source-objectname" + "?versionId=b6602757-7c9c-449b-937f-fed504d04c94", + ) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + check_non_empty_string(object_source) + check_ssec(source_sse) + check_sse(sse) + + # Preserving the user-defined metadata in headers + if metadata: + headers = amzprefix_user_metadata(metadata) + headers["x-amz-metadata-directive"] = "REPLACE" + else: + headers = {} + if conditions: + headers.update(conditions) + headers.update(source_sse.copy_headers() if source_sse else {}) + headers.update(sse.headers() if sse else {}) + headers['X-Amz-Copy-Source'] = quote(object_source) + response = self._execute( + "PUT", + bucket_name, + object_name=object_name, + headers=headers, + ) + element = ET.fromstring(response.data.decode()) + etag = findtext(element, "ETag") + if etag: + etag = etag.replace('"', "") + last_modified = findtext(element, "LastModified") + if last_modified: + last_modified = strptime_rfc3339(last_modified) + return ObjectWriteResult( + bucket_name, + object_name, + response.getheader("x-amz-version-id"), + etag, + last_modified, + ) + + def _abort_multipart_upload(self, bucket_name, object_name, upload_id): + """Execute AbortMultipartUpload S3 API.""" + self._execute( + "DELETE", + bucket_name, + object_name, + query_params={'uploadId': upload_id}, + ) + + def _complete_multipart_upload( + self, bucket_name, object_name, upload_id, parts, + ): + """Execute CompleteMultipartUpload S3 API.""" + body = marshal_complete_multipart(parts) + response = self._execute( + "POST", + bucket_name, + object_name, + body=body, + headers={ + "Content-Type": 'application/xml', + "Content-MD5": md5sum_hash(body), + }, + query_params={'uploadId': upload_id}, + ) + return ( + parse_multipart_upload_result(response.data), + response.getheader("x-amz-version-id"), + ) + + def _create_multipart_upload(self, bucket_name, object_name, headers): + """Execute CreateMultipartUpload S3 API.""" + if not headers.get("Content-Type"): + headers["Content-Type"] = "application/octet-stream" + response = self._execute( + "POST", + bucket_name, + object_name, + headers=headers, + query_params={"uploads": ""}, + ) + return parse_new_multipart_upload(response.data) + + def _put_object(self, bucket_name, object_name, data, headers, + query_params=None): + """Execute PutObject S3 API.""" + response = self._execute( + "PUT", + bucket_name, + object_name, + body=data, + headers=headers, + query_params=query_params, + ) + return ( + response.getheader("etag").replace('"', ""), + response.getheader("x-amz-version-id"), + ) + + def _upload_part(self, bucket_name, object_name, data, headers, + upload_id, part_number): + """Execute UploadPart S3 API.""" + query_params = { + "partNumber": str(part_number), + "uploadId": upload_id, + } + etag, _ = self._put_object( + bucket_name, object_name, data, headers, query_params=query_params, + ) + return etag + + def _upload_part_task(self, args): + """Upload_part task for ThreadPool.""" + return args[5], self._upload_part(*args) + + def put_object( # pylint: disable=too-many-branches,too-many-statements + self, bucket_name, object_name, data, length, + content_type='application/octet-stream', + metadata=None, sse=None, progress=None, + part_size=0, num_parallel_uploads=3, + ): + """ + Uploads data from a stream to an object in a bucket. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param data: Contains object data. + :param content_type: Content type of the object. + :param metadata: Any additional metadata to be uploaded along + with your PUT request. + :param sse: Server-side encryption. + :param progress: A progress object + :param part_size: Multipart part size + :return: etag and version ID if available. + + Example:: + file_stat = os.stat('hello.txt') + with open('hello.txt', 'rb') as data: + minio.put_object( + 'foo', 'bar', data, file_stat.st_size, 'text/plain', + ) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + check_sse(sse) + if not callable(getattr(data, "read")): + raise ValueError("input data must have callable read()") + part_size, part_count = get_part_info(length, part_size) + + if progress: + if not isinstance(progress, Thread): + raise TypeError("progress object must be instance of Thread") + # Set progress bar length and object name before upload + progress.set_meta(object_name=object_name, total_length=length) + + headers = amzprefix_user_metadata(metadata or {}) + headers["Content-Type"] = content_type or "application/octet-stream" + headers.update(sse.headers() if sse else {}) + + object_size = length + uploaded_size = 0 + part_number = 0 + one_byte = b'' + stop = False + upload_id = None + parts = [] + pool = None + + try: + while not stop: + part_number += 1 + if part_count > 0: + if part_number == part_count: + part_size = object_size - uploaded_size + stop = True + part_data = read_part_data( + data, part_size, progress=progress, + ) + if len(part_data) != part_size: + raise IOError( + ( + "stream having not enough data;" + "expected: {0}, got: {1} bytes" + ).format(part_size, len(part_data)) + ) + else: + part_data = read_part_data( + data, part_size + 1, one_byte, progress=progress, + ) + # If part_data_size is less or equal to part_size, + # then we have reached last part. + if len(part_data) <= part_size: + part_count = part_number + stop = True + else: + one_byte = part_data[-1:] + part_data = part_data[:-1] + + uploaded_size += len(part_data) + + if part_count == 1: + return self._put_object( + bucket_name, object_name, part_data, headers, + ) + + if not upload_id: + upload_id = self._create_multipart_upload( + bucket_name, object_name, headers, + ) + if num_parallel_uploads and num_parallel_uploads > 1: + pool = ThreadPool(num_parallel_uploads) + pool.start_parallel() + + args = ( + bucket_name, object_name, part_data, + sse.headers() if isinstance(sse, SseCustomerKey) else None, + upload_id, part_number, + ) + if num_parallel_uploads > 1: + pool.add_task(self._upload_part_task, args) + else: + etag = self._upload_part(*args) + parts.append(Part(part_number, etag)) + + if pool: + result = pool.result() + parts = [None] * part_count + while not result.empty(): + part_number, etag = result.get() + parts[part_number-1] = Part(part_number, etag) + + result = self._complete_multipart_upload( + bucket_name, object_name, upload_id, parts, + ) + return result[0].etag, result[1] + except Exception as exc: + if upload_id: + self._abort_multipart_upload( + bucket_name, object_name, upload_id, + ) + raise exc + + def list_objects(self, bucket_name, prefix=None, recursive=False, + start_after=None, include_user_meta=False, + include_version=False, use_api_v1=False): + """ + Lists object information of a bucket using S3 API version 2, optionally + for prefix recursively. + + :param bucket_name: Name of the bucket. + :param prefix: Object name starts with prefix. + :param recursive: List recursively than directory structure emulation. + :param start_after: List objects after this key name. + :param include_user_meta: MinIO specific flag to control to include + user metadata. + :param include_version: Flag to control whether include object + versions. + :param use_api_v1: Flag to control to use ListObjectV1 S3 API or not. + :return: An iterator contains object information. + + Example:: + # List objects information. + objects = minio.list_objects('foo') + for object in objects: + print(object) + + # List objects information whose names starts with 'hello/'. + objects = minio.list_objects('foo', prefix='hello/') + for object in objects: + print(object) + + # List objects information recursively. + objects = minio.list_objects('foo', recursive=True) + for object in objects: + print(object) + + # List objects information recursively whose names starts with + # 'hello/'. + objects = minio.list_objects( + 'foo', prefix='hello/', recursive=True, + ) + for object in objects: + print(object) + + # List objects information recursively after object name + # 'hello/world/1'. + objects = minio.list_objects( + 'foo', recursive=True, start_after='hello/world/1', + ) + for object in objects: + print(object) + """ + return self._list_objects( + bucket_name, + delimiter=None if recursive else "/", + include_user_meta=include_user_meta, + prefix=prefix, + start_after=start_after, + use_api_v1=use_api_v1, + include_version=include_version, + ) + + def stat_object(self, bucket_name, object_name, sse=None, version_id=None, + extra_query_params=None): + """ + Get object information and metadata of an object. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param sse: Server-side encryption customer key. + :param version_id: Version ID of the object. + :param extra_query_params: Extra query parameters for advanced usage. + :return: :class:`Object `. + + Example:: + stat = minio.stat_object("my-bucketname", "my-objectname") + """ + + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + check_ssec(sse) + + headers = sse.headers() if sse else {} + query_params = extra_query_params or {} + query_params.update({"versionId": version_id} if version_id else {}) + response = self._execute( + "HEAD", + bucket_name, + object_name, + headers=headers, + query_params=query_params, + ) + + custom_metadata = { + key: value for key, value in response.headers.items() + if is_supported_header(key) or is_amz_header(key) + } + + last_modified = response.getheader("last-modified") + if last_modified: + last_modified = dateutil.parser.parse(last_modified).timetuple() + + return Object( + bucket_name, + object_name, + last_modified=last_modified, + etag=response.getheader("etag", "").replace('"', ""), + size=int(response.getheader("content-length", "0")), + content_type=response.getheader("content-type"), + metadata=custom_metadata, + version_id=response.getheader("x-amz-version-id"), + ) + + def remove_object(self, bucket_name, object_name, version_id=None): + """ + Remove an object. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param version_id: Version ID of the object. + + Example:: + minio.remove_object("my-bucketname", "my-objectname") + minio.remove_object( + "my-bucketname", + "my-objectname", + version_id="13f88b18-8dcd-4c83-88f2-8631fdb6250c", + ) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + self._execute( + "DELETE", + bucket_name, + object_name, + query_params={"versionId": version_id} if version_id else None, + ) + + def _process_remove_objects_batch(self, bucket_name, objects_batch): + """ + Requester and response parser for remove_objects + """ + body = xml_marshal_delete_objects(objects_batch) + response = self._execute( + "POST", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={'delete': ''}, + ) + return parse_multi_delete_response(response.data) + + def remove_objects(self, bucket_name, objects_iter): + """ + Remove multiple objects. + + :param bucket_name: Name of the bucket. + :param objects_iter: An iterable type python object providing object + names for deletion. + :return: An iterator contains + :class:`MultiDeleteError `. + + Example:: + minio.remove_objects( + "my-bucketname", + [ + "my-objectname1", + "my-objectname2", + ("my-objectname3", "13f88b18-8dcd-4c83-88f2-8631fdb6250c"), + ], + ) + """ + check_bucket_name(bucket_name) + if isinstance(objects_iter, (str, bytes)): + raise TypeError( + 'objects_iter cannot be `str` or `bytes` instance. It must be ' + 'a list, tuple or iterator of object names' + ) + + # turn list like objects into an iterator. + objects_iter = itertools.chain(objects_iter) + + def check_name(name): + if not isinstance(name, (str, bytes)): + name = name[0] + check_non_empty_string(name) + return True + + while True: + # get 1000 entries or whatever available. + obj_batch = [ + name for _, name in zip(range(1000), objects_iter) + if check_name(name) + ] + + if not obj_batch: + break + + errs_result = self._process_remove_objects_batch( + bucket_name, obj_batch, + ) + + # return the delete errors. + for err_result in errs_result: + yield err_result + + def presigned_url(self, method, + bucket_name, + object_name, + expires=timedelta(days=7), + response_headers=None, + request_date=None, + version_id=None, + extra_query_params=None): + """ + Get presigned URL of an object for HTTP method, expiry time and custom + request parameters. + + :param method: HTTP method. + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param expires: Expiry in seconds; defaults to 7 days. + :params response_headers: Optional response_headers argument to + specify response fields like date, size, + type of file, data about server, etc. + :params request_date: Optional request_date argument to + specify a different request date. Default is + current date. + :param version_id: Version ID of the object. + :param extra_query_params: Extra query parameters for advanced usage. + :return: URL string. + + Example:: + # Get presigned URL string to delete 'my-objectname' in + # 'my-bucketname' with one day expiry. + url = minio.presigned_url( + "DELETE", + "my-bucketname", + "my-objectname", + expires=timedelta(days=1), + ) + print(url) + + # Get presigned URL string to upload 'my-objectname' in + # 'my-bucketname' with response-content-type as application/json + # and one day expiry. + url = minio.presigned_url( + "PUT", + "my-bucketname", + "my-objectname", + expires=timedelta(days=1), + response_headers={"response-content-type": "application/json"}, + ) + print(url) + + # Get presigned URL string to download 'my-objectname' in + # 'my-bucketname' with two hours expiry. + url = minio.presigned_url( + "GET", + "my-bucketname", + "my-objectname", + expires=timedelta(hours=2), + ) + print(url) + """ + check_bucket_name(bucket_name) + check_non_empty_string(object_name) + if expires.total_seconds() < 1 or expires.total_seconds() > 604800: + raise ValueError("expires must be between 1 second to 7 days") + + region = self._get_region(bucket_name, None) + query_params = extra_query_params or {} + query_params.update({"versionId": version_id} if version_id else {}) + query_params.update(response_headers or {}) + creds = self._provider.retrieve() if self._provider else None + if creds and creds.session_token: + query_params["X-Amz-Security-Token"] = creds.session_token + url = self._base_url.build( + method, + region, + bucket_name=bucket_name, + object_name=object_name, + query_params=query_params, + ) + + if creds: + url = presign_v4( + method, + url, + region, + creds, + request_date or datetime.utcnow(), + int(expires.total_seconds()), + ) + return urlunsplit(url) + + def presigned_get_object(self, bucket_name, object_name, + expires=timedelta(days=7), + response_headers=None, + request_date=None, + version_id=None, + extra_query_params=None): + """ + Get presigned URL of an object to download its data with expiry time + and custom request parameters. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param expires: Expiry in seconds; defaults to 7 days. + :param response_headers: Optional response_headers argument to + specify response fields like date, size, + type of file, data about server, etc. + :param request_date: Optional request_date argument to + specify a different request date. Default is + current date. + :param version_id: Version ID of the object. + :param extra_query_params: Extra query parameters for advanced usage. + :return: URL string. + + Example:: + # Get presigned URL string to download 'my-objectname' in + # 'my-bucketname' with default expiry. + url = minio.presigned_get_object("my-bucketname", "my-objectname") + print(url) + + # Get presigned URL string to download 'my-objectname' in + # 'my-bucketname' with two hours expiry. + url = minio.presigned_get_object( + "my-bucketname", "my-objectname", expires=timedelta(hours=2), + ) + print(url) + """ + return self.presigned_url( + "GET", + bucket_name, + object_name, + expires, + response_headers=response_headers, + request_date=request_date, + version_id=version_id, + extra_query_params=extra_query_params, + ) + + def presigned_put_object(self, bucket_name, object_name, + expires=timedelta(days=7)): + """ + Get presigned URL of an object to upload data with expiry time and + custom request parameters. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param expires: Expiry in seconds; defaults to 7 days. + :return: URL string. + + Example:: + # Get presigned URL string to upload data to 'my-objectname' in + # 'my-bucketname' with default expiry. + url = minio.presigned_put_object("my-bucketname", "my-objectname") + print(url) + + # Get presigned URL string to upload data to 'my-objectname' in + # 'my-bucketname' with two hours expiry. + url = minio.presigned_put_object( + "my-bucketname", "my-objectname", expires=timedelta(hours=2), + ) + print(url) + """ + return self.presigned_url('PUT', + bucket_name, + object_name, + expires) + + def presigned_post_policy(self, post_policy): + """ + Get form-data of PostPolicy of an object to upload its data using POST + method. + + :param post_policy: :class:`PostPolicy `. + :return: :dict: contains form-data. + + Example:: + post_policy = PostPolicy() + post_policy.set_bucket_name('bucket_name') + post_policy.set_key_startswith('objectPrefix/') + expires_date = datetime.utcnow()+timedelta(days=10) + post_policy.set_expires(expires_date) + + form_data = presigned_post_policy(post_policy) + print(form_data) + """ + post_policy.is_valid() + if not self._provider: + raise ValueError( + "anonymous access does not require presigned post form-data", + ) + + bucket_name = post_policy.form_data['bucket'] + region = self._get_region(bucket_name, None) + credentials = self._provider.retrieve() + date = datetime.utcnow() + credential_string = get_credential_string( + credentials.access_key, date, region, + ) + policy = [ + ('eq', '$x-amz-date', date.strftime(AMZ_DATE_FORMAT)), + ('eq', '$x-amz-algorithm', SIGN_V4_ALGORITHM), + ('eq', '$x-amz-credential', credential_string), + ] + if credentials.session_token: + policy.append( + ('eq', '$x-amz-security-token', credentials.session_token), + ) + post_policy_base64 = post_policy.base64(extras=policy) + signature = post_presign_v4( + post_policy_base64, credentials, date, region, + ) + form_data = { + 'policy': post_policy_base64, + 'x-amz-algorithm': SIGN_V4_ALGORITHM, + 'x-amz-credential': credential_string, + 'x-amz-date': date.strftime(AMZ_DATE_FORMAT), + 'x-amz-signature': signature, + } + if credentials.session_token: + form_data['x-amz-security-token'] = credentials.session_token + post_policy.form_data.update(form_data) + return ( + self._base_url.build("POST", region, bucket_name), + post_policy.form_data, + ) + + def delete_bucket_replication(self, bucket_name): + """ + Delete replication configuration of a bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.delete_bucket_replication("my-bucketname") + """ + check_bucket_name(bucket_name) + self._execute("DELETE", bucket_name, query_params={"replication": ""}) + + def get_bucket_replication(self, bucket_name): + """ + Get bucket replication configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: :class:`ReplicationConfig ` object. + + Example:: + config = minio.get_bucket_replication("my-bucketname") + """ + check_bucket_name(bucket_name) + try: + response = self._execute( + "GET", bucket_name, query_params={"replication": ""}, + ) + return unmarshal(ReplicationConfig, response.data.decode()) + except S3Error as exc: + if exc.code != "ReplicationConfigurationNotFoundError": + raise + return None + + def set_bucket_replication(self, bucket_name, config): + """ + Set bucket replication configuration to a bucket. + + :param bucket_name: Name of the bucket. + :param config: :class:`ReplicationConfig ` object. + + Example:: + config = ReplicationConfig( + "REPLACE-WITH-ACTUAL-ROLE", + [ + Rule( + Destination( + "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", + ), + ENABLED, + delete_marker_replication=DeleteMarkerReplication( + DISABLED, + ), + rule_filter=Filter( + AndOperator( + "TaxDocs", + {"key1": "value1", "key2": "value2"}, + ), + ), + rule_id="rule1", + priority=1, + ), + ], + ) + minio.set_bucket_replication("my-bucketname", config) + """ + check_bucket_name(bucket_name) + if not isinstance(config, ReplicationConfig): + raise ValueError("config must be ReplicationConfig type") + body = marshal(config) + self._execute( + "PUT", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"replication": ""}, + ) + + def delete_bucket_lifecycle(self, bucket_name): + """ + Delete notification configuration of a bucket. + + :param bucket_name: Name of the bucket. + + Example:: + minio.delete_bucket_lifecycle("my-bucketname") + """ + check_bucket_name(bucket_name) + self._execute("DELETE", bucket_name, query_params={"lifecycle": ""}) + + def get_bucket_lifecycle(self, bucket_name): + """ + Get bucket lifecycle configuration of a bucket. + + :param bucket_name: Name of the bucket. + :return: :class:`LifecycleConfig ` object. + + Example:: + config = minio.get_bucket_lifecycle("my-bucketname") + """ + check_bucket_name(bucket_name) + try: + response = self._execute( + "GET", bucket_name, query_params={"lifecycle": ""}, + ) + return unmarshal(LifecycleConfig, response.data.decode()) + except S3Error as exc: + if exc.code != "NoSuchLifecycleConfiguration": + raise + return None + + def set_bucket_lifecycle(self, bucket_name, config): + """ + Set bucket lifecycle configuration to a bucket. + + :param bucket_name: Name of the bucket. + :param config: :class:`LifecycleConfig ` object. + + Example:: + config = LifecycleConfig( + [ + Rule( + ENABLED, + rule_filter=Filter(prefix="logs/"), + rule_id="rule2", + expiration=Expiration(days=365), + ), + ], + ) + minio.set_bucket_lifecycle("my-bucketname", config) + """ + check_bucket_name(bucket_name) + if not isinstance(config, LifecycleConfig): + raise ValueError("config must be LifecycleConfig type") + body = marshal(config) + self._execute( + "PUT", + bucket_name, + body=body, + headers={"Content-MD5": md5sum_hash(body)}, + query_params={"lifecycle": ""}, + ) + + def _list_objects( # pylint: disable=too-many-arguments,too-many-branches + self, + bucket_name, + continuation_token=None, # listV2 only + delimiter=None, # all + encoding_type=None, # all + fetch_owner=None, # listV2 only + include_user_meta=None, # MinIO specific listV2. + max_keys=None, # all + prefix=None, # all + start_after=None, # all: v1:marker, versioned:key_marker + version_id_marker=None, # versioned + use_api_v1=False, + include_version=False, + ): + """ + List objects optionally including versions. + Note: Its required to send empty values to delimiter/prefix and 1000 to + max-keys when not provided for server-side bucket policy evaluation to + succeed; otherwise AccessDenied error will be returned for such + policies. + """ + + check_bucket_name(bucket_name) + + if version_id_marker: + include_version = True + + is_truncated = True + while is_truncated: + query = {} + if include_version: + query["versions"] = "" + elif not use_api_v1: + query["list-type"] = "2" + + if not include_version and not use_api_v1: + if continuation_token: + query["continuation-token"] = continuation_token + if fetch_owner: + query["fetch-owner"] = "true" + if include_user_meta: + query["user-metadata"] = "true" + query["delimiter"] = delimiter or "" + if encoding_type: + query["encoding-type"] = encoding_type + query["max-keys"] = str(max_keys or 1000) + query["prefix"] = prefix or "" + if start_after: + if include_version: + query["key-marker"] = start_after + elif use_api_v1: + query["marker"] = start_after + else: + query["start-after"] = start_after + if version_id_marker: + query["version-id-marker"] = version_id_marker + + response = self._execute("GET", bucket_name, query_params=query) + + if include_version: + objects, is_truncated, start_after, version_id_marker = ( + parse_list_object_versions(response.data, bucket_name) + ) + elif use_api_v1: + objects, is_truncated, start_after = parse_list_objects( + response.data, + bucket_name, + ) + else: + objects, is_truncated, continuation_token = ( + parse_list_objects_v2(response.data, bucket_name) + ) + + for obj in objects: + yield obj + + def _list_multipart_uploads(self, bucket_name, delimiter=None, + encoding_type=None, key_marker=None, + max_uploads=None, prefix=None, + upload_id_marker=None, extra_headers=None, + extra_query_params=None): + """ + Execute ListMultipartUploads S3 API. + + :param bucket_name: Name of the bucket. + :param region: (Optional) Region of the bucket. + :param delimiter: (Optional) Delimiter on listing. + :param encoding_type: (Optional) Encoding type. + :param key_marker: (Optional) Key marker. + :param max_uploads: (Optional) Maximum upload information to fetch. + :param prefix: (Optional) Prefix on listing. + :param upload_id_marker: (Optional) Upload ID marker. + :param extra_headers: (Optional) Extra headers for advanced usage. + :param extra_query_params: (Optional) Extra query parameters for + advanced usage. + :return: + :class:`ListMultipartUploadsResult ` + object + """ + + query_params = extra_query_params or {} + query_params.update( + { + "uploads": "", + "delimiter": delimiter or "", + "max-uploads": str(max_uploads or 1000), + "prefix": prefix or "", + "encoding-type": "url", + }, + ) + if encoding_type: + query_params["encoding-type"] = encoding_type + if key_marker: + query_params["key-marker"] = key_marker + if upload_id_marker: + query_params["upload-id-marker"] = upload_id_marker + + response = self._execute( + "GET", + bucket_name, + query_params=query_params, + headers=extra_headers, + ) + return parse_list_multipart_uploads(response.data) + + def _list_parts(self, bucket_name, object_name, upload_id, + max_parts=None, part_number_marker=None, + extra_headers=None, extra_query_params=None): + """ + Execute ListParts S3 API. + + :param bucket_name: Name of the bucket. + :param object_name: Object name in the bucket. + :param upload_id: Upload ID. + :param region: (Optional) Region of the bucket. + :param max_parts: (Optional) Maximum parts information to fetch. + :param part_number_marker: (Optional) Part number marker. + :param extra_headers: (Optional) Extra headers for advanced usage. + :param extra_query_params: (Optional) Extra query parameters for + advanced usage. + :return: :class:`ListPartsResult ` object + """ + + query_params = extra_query_params or {} + query_params.update( + { + "uploadId": upload_id, + "max-parts": str(max_parts or 1000), + }, + ) + if part_number_marker: + query_params["part-number-marker"] = part_number_marker + + response = self._execute( + "GET", + bucket_name, + object_name=object_name, + query_params=query_params, + headers=extra_headers, + ) + return parse_list_parts(response.data) diff --git a/testbed/minio__minio-py/minio/commonconfig.py b/testbed/minio__minio-py/minio/commonconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..c59179851a5bdb34d59b75dc7cbdd26bd33632a5 --- /dev/null +++ b/testbed/minio__minio-py/minio/commonconfig.py @@ -0,0 +1,252 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common request/response configuration of S3 APIs.""" +# pylint: disable=invalid-name + +from __future__ import absolute_import + +from abc import ABCMeta + +from .xml import SubElement, find, findall, findtext + +DISABLED = "Disabled" +ENABLED = "Enabled" +_MAX_KEY_LENGTH = 128 +_MAX_VALUE_LENGTH = 256 +_MAX_OBJECT_TAG_COUNT = 10 +_MAX_TAG_COUNT = 50 + + +class Tags(dict): + """dict extended to bucket/object tags.""" + + def __init__(self, for_object=False): + self._for_object = for_object + super().__init__() + + def __setitem__(self, key, value): + limit = _MAX_OBJECT_TAG_COUNT if self._for_object else _MAX_TAG_COUNT + if len(self) == limit: + raise ValueError( + "only {0} {1} tags are allowed".format( + limit, "object" if self._for_object else "bucket", + ), + ) + if not key or len(key) > _MAX_KEY_LENGTH or "&" in key: + raise ValueError("invalid tag key '{0}'".format(key)) + if value is None or len(value) > _MAX_VALUE_LENGTH or "&" in value: + raise ValueError("invalid tag value '{0}'".format(value)) + super().__setitem__(key, value) + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + elements = findall(element, "Tag") + obj = cls() + for tag in elements: + key = findtext(tag, "Key", True) + value = findtext(tag, "Value", True) + obj[key] = value + return obj + + def toxml(self, element): + """Convert to XML.""" + for key, value in self.items(): + tag = SubElement(element, "Tag") + SubElement(tag, "Key", key) + SubElement(tag, "Value", value) + return element + + +class Tag: + """Tag.""" + + def __init__(self, key, value): + if not key: + raise ValueError("key must be provided") + if value is None: + raise ValueError("value must be provided") + self._key = key + self._value = value + + @property + def key(self): + """Get key.""" + return self._key + + @property + def value(self): + """Get value.""" + return self._value + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Tag") + key = findtext(element, "Key", True) + value = findtext(element, "Value", True) + return cls(key, value) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Tag") + SubElement(element, "Key", self._key) + SubElement(element, "Value", self._value) + return element + + +class AndOperator: + """AND operator.""" + + def __init__(self, prefix=None, tags=None): + if prefix is None and not tags: + raise ValueError("at least prefix or tags must be provided") + self._prefix = prefix + self._tags = tags + + @property + def prefix(self): + """Get prefix.""" + return self._prefix + + @property + def tags(self): + """Get tags.""" + return self._tags + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "And") + prefix = findtext(element, "Prefix") + tags = ( + None if find(element, "Tag") is None + else Tags.fromxml(element) + ) + return cls(prefix, tags) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "And") + if self._prefix is not None: + SubElement(element, "Prefix", self._prefix) + if self._tags is not None: + self._tags.toxml(element) + return element + + +class Filter: + """Lifecycle rule filter.""" + + def __init__(self, and_operator=None, prefix=None, tag=None): + valid = ( + (and_operator is not None) ^ + (prefix is not None) ^ + (tag is not None) + ) + if not valid: + raise ValueError("only one of and, prefix or tag must be provided") + if prefix is not None and not prefix: + raise ValueError("prefix must not be empty") + self._and_operator = and_operator + self._prefix = prefix + self._tag = tag + + @property + def and_operator(self): + """Get AND operator.""" + return self._and_operator + + @property + def prefix(self): + """Get prefix.""" + return self._prefix + + @property + def tag(self): + """Get tag.""" + return self._tag + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Filter") + and_operator = ( + None if find(element, "And") is None + else AndOperator.fromxml(element) + ) + prefix = findtext(element, "Prefix") + tag = None if find(element, "Tag") is None else Tag.fromxml(element) + return cls(and_operator, prefix, tag) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Filter") + if self._and_operator: + self._and_operator.toxml(element) + if self._prefix is not None: + SubElement(element, "Prefix", self._prefix) + if self._tag is not None: + self._tag.toxml(element) + return element + + +class BaseRule: + """Base rule class for Replication and Lifecycle.""" + __metaclass__ = ABCMeta + + def __init__(self, rule_filter=None, rule_id=None): + if rule_id is not None: + rule_id = rule_id.strip() + if not rule_id: + raise ValueError("rule ID must be non-empty string") + if len(rule_id) > 255: + raise ValueError("rule ID must not exceed 255 characters") + self._rule_filter = rule_filter + self._rule_id = rule_id + + @property + def rule_filter(self): + """Get replication rule filter.""" + return self._rule_filter + + @property + def rule_id(self): + """Get rule ID.""" + return self._rule_id + + @staticmethod + def parsexml(element): + """Parse XML and return filter and ID.""" + return ( + None if find(element, "Filter") is None + else Filter.fromxml(element) + ), findtext(element, "ID") + + def toxml(self, element): + """Convert to XML.""" + if self._rule_filter: + self._rule_filter.toxml(element) + if self._rule_id is not None: + SubElement(element, "ID", self._rule_id) + return element + + +def check_status(status): + """Validate status.""" + if status not in [ENABLED, DISABLED]: + raise ValueError("status must be 'Enabled' or 'Disabled'") diff --git a/testbed/minio__minio-py/minio/copy_conditions.py b/testbed/minio__minio-py/minio/copy_conditions.py new file mode 100644 index 0000000000000000000000000000000000000000..90305c949427978889d1bc6bd91aebdcc0546714 --- /dev/null +++ b/testbed/minio__minio-py/minio/copy_conditions.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.copy_conditions +~~~~~~~~~~~~~~~ + +This module contains :class:`CopyConditions ` implementation. + +:copyright: (c) 2016 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from collections.abc import MutableMapping + +from .helpers import check_non_empty_string + +# CopyCondition explanation: +# http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html +# +# Example: +# +# copyCondition { +# key: "x-amz-copy-if-modified-since", +# value: "Tue, 15 Nov 1994 12:45:26 GMT", +# + + +class CopyConditions(MutableMapping): + """ + A :class:`CopyConditions ` collection of + supported CopyObject conditions. + + - x-amz-copy-source-if-match + - x-amz-copy-source-if-none-match + - x-amz-copy-source-if-unmodified-since + - x-amz-copy-source-if-modified-since + + """ + + def __init__(self, *args, **kwargs): + self._store = dict(*args, **kwargs) + + def __getitem__(self, key): + return self._store[key] + + def __setitem__(self, key, value): + self._store[key] = value + + def __delitem__(self, key): + del self._store[key] + + def __iter__(self): + return iter(self._store) + + def __len__(self): + return len(self._store) + + def set_match_etag(self, etag): + """Set ETag match condition.""" + check_non_empty_string(etag) + self._store["X-Amz-Copy-Source-If-Match"] = etag + + def set_match_etag_except(self, etag): + """Set ETag not match condition.""" + check_non_empty_string(etag) + self._store["X-Amz-Copy-Source-If-None-Match"] = etag + + def set_unmodified_since(self, mod_time): + """Set unmodified since condition.""" + time = mod_time.strftime("%a, %d %b %Y %H:%M:%S GMT") + self._store["X-Amz-Copy-Source-If-Unmodified-Since"] = time + + def set_modified_since(self, mod_time): + """Set modified since condition.""" + time = mod_time.strftime("%a, %d %b %Y %H:%M:%S GMT") + self._store["X-Amz-Copy-Source-If-Modified-Since"] = time diff --git a/testbed/minio__minio-py/minio/credentials/__init__.py b/testbed/minio__minio-py/minio/credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f770e6deb136d41251999c15543ec614be9dae6 --- /dev/null +++ b/testbed/minio__minio-py/minio/credentials/__init__.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Credential module.""" + +# pylint: disable=unused-import +from .credentials import Credentials +from .providers import (AssumeRoleProvider, AWSConfigProvider, ChainedProvider, + ClientGrantsProvider, EnvAWSProvider, EnvMinioProvider, + IamAwsProvider, LdapIdentityProvider, + MinioClientConfigProvider, Provider, StaticProvider, + WebIdentityProvider) diff --git a/testbed/minio__minio-py/minio/credentials/credentials.py b/testbed/minio__minio-py/minio/credentials/credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..4796171f71191cddf68f65b4b2cc08b3f2980e9f --- /dev/null +++ b/testbed/minio__minio-py/minio/credentials/credentials.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Credential definitions to access S3 service.""" + +from datetime import datetime, timedelta, timezone + + +class Credentials: + """ + Represents credentials access key, secret key and session token. + """ + + def __init__( + self, access_key, secret_key, session_token=None, expiration=None, + ): + if not access_key: + raise ValueError("Access key must not be empty") + + if not secret_key: + raise ValueError("Secret key must not be empty") + + self._access_key = access_key + self._secret_key = secret_key + self._session_token = session_token + if expiration and expiration.tzinfo: + expiration = ( + expiration.astimezone(timezone.utc).replace(tzinfo=None) + ) + self._expiration = expiration + + @property + def access_key(self): + """Get access key.""" + return self._access_key + + @property + def secret_key(self): + """Get secret key.""" + return self._secret_key + + @property + def session_token(self): + """Get session token.""" + return self._session_token + + def is_expired(self): + """Check whether this credentials expired or not.""" + return ( + self._expiration < (datetime.utcnow() + timedelta(seconds=10)) + if self._expiration else False + ) diff --git a/testbed/minio__minio-py/minio/credentials/providers.py b/testbed/minio__minio-py/minio/credentials/providers.py new file mode 100644 index 0000000000000000000000000000000000000000..b0c6b5a12963b44fee5b17e04111212c1920613b --- /dev/null +++ b/testbed/minio__minio-py/minio/credentials/providers.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Credential providers.""" + +import configparser +import ipaddress +import json +import os +import socket +import sys +import time +from abc import ABCMeta, abstractmethod +from datetime import datetime, timedelta +from urllib.parse import urlencode, urlsplit +from xml.etree import ElementTree + +import urllib3 + +from minio.helpers import sha256_hash, strptime_rfc3339 +from minio.signer import AMZ_DATE_FORMAT, sign_v4_sts + +from .credentials import Credentials + +_MIN_DURATION_SECONDS = timedelta(minutes=15).total_seconds() +_MAX_DURATION_SECONDS = timedelta(days=7).total_seconds() +_DEFAULT_DURATION_SECONDS = timedelta(hours=1).total_seconds() +_XML_NS = { + "s3": "http://s3.amazonaws.com/doc/2006-03-01/", + "sts": "https://sts.amazonaws.com/doc/2011-06-15/", +} + + +def _parse_credentials(data, result_path): + """Parse data containing credentials XML.""" + + root = ElementTree.fromstring(data) + credentials = root.find("sts:" + result_path, _XML_NS).find( + "sts:Credentials", _XML_NS) + + access_key = credentials.find("sts:AccessKeyId", _XML_NS).text + secret_key = credentials.find("sts:SecretAccessKey", _XML_NS).text + session_token = credentials.find("sts:SessionToken", _XML_NS).text + expiration = strptime_rfc3339( + credentials.find("sts:Expiration", _XML_NS).text, + ) + + return Credentials(access_key, secret_key, session_token, expiration) + + +def _urlopen(http_client, method, url, body=None, headers=None): + """Wrapper of urlopen() handles HTTP status code.""" + res = http_client.urlopen(method, url, body=body, headers=headers) + if res.status not in [200, 204, 206]: + raise ValueError( + "{0} failed with HTTP status code {1}".format(url, res.status), + ) + return res + + +class Provider: # pylint: disable=too-few-public-methods + """Credential retriever.""" + __metaclass__ = ABCMeta + + @abstractmethod + def retrieve(self): + """Retrieve credentials and its expiry if available.""" + + +class AssumeRoleProvider(Provider): + """Assume-role credential provider.""" + + def __init__( + self, sts_endpoint, access_key, secret_key, duration_seconds=0, + policy=None, region=None, role_arn=None, role_session_name=None, + external_id=None, http_client=None, + ): + self._sts_endpoint = sts_endpoint + self._access_key = access_key + self._secret_key = secret_key + self._region = region or "" + self._http_client = http_client or urllib3.PoolManager( + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ), + ) + + query_params = { + "Action": "AssumeRole", + "Version": "2011-06-15", + "DurationSeconds": str( + duration_seconds + if duration_seconds > _DEFAULT_DURATION_SECONDS + else _DEFAULT_DURATION_SECONDS + ), + } + + if role_arn: + query_params["RoleArn"] = role_arn + if role_session_name: + query_params["RoleSessionName"] = role_session_name + if policy: + query_params["Policy"] = policy + if external_id: + query_params["ExternalId"] = external_id + + self._body = urlencode(query_params) + self._content_sha256 = sha256_hash(self._body) + url = urlsplit(sts_endpoint) + self._host = url.netloc + if ( + (url.scheme == "http" and url.port == 80) or + (url.scheme == "https" and url.port == 443) + ): + self._host = url.hostname + self._credentials = None + + def retrieve(self): + """Retrieve credentials.""" + if self._credentials and not self._credentials.is_expired(): + return self._credentials + + utcnow = datetime.utcnow() + headers = sign_v4_sts( + "POST", + urlsplit(self._sts_endpoint), + self._region, + { + "Content-Type": "application/x-www-form-urlencoded", + "Host": self._host, + "X-Amz-Date": utcnow.strftime(AMZ_DATE_FORMAT), + }, + Credentials(self._access_key, self._secret_key), + self._content_sha256, + utcnow, + ) + + res = _urlopen( + self._http_client, + "POST", + self._sts_endpoint, + body=self._body, + headers=headers, + ) + + self._credentials = _parse_credentials( + res.data.decode(), "AssumeRoleResult", + ) + + return self._credentials + + +class ChainedProvider(Provider): + """Chained credential provider.""" + + def __init__(self, providers): + self._providers = providers + self._provider = None + self._credentials = None + + def retrieve(self): + """Retrieve credentials from one of available provider.""" + if self._credentials and not self._credentials.is_expired(): + return self._credentials + + if self._provider: + try: + self._credentials = self._provider.retrieve() + return self._credentials + except ValueError: + # Ignore this error and iterate other providers. + pass + + for provider in self._providers: + try: + self._credentials = provider.retrieve() + self._provider = provider + return self._credentials + except ValueError: + # Ignore this error and iterate other providers. + pass + + return ValueError("All providers fail to fetch credentials") + + +class EnvAWSProvider(Provider): + """Credential provider from AWS environment variables.""" + + def __init__(self): + access_key = ( + os.environ.get("AWS_ACCESS_KEY_ID") or + os.environ.get("AWS_ACCESS_KEY") + ) + secret_key = ( + os.environ.get("AWS_SECRET_ACCESS_KEY") or + os.environ.get("AWS_SECRET_KEY") + ) + self._credentials = Credentials( + access_key, + secret_key, + session_token=os.environ.get("AWS_SESSION_TOKEN"), + ) + + def retrieve(self): + """Retrieve credentials.""" + return self._credentials + + +class EnvMinioProvider(Provider): + """Credential provider from MinIO environment variables.""" + + def __init__(self): + self._credentials = Credentials( + os.environ.get("MINIO_ACCESS_KEY"), + os.environ.get("MINIO_SECRET_KEY"), + ) + + def retrieve(self): + """Retrieve credentials.""" + return self._credentials + + +class AWSConfigProvider(Provider): + """Credential provider from AWS credential file.""" + + def __init__(self, filename=None, profile=None): + self._filename = ( + filename or + os.environ.get("AWS_SHARED_CREDENTIALS_FILE") or + os.path.join(os.environ.get("HOME"), ".aws", "credentials") + ) + self._profile = profile or os.environ.get("AWS_PROFILE") or "default" + + def retrieve(self): + """Retrieve credentials from AWS configuration file.""" + parser = configparser.ConfigParser() + parser.read(self._filename) + access_key = parser.get( + self._profile, + "aws_access_key_id", + fallback=None, + ) + secret_key = parser.get( + self._profile, + "aws_secret_access_key", + fallback=None, + ) + session_token = parser.get( + self._profile, + "aws_session_token", + fallback=None, + ) + + if not access_key: + raise ValueError( + ( + "access key does not exist in profile " + "{0} in AWS credential file {1}" + ).format( + self._profile, self._filename, + ), + ) + + if not secret_key: + raise ValueError( + ( + "secret key does not exist in profile " + "{0} in AWS credential file {1}" + ).format( + self._profile, self._filename, + ), + ) + + return Credentials( + access_key, + secret_key, + session_token=session_token, + ) + + +class MinioClientConfigProvider(Provider): + """Credential provider from MinIO Client configuration file.""" + + def __init__(self, filename=None, alias=None): + self._filename = ( + filename or + os.path.join( + os.environ.get("HOME"), + "mc" if sys.platform == "win32" else ".mc", + "config.json", + ) + ) + self._alias = alias or os.environ.get("MINIO_ALIAS") or "s3" + + def retrieve(self): + """Retrieve credential value from MinIO client configuration file.""" + try: + with open(self._filename) as conf_file: + config = json.load(conf_file) + if not config.get("hosts"): + raise ValueError( + "invalid configuration in file {0}".format( + self._filename, + ), + ) + creds = config.get("hosts").get(self._alias) + if not creds: + raise ValueError( + ( + "alias {0} not found in MinIO client" + "configuration file {1}" + ).format( + self._alias, self._filename, + ), + ) + return Credentials(creds.get("accessKey"), creds.get("secretKey")) + except (IOError, OSError) as exc: + raise ValueError( + "error in reading file {0}".format(self._filename), + ) from exc + + +def _check_loopback_host(url): + """Check whether host in url points only to localhost.""" + host = urllib3.util.parse_url(url).host + try: + addrs = set(info[4][0] for info in socket.getaddrinfo(host, None)) + for addr in addrs: + if not ipaddress.ip_address(addr).is_loopback: + raise ValueError(host + " is not loopback only host") + except socket.gaierror as exc: + raise ValueError("Host " + host + " is not loopback address") from exc + + +def _get_jwt_token(token_file): + """Read and return content of token file. """ + try: + with open(token_file) as file: + return {"access_token": file.read(), "expires_in": "0"} + except (IOError, OSError) as exc: + raise ValueError( + "error in reading file {0}".format(token_file), + ) from exc + + +class IamAwsProvider(Provider): + """Credential provider using IAM roles for Amazon EC2/ECS.""" + + def __init__(self, custom_endpoint=None, http_client=None): + self._custom_endpoint = custom_endpoint + self._http_client = http_client or urllib3.PoolManager( + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ), + ) + self._token_file = os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE") + self._aws_region = os.environ.get("AWS_REGION") + self._role_arn = os.environ.get("AWS_ROLE_ARN") + self._role_session_name = os.environ.get("AWS_ROLE_SESSION_NAME") + self._relative_uri = os.environ.get( + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", + ) + if self._relative_uri and not self._relative_uri.startswith("/"): + self._relative_uri = "/" + self._relative_uri + self._full_uri = os.environ.get("AWS_CONTAINER_CREDENTIALS_FULL_URI") + self._credentials = None + + def fetch(self, url): + """Fetch credentials from EC2/ECS. """ + + res = _urlopen(self._http_client, "GET", url) + data = json.loads(res.data) + if data["Code"] != "Success": + raise ValueError( + "{0} failed with code {1} message {2}".format( + url, data["Code"], data["Message"], + ), + ) + data["Expiration"] = strptime_rfc3339(data["Expiration"]) + + return Credentials( + data["AccessKeyId"], + data["SecretAccessKey"], + data["Token"], + data["Expiration"], + ) + + def retrieve(self): + """Retrieve credentials from WebIdentity/EC2/ECS.""" + + if self._credentials and not self._credentials.is_expired(): + return self._credentials + + url = self._custom_endpoint + if self._token_file: + if not url: + url = "https://sts.{0}{1}amazonaws.com".format( + self._aws_region, "." if self._aws_region else "", + ) + + provider = WebIdentityProvider( + lambda: _get_jwt_token(self._token_file), + url, + role_arn=self._role_arn, + role_session_name=self._role_session_name, + http_client=self._http_client, + ) + self._credentials = provider.retrieve() + return self._credentials + + if self._relative_uri: + if not url: + url = "http://169.254.170.2" + self._relative_uri + elif self._full_uri: + if not url: + url = self._full_uri + _check_loopback_host(url) + else: + if not url: + url = ( + "http://169.254.169.254" + + "/latest/meta-data/iam/security-credentials/" + ) + + res = _urlopen(self._http_client, "GET", url) + role_names = res.data.decode("utf-8").split("\n") + if not role_names: + raise ValueError( + "no IAM roles attached to EC2 service {0}".format(url), + ) + url += "/" + role_names[0].strip("\r") + + self._credentials = self.fetch(url) + return self._credentials + + +class LdapIdentityProvider(Provider): + """Credential provider using AssumeRoleWithLDAPIdentity API.""" + + def __init__( + self, sts_endpoint, ldap_username, ldap_password, http_client=None, + ): + self._sts_endpoint = sts_endpoint + "?" + urlencode( + { + "Action": "AssumeRoleWithLDAPIdentity", + "Version": "2011-06-15", + "LDAPUsername": ldap_username, + "LDAPPassword": ldap_password, + }, + ) + self._http_client = http_client or urllib3.PoolManager( + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ), + ) + self._credentials = None + + def retrieve(self): + """Retrieve credentials.""" + + if self._credentials and not self._credentials.is_expired(): + return self._credentials + + res = _urlopen( + self._http_client, + "POST", + self._sts_endpoint, + ) + + self._credentials = _parse_credentials( + res.data.decode(), "AssumeRoleWithLDAPIdentityResult", + ) + + return self._credentials + + +class StaticProvider(Provider): + """Fixed credential provider.""" + + def __init__(self, access_key, secret_key, session_token=None): + self._credentials = Credentials(access_key, secret_key, session_token) + + def retrieve(self): + """Return passed credentials.""" + return self._credentials + + +class WebIdentityClientGrantsProvider(Provider): + """Base class for WebIdentity and ClientGrants credentials provider.""" + __metaclass__ = ABCMeta + + def __init__( + self, jwt_provider_func, sts_endpoint, + duration_seconds=0, policy=None, role_arn=None, + role_session_name=None, http_client=None, + ): + self._jwt_provider_func = jwt_provider_func + self._sts_endpoint = sts_endpoint + self._duration_seconds = duration_seconds + self._policy = policy + self._role_arn = role_arn + self._role_session_name = role_session_name + self._http_client = http_client or urllib3.PoolManager( + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ), + ) + self._credentials = None + + @abstractmethod + def _is_web_identity(self): + """Check if derived class deal with WebIdentity.""" + + def _get_duration_seconds(self, expiry): + """Get DurationSeconds optimal value.""" + + if self._duration_seconds: + expiry = self._duration_seconds + + if expiry > _MAX_DURATION_SECONDS: + return _MAX_DURATION_SECONDS + + if expiry <= 0: + return expiry + + return ( + _MIN_DURATION_SECONDS if expiry < _MIN_DURATION_SECONDS else expiry + ) + + def retrieve(self): + """Retrieve credentials.""" + + if self._credentials and not self._credentials.is_expired(): + return self._credentials + + jwt = self._jwt_provider_func() + + query_params = {"Version": "2011-06-15"} + duration_seconds = self._get_duration_seconds( + int(jwt.get("expires_in", "0")), + ) + if duration_seconds: + query_params["DurationSeconds"] = str(duration_seconds) + if self._policy: + query_params["Policy"] = self._policy + + if self._is_web_identity(): + query_params["Action"] = "AssumeRoleWithWebIdentity" + query_params["WebIdentityToken"] = jwt.get("access_token") + if self._role_arn: + query_params["RoleArn"] = self._role_arn + query_params["RoleSessionName"] = ( + self._role_session_name + if self._role_session_name + else str(time.time()).replace(".", "") + ) + else: + query_params["Action"] = "AssumeRoleWithClientGrants" + query_params["Token"] = jwt.get("access_token") + + url = self._sts_endpoint + "?" + urlencode(query_params) + res = _urlopen(self._http_client, "POST", url) + + self._credentials = _parse_credentials( + res.data.decode(), + ( + "AssumeRoleWithWebIdentityResult" + if self._is_web_identity() + else "AssumeRoleWithClientGrantsResult" + ), + ) + + return self._credentials + + +class ClientGrantsProvider(WebIdentityClientGrantsProvider): + """Credential provider using AssumeRoleWithClientGrants API.""" + + def __init__( + self, jwt_provider_func, sts_endpoint, + duration_seconds=0, policy=None, http_client=None, + ): + super().__init__( + jwt_provider_func, sts_endpoint, duration_seconds, policy, + http_client=http_client, + ) + + def _is_web_identity(self): + return False + + +class WebIdentityProvider(WebIdentityClientGrantsProvider): + """Credential provider using AssumeRoleWithWebIdentity API.""" + + def _is_web_identity(self): + return True diff --git a/testbed/minio__minio-py/minio/definitions.py b/testbed/minio__minio-py/minio/definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4cd07dcafe191372712a5edfafbd5ea7a43419 --- /dev/null +++ b/testbed/minio__minio-py/minio/definitions.py @@ -0,0 +1,488 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.definitions +~~~~~~~~~~~~~~~ + +This module contains the primary objects that power MinIO. + +:copyright: (c) 2015 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from urllib.parse import urlsplit + +from .helpers import queryencode, quote, url_replace + + +def _extract_region(host): + """Extract region from Amazon S3 host.""" + + tokens = host.split(".") + token = tokens[1] + + # If token is "dualstack", then region might be in next token. + if token == "dualstack": + token = tokens[2] + + # If token is equal to "amazonaws", region is not passed in the host. + if token == "amazonaws": + return None + + # Return token as region. + return token + + +class BaseURL: + """Base URL of S3 endpoint.""" + + def __init__(self, endpoint, region): + url = urlsplit(endpoint) + host = url.hostname + + if url.scheme.lower() not in ["http", "https"]: + raise ValueError("scheme in endpoint must be http or https") + + url = url_replace(url, scheme=url.scheme.lower()) + + if url.path and url.path != "/": + raise ValueError("path in endpoint is not allowed") + + url = url_replace(url, path="") + + if url.query: + raise ValueError("query in endpoint is not allowed") + + if url.fragment: + raise ValueError("fragment in endpoint is not allowed") + + try: + url.port + except ValueError as exc: + raise ValueError("invalid port") from exc + + if url.username: + raise ValueError("username in endpoint is not allowed") + + if url.password: + raise ValueError("password in endpoint is not allowed") + + if ( + (url.scheme == "http" and url.port == 80) or + (url.scheme == "https" and url.port == 443) + ): + url = url_replace(url, netloc=host) + + self._accelerate_host_flag = host.startswith("s3-accelerate.") + self._is_aws_host = ( + ( + host.startswith("s3.") or self._accelerate_host_flag + ) and + ( + host.endswith(".amazonaws.com") or + host.endswith(".amazonaws.com.cn") + ) + ) + self._virtual_style_flag = ( + self._is_aws_host or host.endswith("aliyuncs.com") + ) + + region_in_host = None + if self._is_aws_host: + is_aws_china_host = host.endswith(".cn") + url = url_replace( + url, + netloc=( + "amazonaws.com.cn" + if is_aws_china_host else "amazonaws.com" + ), + ) + region_in_host = _extract_region(host) + + if is_aws_china_host and not region_in_host and not region: + raise ValueError( + "region missing in Amazon S3 China endpoint {0}".format( + endpoint, + ), + ) + self._dualstack_host_flag = ".dualstack." in host + else: + self._accelerate_host_flag = False + + self._url = url + self._region = region or region_in_host + + @property + def region(self): + """Get region.""" + return self._region + + @property + def is_https(self): + """Check if scheme is HTTPS.""" + return self._url.scheme == "https" + + @property + def host(self): + """Get hostname.""" + return self._url.netloc + + @property + def is_aws_host(self): + """Check if URL points to AWS host.""" + return self._is_aws_host + + @property + def accelerate_host_flag(self): + """Check if URL points to AWS accelerate host.""" + return self._accelerate_host_flag + + @accelerate_host_flag.setter + def accelerate_host_flag(self, flag): + """Check if URL points to AWS accelerate host.""" + if self._is_aws_host: + self._accelerate_host_flag = flag + + @property + def dualstack_host_flag(self): + """Check if URL points to AWS dualstack host.""" + return self._dualstack_host_flag + + @dualstack_host_flag.setter + def dualstack_host_flag(self, flag): + """Check to use virtual style or not.""" + if self._is_aws_host: + self._dualstack_host_flag = flag + + @property + def virtual_style_flag(self): + """Check to use virtual style or not.""" + return self._virtual_style_flag + + @virtual_style_flag.setter + def virtual_style_flag(self, flag): + """Check to use virtual style or not.""" + self._virtual_style_flag = flag + + def build( + self, method, region, + bucket_name=None, object_name=None, query_params=None, + ): + """Build URL for given information.""" + + if not bucket_name and object_name: + raise ValueError( + "empty bucket name for object name {0}".format(object_name), + ) + + query = [] + for key, values in sorted((query_params or {}).items()): + values = values if isinstance(values, (list, tuple)) else [values] + query += [ + "{0}={1}".format(queryencode(key), queryencode(value)) + for value in sorted(values) + ] + url = url_replace(self._url, query="&".join(query)) + host = self._url.netloc + + if not bucket_name: + url = url_replace(url, path="/") + return ( + url_replace(url, netloc="s3." + region + "." + host) + if self._is_aws_host else url + ) + + enforce_path_style = ( + # CreateBucket API requires path style in Amazon AWS S3. + (method == "PUT" and not object_name and not query_params) or + + # GetBucketLocation API requires path style in Amazon AWS S3. + (query_params and "location" in query_params) or + + # Use path style for bucket name containing '.' which causes + # SSL certificate validation error. + ("." in bucket_name and self._url.scheme == "https") + ) + + if self._is_aws_host: + s3_domain = "s3." + if self._accelerate_host_flag: + if "." in bucket_name: + raise ValueError( + ( + "bucket name '{0}' with '.' is not allowed " + "for accelerated endpoint" + ).format(bucket_name), + ) + + if not enforce_path_style: + s3_domain = "s3-accelerate." + + dual_stack = "dualstack." if self._dualstack_host_flag else "" + endpoint = s3_domain + dual_stack + if enforce_path_style or not self._accelerate_host_flag: + endpoint += region + "." + host = endpoint + host + + if enforce_path_style or not self._virtual_style_flag: + url = url_replace(url, netloc=host) + url = url_replace(url, path="/" + bucket_name) + else: + url = url_replace( + url, + netloc=bucket_name + "." + host, + path="/", + ) + + if object_name: + path = url.path + path += ("" if path.endswith("/") else "/") + quote(object_name) + url = url_replace(url, path=path) + + return url + + +class Bucket: + """ + A bucket metadata :class:`Bucket `. + + :param name: Bucket name. + :param created: Bucket creation date. + """ + + def __init__(self, name, created): + self.name = name + self.creation_date = created + + def __str__(self): + return "".format(self.name, self.creation_date) + + +class Object: + """ + A object metadata :class:`Object `. + + :param bucket_name: Bucket name. + :param object_name: Object name. + :param last_modified: Object when it was last modified on server. + :param etag: ETag saved on server for the object_name. + :param size: Size of the object on server. + :param content_type: Optional parameter indicating content type. + :param is_dir: Optional parameter differentiating object prefixes. + :param metadata: Optional parameter contains all the custom metadata. + """ + + def __init__(self, bucket_name, # pylint: disable=too-many-arguments + object_name, + last_modified=None, etag='', + size=0, content_type=None, is_dir=False, metadata=None, + version_id=None, is_latest=None, storage_class=None, + owner_id=None, owner_name=None, delete_marker=False): + self.bucket_name = bucket_name + self.object_name = object_name + self.last_modified = last_modified + self.etag = etag + self.size = size + self.content_type = content_type + self.is_dir = is_dir + self.metadata = metadata + self.version_id = version_id + self.is_latest = is_latest + self.storage_class = storage_class + self.owner_id = owner_id + self.owner_name = owner_name + self.delete_marker = delete_marker + + def __str__(self): + return ( + "" + ).format( + bucket_name=self.bucket_name, + object_name=self.object_name.encode("utf-8"), + version_id=self.version_id, + last_modified=self.last_modified, + etag=self.etag, + size=self.size, + content_type=self.content_type, + is_dir=self.is_dir, + metadata=self.metadata, + ) + + +class MultipartUploadResult: + """ + A completed multipart upload metadata + :class:`MultipartUploadResult `. + + :param bucket_name: Bucket name. + :param object_name: Object name. + :param location: Object uploaded location. + :param etag: Object final etag. + """ + + def __init__(self, bucket_name, object_name, location, etag): + self.bucket_name = bucket_name + self.object_name = object_name + self.location = location + self.etag = etag + + def __str__(self): + string_format = ("") + return string_format.format(self.bucket_name, self.object_name, + self.location, self.etag) + + +class Upload: + """ Upload information of a multipart upload.""" + + def __init__(self, root): + self.object_name = root.get_urldecoded_elem_text("Key") + self.upload_id = root.get_child_text("UploadId") + self.initiator_id, self.initator_name = ( + root.find("Initiator").get_child_text("ID", strict=False), + root.find("Initiator").get_child_text( + "DisplayName", strict=False, + ), + ) if root.find("Initiator") else (None, None) + self.owner_id, self.owner_name = ( + root.find("Owner").get_child_text("ID", strict=False), + root.find("Owner").get_child_text("DisplayName", strict=False), + ) if root.find("Owner") else (None, None) + self.storage_class = root.get_child_text("StorageClass") + self.initiated_time = root.get_localized_time_elem("Initiated") + + +class ListMultipartUploadsResult: + """ListMultipartUploads API result.""" + + def __init__(self, root): + self.bucket_name = root.get_child_text("Bucket") + self.key_marker = root.get_urldecoded_elem_text( + "KeyMarker", strict=False, + ) + self.upload_id_marker = root.get_child_text( + "UploadIdMarker", strict=False, + ) + self.next_key_marker = root.get_urldecoded_elem_text( + "NextKeyMarker", strict=False, + ) + self.next_upload_id_marker = root.get_child_text( + "NextUploadIdMarker", strict=False, + ) + self.max_uploads = root.get_int_elem("MaxUploads") + self._is_truncated = ( + root.get_child_text("IsTruncated", strict=False).lower() == "true" + ) + self.uploads = [ + Upload(upload_element) for upload_element in root.findall("Upload") + ] + + +class Part: + """Part information of a multipart upload.""" + + def __init__(self, part_number=None, etag=None, root=None): + if not root and not part_number and not etag: + raise ValueError("part_number/etag or root element must be passed") + + if root: + part_number = root.get_child_text("PartNumber") + etag = root.get_child_text("ETag") + self.last_modified = root.get_localized_time_elem("LastModified") + self.size = root.get_int_elem("Size") + self.part_number = part_number + self.etag = etag + + +class ListPartsResult: + """ListParts API result.""" + + def __init__(self, root): + self.bucket_name = root.get_child_text("Bucket") + self.object_name = root.get_child_text("Key") + self.initiator_id, self.initator_name = ( + root.find("Initiator").get_child_text("ID", strict=False), + root.find("Initiator").get_child_text( + "DisplayName", strict=False, + ), + ) if root.find("Initiator") else (None, None) + self.owner_id, self.owner_name = ( + root.find("Owner").get_child_text("ID", strict=False), + root.find("Owner").get_child_text("DisplayName", strict=False), + ) if root.find("Owner") else (None, None) + self.storage_class = root.get_child_text("StorageClass") + self.part_number_marker = root.get_int_elem("PartNumberMarker") + self.next_part_number_marker = root.get_int_elem( + "NextPartNumberMarker", + ) + self.max_parts = root.get_int_elem("MaxParts") + self._is_truncated = ( + root.get_child_text("IsTruncated", strict=False).lower() == "true" + ) + self.parts = [ + Part(part_element) for part_element in root.findall("Part") + ] + + +class ObjectWriteResult: + """Result class of any APIs doing object creation.""" + + def __init__( + self, bucket_name, object_name, version_id, etag, last_modified, + ): + self._bucket_name = bucket_name + self._object_name = object_name + self._version_id = version_id + self._etag = etag + self._last_modified = last_modified + + @property + def bucket_name(self): + """Get bucket name.""" + return self._bucket_name + + @property + def object_name(self): + """Get object name.""" + return self._object_name + + @property + def version_id(self): + """Get version ID.""" + return self._version_id + + @property + def etag(self): + """Get etag.""" + return self._etag + + @property + def last_modified(self): + """Get last-modified time.""" + return self._last_modified diff --git a/testbed/minio__minio-py/minio/error.py b/testbed/minio__minio-py/minio/error.py new file mode 100644 index 0000000000000000000000000000000000000000..67f53c5b5703c6f8d3fbb34c5a1fdddd6cc057b6 --- /dev/null +++ b/testbed/minio__minio-py/minio/error.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015-2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: disable=too-many-lines + +""" +minio.error +~~~~~~~~~~~~~~~~~~~ + +This module provides custom exception classes for MinIO library +and API specific errors. + +:copyright: (c) 2015, 2016, 2017 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + + +class MinioException(Exception): + """Base Minio exception.""" + + +class InvalidResponseError(MinioException): + """Raised to indicate that non-xml response from server.""" + + def __init__(self, code, content_type, body): + self._code = code + self._content_type = content_type + self._body = body + super().__init__( + ( + "non-XML response from server; " + "Response code: {0}, Content-Type: {1}, Body: {2}" + ).format(code, content_type, body), + ) + + +class ServerError(MinioException): + """Raised to indicate that S3 service returning HTTP server error.""" + + +class S3Error(MinioException): + """ + Raised to indicate that error response is received + when executing S3 operation. + """ + + def __init__(self, code, message, resource, request_id, host_id, + response, bucket_name=None, object_name=None): + self._code = code + self._message = message + self._resource = resource + self._request_id = request_id + self._host_id = host_id + self._response = response + self._bucket_name = bucket_name + self._object_name = object_name + super().__init__( + ( + "S3 operation failed; code: {0}, message: {1}, " + "resource: {2}, request_id: {3}, host_id: {4}{5}{6}" + ).format( + self._code, + self._message, + self._resource, + self._request_id, + self._host_id, + ( + (", bucket_name: " + self._bucket_name) + if self._bucket_name else "" + ), + ( + (", object_name: " + self._object_name) + if self._object_name else "" + ), + ), + ) + + @property + def code(self): + """Get S3 error code.""" + return self._code + + @property + def message(self): + """Get S3 error message.""" + return self._message + + @property + def response(self): + """Get HTTP response.""" + return self._response + + def copy(self, code, message): + """Make a copy with replace code and message.""" + return S3Error( + code, + message, + self._resource, + self._request_id, + self._host_id, + self._response, + self._bucket_name, + self._object_name, + ) + + +class MultiDeleteError(MinioException): + """Represents an error message in RemoveObjects S3 API.""" + + def __init__(self, object_name, code, message): + self._object_name = object_name + self._code = code + self._message = message + super().__init__( + "unable to remove object {0}; code: {1}, message: {2}".format( + object_name, code, message, + ), + ) diff --git a/testbed/minio__minio-py/minio/helpers.py b/testbed/minio__minio-py/minio/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..613e0f2c8c155fe1b18dff27d72f9186f9bbbc89 --- /dev/null +++ b/testbed/minio__minio-py/minio/helpers.py @@ -0,0 +1,499 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2015, 2016, 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.helpers + +This module implements all helper functions. + +:copyright: (c) 2015, 2016, 2017 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +# if math.ceil returns an integer and devide two integers returns a float, +# calculate part size will cause errors, so make sure division integers returns +# a float. +from __future__ import absolute_import, division, unicode_literals + +import base64 +import errno +import hashlib +import math +import os +import re +import urllib.parse +from datetime import datetime + +from .sse import Sse, SseCustomerKey + +# Constants +MAX_MULTIPART_COUNT = 10000 # 10000 parts +MAX_MULTIPART_OBJECT_SIZE = 5 * 1024 * 1024 * 1024 * 1024 # 5TiB +MAX_PART_SIZE = 5 * 1024 * 1024 * 1024 # 5GiB +MIN_PART_SIZE = 5 * 1024 * 1024 # 5MiB +DEFAULT_PART_SIZE = MIN_PART_SIZE # Currently its 5MiB + +_VALID_BUCKETNAME_REGEX = re.compile( + '^[A-Za-z0-9][A-Za-z0-9\\.\\-\\_\\:]{1,61}[A-Za-z0-9]$') +_VALID_BUCKETNAME_STRICT_REGEX = re.compile( + '^[a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9]$') +_VALID_IP_ADDRESS = re.compile( + r'^(\d+\.){3}\d+$') +_ALLOWED_HOSTNAME_REGEX = re.compile( + '^((?!-)(?!_)[A-Z_\\d-]{1,63}(? 0: + if part_size < MIN_PART_SIZE: + raise ValueError( + "part size {0} is not supported; minimum allowed 5MiB".format( + part_size, + ), + ) + if part_size > MAX_PART_SIZE: + raise ValueError( + "part size {0} is not supported; minimum allowed 5GiB".format( + part_size, + ), + ) + + if object_size >= 0: + if object_size > MAX_MULTIPART_OBJECT_SIZE: + raise ValueError( + ( + "object size {0} is not supported; " + "maximum allowed 5TiB" + ).format(object_size), + ) + elif part_size <= 0: + raise ValueError( + "valid part size must be provided when object size is unknown", + ) + + +def _get_part_info(object_size, part_size): + """Compute part information for object and part size.""" + _validate_sizes(object_size, part_size) + + if object_size < 0: + return part_size, -1 + + if part_size > 0: + if part_size > object_size: + part_size = object_size + return part_size, math.ceil(object_size / part_size) + + part_size = math.ceil( + math.ceil(object_size / MAX_MULTIPART_COUNT) / MIN_PART_SIZE, + ) * MIN_PART_SIZE + return part_size, math.ceil(object_size / part_size) if part_size else 1 + + +def get_part_info(object_size, part_size): + """Compute part information for object and part size.""" + part_size, part_count = _get_part_info(object_size, part_size) + if part_count > MAX_MULTIPART_COUNT: + raise ValueError( + ( + "object size {0} and part size {1} " + "make more than {2} parts for upload" + ).format(object_size, part_size, MAX_MULTIPART_COUNT), + ) + return part_size, part_count + + +def read_part_data(stream, size, part_data=b'', progress=None): + """Read part data of given size from stream.""" + while len(part_data) < size: + bytes_to_read = size - len(part_data) + if bytes_to_read > 16384: + bytes_to_read = 16384 + data = stream.read(bytes_to_read) + if not data: + break # EOF reached + part_data += data + if progress: + progress.update(len(data)) + return part_data + + +def makedirs(path): + """Wrapper of os.makedirs() ignores errno.EEXIST.""" + try: + if path: + os.makedirs(path) + except OSError as exc: # Python >2.5 + if exc.errno != errno.EEXIST: + raise + + if not os.path.isdir(path): + raise ValueError( + "path {0} is not a directory".format(path), + ) from exc + + +def check_bucket_name(bucket_name, strict=False): + """Check whether bucket name is valid optional with strict check or not.""" + + # Verify bucket name is not empty + bucket_name = str(bucket_name).strip() + if not bucket_name: + raise ValueError('Bucket name cannot be empty.') + + # Verify bucket name length. + if len(bucket_name) < 3: + raise ValueError('Bucket name cannot be less than' + ' 3 characters.') + if len(bucket_name) > 63: + raise ValueError('Bucket name cannot be greater than' + ' 63 characters.') + + match = _VALID_IP_ADDRESS.match(bucket_name) + if match: + raise ValueError('Bucket name cannot be an ip address') + + unallowed_successive_chars = ['..', '.-', '-.'] + if any(x in bucket_name for x in unallowed_successive_chars): + raise ValueError('Bucket name contains invalid ' + 'successive chars ' + + str(unallowed_successive_chars) + '.') + + if strict: + match = _VALID_BUCKETNAME_STRICT_REGEX.match(bucket_name) + if (not match) or match.end() != len(bucket_name): + raise ValueError('Bucket name contains invalid ' + 'characters (strictly enforced).') + + match = _VALID_BUCKETNAME_REGEX.match(bucket_name) + if (not match) or match.end() != len(bucket_name): + raise ValueError('Bucket name does not follow S3 standards.' + ' Bucket: {0}'.format(bucket_name)) + + +def check_non_empty_string(string): + """Check whether given string is not empty.""" + try: + if not string.strip(): + raise ValueError() + except AttributeError as exc: + raise TypeError() from exc + + +def is_valid_policy_type(policy): + """ + Validate if policy is type str + + :param policy: S3 style Bucket policy. + :return: True if policy parameter is of a valid type, 'string'. + Raise :exc:`TypeError` otherwise. + """ + if not isinstance(policy, (str, bytes)): + raise TypeError("policy must be str or bytes type") + + check_non_empty_string(policy) + + return True + + +def is_valid_notification_config(config): + """ + Validate the notifications config structure + + :param notifications: Dictionary with specific structure. + :return: True if input is a valid bucket notifications structure. + Raise :exc:`ValueError` otherwise. + """ + + valid_events = ( + "s3:ObjectAccessed:*", + "s3:ObjectAccessed:Get", + "s3:ObjectAccessed:Head", + "s3:ReducedRedundancyLostObject", + "s3:ObjectCreated:*", + "s3:ObjectCreated:Put", + "s3:ObjectCreated:Post", + "s3:ObjectCreated:Copy", + "s3:ObjectCreated:CompleteMultipartUpload", + "s3:ObjectRemoved:*", + "s3:ObjectRemoved:Delete", + "s3:ObjectRemoved:DeleteMarkerCreated", + ) + + def _check_filter_rules(rules): + for rule in rules: + if not (rule.get("Name") and rule.get("Value")): + msg = ("{} - a FilterRule dictionary must have 'Name' " + "and 'Value' keys") + raise ValueError(msg.format(rule)) + + if rule.get("Name") not in ["prefix", "suffix"]: + msg = ("{} - The 'Name' key in a filter rule must be " + "either 'prefix' or 'suffix'") + raise ValueError(msg.format(rule.get("Name"))) + + def _check_service_config(config): + # check keys are valid + for skey in config.keys(): + if skey not in ("Id", "Arn", "Events", "Filter"): + msg = "{} is an invalid key for a service configuration item" + raise ValueError(msg.format(skey)) + + # check if "Id" key is present, it should be string or bytes. + if not isinstance(config.get("Id", ""), str): + raise ValueError("'Id' key must be a string") + + # check for required keys + if not config.get("Arn"): + raise ValueError( + "Arn key in service config must be present and has to be " + "non-empty string", + ) + + events = config.get("Events", []) + if not isinstance(events, list): + raise ValueError( + "'Events' must be a list of strings in a service " + "configuration", + ) + if not events: + raise ValueError( + "At least one event must be specified in a service config", + ) + + for event in events: + if event not in valid_events: + msg = "{} is not a valid event. Valid events are: {}" + raise ValueError(msg.format(event, valid_events)) + + if "Filter" not in config: + return + + msg = ("{} - If a Filter key is given, it must be a " + "dictionary, the dictionary must have the key 'Key', " + "and its value must be an object, with a key named " + "'FilterRules' which must be a non-empty list.") + if ( + not isinstance(config.get("Filter", {}), dict) or + not isinstance(config.get("Filter", {}).get("Key", {}), dict) + ): + raise ValueError(msg.format(config["Filter"])) + + rules = config.get( + "Filter", {}).get("Key", {}).get("FilterRules", []) + if not isinstance(rules, list) or not rules: + raise ValueError(msg.format(config["Filter"])) + _check_filter_rules(rules) + + def _check_value(value, key): + # check if config values conform + # first check if value is a list + if not isinstance(value, list): + msg = ("The value for key '{}' in the notifications configuration " + "must be a list.") + raise ValueError(msg.format(key)) + + for sconfig in value: + _check_service_config(sconfig) + + # check if config is a dict. + if not isinstance(config, dict): + raise TypeError("notifications configuration must be a dictionary") + + if not config: + raise ValueError( + "notifications configuration may not be empty" + ) + + for key, value in config.items(): + # check if key names are valid + if key not in ( + "TopicConfigurations", + "QueueConfigurations", + "CloudFunctionConfigurations", + ): + raise ValueError(( + '{} is an invalid key ' + 'for notifications configuration').format(key)) + _check_value(value, key) + + return True + + +def check_ssec(sse): + """Check sse is SseCustomerKey type or not.""" + if sse and not isinstance(sse, SseCustomerKey): + raise ValueError("SseCustomerKey type is required") + + +def check_sse(sse): + """Check sse is Sse type or not.""" + if sse and not isinstance(sse, Sse): + raise ValueError("Sse type is required") + + +def md5sum_hash(data): + """Compute MD5 of data and return hash as Base64 encoded value.""" + if data is None: + return None + + hasher = hashlib.md5() + hasher.update(data.encode() if isinstance(data, str) else data) + md5sum = base64.b64encode(hasher.digest()) + return md5sum.decode() if isinstance(md5sum, bytes) else md5sum + + +def sha256_hash(data): + """Compute SHA-256 of data and return hash as hex encoded value.""" + data = data or b"" + hasher = hashlib.sha256() + hasher.update(data.encode() if isinstance(data, str) else data) + sha256sum = hasher.hexdigest() + return sha256sum.decode() if isinstance(sha256sum, bytes) else sha256sum + + +def amzprefix_user_metadata(metadata): + """ + Return a new metadata dictionary where user defined metadata keys + are prefixed by "x-amz-meta-". + """ + meta = dict() + for key, value in metadata.items(): + # Check if metadata value has US-ASCII encoding since it is + # the only one supported by HTTP headers. This will show a better + # exception message when users pass unsupported characters + # in metadata values. + try: + if isinstance(value, str): + value.encode('us-ascii') + value = ( + [str(val) for val in value] + if isinstance(value, (list, tuple)) else str(value) + ) + except UnicodeEncodeError as exc: + raise ValueError( + 'Metadata supports only US-ASCII characters.', + ) from exc + + if (is_amz_header(key) or is_supported_header(key) or + is_storageclass_header(key)): + meta[key] = value + else: + meta["X-Amz-Meta-" + key] = value + return meta + + +def is_amz_header(key): + """Returns true if amz s3 system defined metadata.""" + key = key.lower() + return (key.startswith("x-amz-meta") or key == "x-amz-acl" or + key.startswith("x-amz-server-side-encryption")) + + +def is_supported_header(key): + """Returns true if a standard supported header.""" + + # Supported headers for object. + supported_headers = [ + "cache-control", + "content-encoding", + "content-type", + "content-disposition", + "content-language", + "x-amz-website-redirect-location", + # Add more supported headers here. + ] + return key.lower() in supported_headers + + +def is_storageclass_header(key): + """Returns true if header is a storage class header.""" + return key.lower() == "x-amz-storage-class" + + +def url_replace( + url, scheme=None, netloc=None, path=None, query=None, fragment=None +): + """Return new URL with replaced properties in given URL.""" + return urllib.parse.SplitResult( + scheme if scheme is not None else url.scheme, + netloc if netloc is not None else url.netloc, + path if path is not None else url.path, + query if query is not None else url.query, + fragment if fragment is not None else url.fragment, + ) diff --git a/testbed/minio__minio-py/minio/lifecycleconfig.py b/testbed/minio__minio-py/minio/lifecycleconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..03f1e07c9b2305be5e9ca2c159653729105026b9 --- /dev/null +++ b/testbed/minio__minio-py/minio/lifecycleconfig.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2015, 2016, 2017, 2018, 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Request/response of PutBucketLifecycleConfiguration and +GetBucketLifecycleConfiguration APIs. +""" +# pylint: disable=invalid-name + +from __future__ import absolute_import + +from abc import ABCMeta + +from .commonconfig import BaseRule, check_status +from .helpers import strftime_rfc3339, strptime_rfc3339 +from .xml import Element, SubElement, find, findall, findtext + + +class DateDays: + """Base class holds date and days of Transition and Expiration.""" + __metaclass__ = ABCMeta + + def __init__(self, date=None, days=None): + self._date = date + self._days = days + + @property + def date(self): + """Get date.""" + return self._date + + @property + def days(self): + """Get days.""" + return self._days + + @staticmethod + def parsexml(element): + """Parse XML to date and days.""" + date = strptime_rfc3339(findtext(element, "Date")) + days = findtext(element, "Days") + if days is not None: + days = int(days) + return date, days + + def toxml(self, element): + """Convert to XML.""" + if self._date is not None: + SubElement( + element, "Date", strftime_rfc3339(self._date), + ) + if self._days: + SubElement(element, "Days", str(self._days)) + return element + + +class Transition(DateDays): + """Transition.""" + + def __init__(self, date=None, days=None, storage_class=None): + super().__init__(date, days) + self._storage_class = storage_class + + @property + def storage_class(self): + """Get storage class.""" + return self._storage_class + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Transition") + date, days = cls.parsexml(element) + return cls(date, days, findtext(element, "StorageClass")) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "NoncurrentVersionTransition") + super().toxml(element) + if self._storage_class: + SubElement(element, "StorageClass", self._storage_class) + return element + + +class NoncurrentVersionTransition: + """Noncurrent version transition.""" + + def __init__(self, noncurrent_days=None, storage_class=None): + self._noncurrent_days = noncurrent_days + self._storage_class = storage_class + + @property + def noncurrent_days(self): + """Get Noncurrent days.""" + return self._noncurrent_days + + @property + def storage_class(self): + """Get storage class.""" + return self._storage_class + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "NoncurrentVersionTransition") + noncurrent_days = findtext(element, "NoncurrentDays") + if noncurrent_days is not None: + noncurrent_days = int(noncurrent_days) + return cls(noncurrent_days, findtext(element, "StorageClass")) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "NoncurrentVersionTransition") + if self._noncurrent_days: + SubElement(element, "NoncurrentDays", str(self._noncurrent_days)) + if self._storage_class: + SubElement(element, "StorageClass", self._storage_class) + return element + + +class NoncurrentVersionExpiration: + """Noncurrent version expiration.""" + + def __init__(self, noncurrent_days=None): + self._noncurrent_days = noncurrent_days + + @property + def noncurrent_days(self): + """Get Noncurrent days.""" + return self._noncurrent_days + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "NoncurrentVersionExpiration") + noncurrent_days = findtext(element, "NoncurrentDays") + if noncurrent_days is not None: + noncurrent_days = int(noncurrent_days) + return cls(noncurrent_days) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "NoncurrentVersionExpiration") + if self._noncurrent_days: + SubElement(element, "NoncurrentDays", str(self._noncurrent_days)) + return element + + +class Expiration(DateDays): + """Expiration.""" + + def __init__(self, date=None, days=None, + expired_object_delete_marker=None): + super().__init__(date, days) + self._expired_object_delete_marker = expired_object_delete_marker + + @property + def expired_object_delete_marker(self): + """Get expired object delete marker.""" + return self._expired_object_delete_marker + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Expiration") + date, days = cls.parsexml(element) + expired_object_delete_marker = findtext( + element, "ExpiredObjectDeleteMarker", + ) + if expired_object_delete_marker is not None: + if expired_object_delete_marker.title() not in ["False", "True"]: + raise ValueError( + "value of ExpiredObjectDeleteMarker must be " + "'True' or 'False'", + ) + expired_object_delete_marker = ( + expired_object_delete_marker.title() == "True" + ) + + return cls(date, days, expired_object_delete_marker) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Expiration") + super().toxml(element) + if self._expired_object_delete_marker is not None: + SubElement( + element, + "ExpiredObjectDeleteMarker", + str(self._expired_object_delete_marker), + ) + return element + + +class AbortIncompleteMultipartUpload: + """Abort incomplete multipart upload.""" + + def __init__(self, days_after_initiation=None): + self._days_after_initiation = days_after_initiation + + @property + def days_after_initiation(self): + """Get days after initiation.""" + return self._days_after_initiation + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "AbortIncompleteMultipartUpload") + days_after_initiation = findtext(element, "DaysAfterInitiation") + if days_after_initiation is not None: + days_after_initiation = int(days_after_initiation) + return cls(days_after_initiation) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "AbortIncompleteMultipartUpload") + if self._days_after_initiation: + SubElement( + element, + "DaysAfterInitiation", + str(self._days_after_initiation), + ) + return element + + +class Rule(BaseRule): + """Lifecycle rule. """ + + def __init__(self, status, abort_incomplete_multipart_upload=None, + expiration=None, rule_filter=None, rule_id=None, + noncurrent_version_expiration=None, + noncurrent_version_transition=None, + transition=None): + check_status(status) + + super().__init__(rule_filter, rule_id) + + self._status = status + self._abort_incomplete_multipart_upload = ( + abort_incomplete_multipart_upload + ) + self._expiration = expiration + self._noncurrent_version_expiration = noncurrent_version_expiration + self._noncurrent_version_transition = noncurrent_version_transition + self._transition = transition + + @property + def status(self): + """Get status.""" + return self._status + + @property + def abort_incomplete_multipart_upload(self): + """Get abort incomplete multipart upload.""" + return self._abort_incomplete_multipart_upload + + @property + def expiration(self): + """Get expiration.""" + return self._expiration + + @property + def noncurrent_version_expiration(self): + """Get noncurrent version expiration.""" + return self._noncurrent_version_expiration + + @property + def noncurrent_version_transition(self): + """Get noncurrent version transition.""" + return self._noncurrent_version_transition + + @property + def transition(self): + """Get transition.""" + return self._transition + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + status = findtext(element, "Status", True) + abort_incomplete_multipart_upload = ( + None if find(element, "AbortIncompleteMultipartUpload") is None + else AbortIncompleteMultipartUpload.fromxml(element) + ) + expiration = ( + None if find(element, "Expiration") is None + else Expiration.fromxml(element) + ) + rule_filter, rule_id = cls.parsexml(element) + noncurrent_version_expiration = ( + None if find(element, "NoncurrentVersionExpiration") is None + else NoncurrentVersionExpiration.fromxml(element) + ) + noncurrent_version_transition = ( + None if find(element, "NoncurrentVersionTransition") is None + else NoncurrentVersionTransition.fromxml(element) + ) + transition = ( + None if find(element, "Transition") is None + else Transition.fromxml(element) + ) + + return cls( + status, + abort_incomplete_multipart_upload=( + abort_incomplete_multipart_upload + ), + expiration=expiration, + rule_filter=rule_filter, + rule_id=rule_id, + noncurrent_version_expiration=noncurrent_version_expiration, + noncurrent_version_transition=noncurrent_version_transition, + transition=transition, + ) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Rule") + SubElement(element, "Status", self._status) + if self._abort_incomplete_multipart_upload: + self._abort_incomplete_multipart_upload.toxml(element) + if self._expiration: + self._expiration.toxml(element) + super().toxml(element) + if self._noncurrent_version_expiration: + self._noncurrent_version_expiration.toxml(element) + if self._noncurrent_version_transition: + self._noncurrent_version_expiration.toxml(element) + if self._transition: + self._transition.toxml(element) + return element + + +class LifecycleConfig: + """Lifecycle configuration.""" + + def __init__(self, rules): + if not rules: + raise ValueError("rules must be provided") + self._rules = rules + + @property + def rules(self): + """Get rules.""" + return self._rules + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + elements = findall(element, "Rule") + rules = [] + for tag in elements: + rules.append(Rule.fromxml(tag)) + return cls(rules) + + def toxml(self, element): + """Convert to XML.""" + element = Element("LifecycleConfiguration") + for rule in self._rules: + rule.toxml(element) + return element diff --git a/testbed/minio__minio-py/minio/parsers.py b/testbed/minio__minio-py/minio/parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..d625d1e94948b9a927d627871cb252d1dc28191b --- /dev/null +++ b/testbed/minio__minio-py/minio/parsers.py @@ -0,0 +1,456 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.parsers +~~~~~~~~~~~~~~~~~~~ + +This module contains core API parsers. + +:copyright: (c) 2015 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from datetime import timezone +from urllib.parse import unquote +from xml.etree import ElementTree +from xml.etree.ElementTree import ParseError + +from .definitions import (Bucket, ListMultipartUploadsResult, ListPartsResult, + MultipartUploadResult, Object) +# minio specific. +from .error import MultiDeleteError, S3Error +from .helpers import strptime_rfc3339 +from .xml_marshal import NOTIFICATIONS_ARN_FIELDNAME_MAP + +# dependencies. + + +_XML_NS = { + 's3': 'http://s3.amazonaws.com/doc/2006-03-01/', +} + + +class S3Element: + """S3 aware XML parsing class. Wraps a root element name and + ElementTree.Element instance. Provides S3 namespace aware parsing + functions. + + """ + + def __init__(self, root_name, element): + self.root_name = root_name + self.element = element + + @classmethod + def fromstring(cls, root_name, data): + """Initialize S3Element from name and XML string data. + + :param name: Name for XML data. Used in XML errors. + :param data: string data to be parsed. + :return: Returns an S3Element. + """ + try: + return cls(root_name, ElementTree.fromstring(data.strip())) + except (ParseError, AttributeError, ValueError, TypeError) as exc: + raise ValueError( + '"{}" XML is not parsable.'.format(root_name), + ) from exc + + def findall(self, name): + """Similar to ElementTree.Element.findall() + + """ + return [ + S3Element(self.root_name, elem) + for elem in self.element.findall('s3:{}'.format(name), _XML_NS) + ] + + def find(self, name): + """Similar to ElementTree.Element.find() + + """ + elt = self.element.find('s3:{}'.format(name), _XML_NS) + return S3Element(self.root_name, elt) if elt else None + + def get_child_text(self, name, strict=True): + """Extract text of a child element. If strict, and child element is + not present, raises ValueError and otherwise returns + None. + + """ + if strict: + try: + return self.element.find('s3:{}'.format(name), _XML_NS).text + except (ParseError, AttributeError, ValueError, TypeError) as exc: + raise ValueError( + ( + 'Invalid XML provided for "{}" - erroring tag <{}>' + ).format(self.root_name, name), + ) from exc + else: + return self.element.findtext('s3:{}'.format(name), None, _XML_NS) + + def get_urldecoded_elem_text(self, name, strict=True): + """Like self.get_child_text(), but also performs urldecode() on the + result. + + """ + text = self.get_child_text(name, strict) + # strictness is already enforced above. + return unquote(text) if text is not None else None + + def get_etag_elem(self, strict=True): + """Fetches an 'ETag' child element suitably processed. + + """ + return self.get_child_text('ETag', strict).replace('"', '') + + def get_int_elem(self, name): + """Fetches an integer type XML child element by name. + + """ + return int(self.get_child_text(name)) + + def get_time_elem(self, name): + """Parse a time XML child element. + + """ + return strptime_rfc3339( + self.get_child_text(name), + ).replace(tzinfo=timezone.utc) + + def text(self): + """Fetch the current node's text + + """ + return self.element.text + + def is_dir(self): + """Returns True if the object is a dir + ie, if an object name has `/` suffixed. + + """ + text = self.get_child_text('Key') + return text.endswith("/") + + +def parse_error_response(response): + """Parser for S3 error response.""" + element = ElementTree.fromstring(response.data.decode()) + + def _get_text(name): + return ( + element.find(name).text if element.find(name) is not None else None + ) + + return S3Error( + _get_text("Code"), + _get_text("Message"), + _get_text("Resource"), + _get_text("RequestId"), + _get_text("HostId"), + bucket_name=_get_text("BucketName"), + object_name=_get_text("Key"), + response=response, + ) + + +def parse_multipart_upload_result(data): + """ + Parser for complete multipart upload response. + + :param data: Response data for complete multipart upload. + :return: :class:`MultipartUploadResult `. + """ + root = S3Element.fromstring('CompleteMultipartUploadResult', data) + + return MultipartUploadResult( + root.get_child_text('Bucket'), + root.get_child_text('Key'), + root.get_child_text('Location'), + root.get_etag_elem() + ) + + +def parse_list_buckets(data): + """ + Parser for list buckets response. + + :param data: Response data for list buckets. + :return: List of :class:`Bucket `. + """ + root = S3Element.fromstring('ListBucketsResult', data) + + return [ + Bucket(bucket.get_child_text('Name'), + bucket.get_time_elem('CreationDate')) + for buckets in root.findall('Buckets') + for bucket in buckets.findall('Bucket') + ] + + +def _parse_objects_from_xml_elts(bucket_name, contents, common_prefixes, + delete_markers=()): + """Internal function that extracts objects and common prefixes from + list_objects responses. + """ + objects = [ + Object( + bucket_name, + content.get_child_text("Key"), + last_modified=content.get_time_elem("LastModified"), + etag=content.get_etag_elem(strict=False), + size=content.get_int_elem("Size"), + is_dir=content.is_dir(), + version_id=content.get_child_text("VersionId", strict=False), + is_latest=content.get_child_text("IsLatest", strict=False), + storage_class=content.get_child_text("StorageClass", strict=False), + owner_id=( + content.find("Owner").get_child_text("ID", strict=False) + if content.find("Owner") else None + ), + owner_name=( + content.find("Owner").get_child_text( + "DisplayName", strict=False, + ) if content.find("Owner") else None + ), + ) for content in contents + ] + + object_dirs = [ + Object(bucket_name, dir_elt.text(), is_dir=True) + for dirs_elt in common_prefixes + for dir_elt in dirs_elt.findall('Prefix') + ] + + markers = [ + Object( + bucket_name, + content.get_child_text("Key"), + last_modified=content.get_time_elem("LastModified"), + is_dir=content.is_dir(), + version_id=content.get_child_text("VersionId", strict=False), + is_latest=content.get_child_text("IsLatest", strict=False), + owner_id=( + content.find("Owner").get_child_text("ID", strict=False) + if content.find("Owner") else None + ), + owner_name=( + content.find("Owner").get_child_text( + "DisplayName", strict=False, + ) if content.find("Owner") else None + ), + delete_marker=True, + ) for content in delete_markers + ] + + return objects, object_dirs, markers + + +def parse_list_objects(data, bucket_name): + """ + Parser for list objects response. + + :param data: Response data for list objects. + :param bucket_name: Response for the bucket. + :return: Replies back three distinctive components. + - List of :class:`Object ` + - True if list is truncated, False otherwise. + - Object name marker for the next request. + """ + root = S3Element.fromstring('ListObjectResult', data) + + is_truncated = root.get_child_text('IsTruncated').lower() == 'true' + # NextMarker element need not be present. + marker = root.get_urldecoded_elem_text('NextMarker', strict=False) + objects, object_dirs, _ = _parse_objects_from_xml_elts( + bucket_name, + root.findall('Contents'), + root.findall('CommonPrefixes') + ) + + if is_truncated and marker is None: + marker = objects[-1].object_name + + return objects + object_dirs, is_truncated, marker + + +def parse_list_objects_v2(data, bucket_name): + """ + Parser for list objects version 2 response. + + :param data: Response data for list objects. + :param bucket_name: Response for the bucket. + :return: Returns three distinct components: + - List of :class:`Object ` + - True if list is truncated, False otherwise. + - Continuation Token for the next request. + """ + root = S3Element.fromstring('ListObjectV2Result', data) + + is_truncated = root.get_child_text('IsTruncated').lower() == 'true' + # NextContinuationToken may not be present. + continuation_token = root.get_child_text('NextContinuationToken', + strict=False) + objects, object_dirs, _ = _parse_objects_from_xml_elts( + bucket_name, + root.findall('Contents'), + root.findall('CommonPrefixes') + ) + + return objects + object_dirs, is_truncated, continuation_token + + +def parse_list_object_versions(data, bucket_name): + """ + Parser for list object versions response. + + :param data: Response data for list objects. + :param bucket_name: Response for the bucket. + :return: Returns three distinct components: + - List of :class:`Object ` + - True if list is truncated, False otherwise. + - Continuation Token for the next request. + """ + root = S3Element.fromstring("ListVersionsResult", data) + + is_truncated = root.get_child_text("IsTruncated").lower() == "true" + + key_marker = root.get_urldecoded_elem_text("NextKeyMarker", strict=False) + version_id_marker = root.get_urldecoded_elem_text( + "NextVersionIdMarker", + strict=False, + ) + + objects, object_dirs, delete_markers = _parse_objects_from_xml_elts( + bucket_name, + root.findall("Version"), + root.findall("CommonPrefixes"), + root.findall("DeleteMarker"), + ) + + return ( + objects + object_dirs + delete_markers, + is_truncated, + key_marker, + version_id_marker, + ) + + +def parse_new_multipart_upload(data): + """ + Parser for new multipart upload response. + + :param data: Response data for new multipart upload. + :return: Returns a upload id. + """ + root = S3Element.fromstring('InitiateMultipartUploadResult', data) + return root.get_child_text('UploadId') + + +def parse_get_bucket_notification(data): + """ + Parser for a get_bucket_notification response from S3. + + :param data: Body of response from get_bucket_notification. + :return: Returns bucket notification configuration + """ + root = S3Element.fromstring('GetBucketNotificationResult', data) + + notifications = _add_notifying_service_config( + root, {}, + 'TopicConfigurations', 'TopicConfiguration' + ) + notifications = _add_notifying_service_config( + root, notifications, + 'QueueConfigurations', 'QueueConfiguration' + ) + notifications = _add_notifying_service_config( + root, notifications, + 'CloudFunctionConfigurations', 'CloudFunctionConfiguration' + ) + + return notifications + + +def _add_notifying_service_config(data, notifications, service_key, + service_xml_tag): + """Add service configuration in notification.""" + + arn_elt_name = NOTIFICATIONS_ARN_FIELDNAME_MAP[service_xml_tag] + config = [] + for service in data.findall(service_xml_tag): + config_item = {} + config_item['Id'] = service.get_child_text('Id') + config_item['Arn'] = service.get_child_text(arn_elt_name) + config_item['Events'] = [ + event.text() for event in service.findall('Event') + ] + filter_terms = [ + { + 'Key': { + 'FilterRules': [ + { + 'Name': xml_filter_rule.get_child_text('Name'), + 'Value': xml_filter_rule.get_child_text('Value'), + } + for xml_filter_rule in xml_filter_rules.findall( + './S3Key/FilterRule') + ] + } + } + for xml_filter_rules in service.findall('Filter') + ] + if len(filter_terms) > 0: + config_item['Filter'] = filter_terms + config.append(config_item) + + if len(config) > 0: + notifications[service_key] = config + + return notifications + + +def parse_multi_delete_response(data): + """Parser for Multi-Object Delete API response. + + :param data: XML response body content from service. + + :return: Returns list of error objects for each delete object that + had an error. + + """ + root = S3Element.fromstring('MultiObjectDeleteResult', data) + return [ + MultiDeleteError(errtag.get_child_text('Key'), + errtag.get_child_text('Code'), + errtag.get_child_text('Message')) + for errtag in root.findall('Error') + ] + + +def parse_list_multipart_uploads(data): + """Parse ListMultipartUploads API resppnse XML.""" + return ListMultipartUploadsResult( + S3Element.fromstring("ListMultipartUploadsResult", data), + ) + + +def parse_list_parts(data): + """Parse ListParts API resppnse XML.""" + return ListPartsResult(S3Element.fromstring("ListPartsResult", data)) diff --git a/testbed/minio__minio-py/minio/post_policy.py b/testbed/minio__minio-py/minio/post_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb5e803957c107cf32221cc397cb8215ef4f22b --- /dev/null +++ b/testbed/minio__minio-py/minio/post_policy.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2015, 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.post_policy +~~~~~~~~~~~~~~~ + +This module contains :class:`PostPolicy ` implementation. + +:copyright: (c) 2015 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +import base64 +import datetime +import json + +from .helpers import check_bucket_name, check_non_empty_string + + +# Policy explanation: +# http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html +class PostPolicy: + """ + A :class:`PostPolicy ` object for constructing + Amazon S3 POST policy JSON string. + """ + + def __init__(self): + self._expiration = None + self._content_length_range = tuple() + # publicly accessible + self.policies = [] + self.form_data = dict() + self.bucket_name = '' + self.key = '' + + def set_expires(self, time): + """ + Set expiration time :class:`datetime.datetime`. + + :param time: set expiration :class:`datetime.datetime`. + """ + if time.toordinal() < 1: + ValueError() + self._expiration = time + + def set_key(self, key): + """ + Set key policy condition. + + :param key: set key name. + """ + check_non_empty_string(key) + + self.policies.append(('eq', '$key', key)) + self.form_data['key'] = key + self.key = key + + def set_key_startswith(self, key_startswith): + """ + Set key startswith policy condition. + + :param key_startswith: set key prefix name. + """ + check_non_empty_string(key_startswith) + + self.policies.append(('starts-with', '$key', key_startswith)) + self.form_data['key'] = key_startswith + + def set_bucket_name(self, bucket_name): + """ + Set bucket name policy condition. + + :param bucket_name: set bucket name. + """ + check_bucket_name(bucket_name) + + self.policies.append(('eq', '$bucket', bucket_name)) + self.form_data['bucket'] = bucket_name + self.bucket_name = bucket_name + + def set_content_type(self, content_type): + """ + Set content-type policy condition. + + :param content_type: set content type name. + """ + self.policies.append(('eq', '$Content-Type', content_type)) + self.form_data['Content-Type'] = content_type + + def set_content_length_range(self, min_length, max_length): + """ + Set content length range policy condition. + Raise :exc:`ValueError` for invalid inputs. + + :param min_length: Minimum length limit for content size. + :param max_length: Maximum length limit for content size. + """ + err_msg = ('Min-length ({}) must be <= Max-length ({}), ' + 'and they must be non-negative.').format( + min_length, max_length) + if min_length > max_length or min_length < 0 or max_length < 0: + raise ValueError(err_msg) + + self._content_length_range = (min_length, max_length) + + def append_policy(self, condition, target, value): + """Append policy.""" + self.policies.append([condition, target, value]) + + def _marshal_json(self, extras=()): + """ + Marshal various policies into json str/bytes. + """ + policies = self.policies[:] + policies.extend(extras) + if self._content_length_range: + policies.append(['content-length-range'] + + list(self._content_length_range)) + + policy_stmt = { + "expiration": self._expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z"), + } + + if policies: + policy_stmt["conditions"] = policies + + return json.dumps(policy_stmt) + + def base64(self, extras=()): + """ + Encode json into base64. + """ + data = self._marshal_json(extras=extras) + if not isinstance(data, bytes): + data = data.encode('utf-8') + b64enc = base64.b64encode(data) + return b64enc.decode('utf-8') if isinstance(b64enc, bytes) else b64enc + + def is_valid(self): + """ + Validate for required parameters. + """ + if not isinstance(self._expiration, datetime.datetime): + raise ValueError("Expiration datetime must be specified.") + + if 'key' not in self.form_data: + raise ValueError("object key must be specified.") + + if 'bucket' not in self.form_data: + raise ValueError("bucket name must be specified.") diff --git a/testbed/minio__minio-py/minio/replicationconfig.py b/testbed/minio__minio-py/minio/replicationconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..c372f4a682e4327d0bd08cb82e88515ae4c5f46b --- /dev/null +++ b/testbed/minio__minio-py/minio/replicationconfig.py @@ -0,0 +1,497 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Request/response of PutBucketReplication and GetBucketReplication APIs.""" + +from __future__ import absolute_import + +from abc import ABCMeta + +from .commonconfig import DISABLED, BaseRule, check_status +from .xml import Element, SubElement, find, findall, findtext + + +class Status: + """Status.""" + __metaclass__ = ABCMeta + + def __init__(self, status): + check_status(status) + self._status = status + + @property + def status(self): + """Get status.""" + return self._status + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, cls.__name__) + return cls(findtext(element, "Status", True)) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, self.__class__.__name__) + SubElement(element, "Status", self._status) + return element + + +class SseKmsEncryptedObjects(Status): + """SSE KMS encrypted objects.""" + + +class SourceSelectionCriteria: + """Source selection criteria.""" + + def __init__(self, sse_kms_encrypted_objects=None): + self._sse_kms_encrypted_objects = sse_kms_encrypted_objects + + @property + def sse_kms_encrypted_objects(self): + """Get SSE KMS encrypted objects.""" + return self._sse_kms_encrypted_objects + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "SourceSelectionCriteria") + return cls( + None if find(element, "SseKmsEncryptedObjects") is None + else SseKmsEncryptedObjects.fromxml(element) + ) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "SourceSelectionCriteria") + if self._sse_kms_encrypted_objects: + self._sse_kms_encrypted_objects.toxml(element) + return element + + +class ExistingObjectReplication(Status): + """Existing object replication.""" + + +class DeleteMarkerReplication(Status): + """Delete marker replication.""" + + def __init__(self, status=DISABLED): + super().__init__(status) + + +class ReplicationTimeValue: + """Replication time value.""" + __metaclass__ = ABCMeta + + def __init__(self, minutes=15): + self._minutes = minutes + + @property + def minutes(self): + """Get minutes.""" + return self._minutes + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, cls.__name__) + minutes = findtext(element, "Minutes") + if minutes is not None: + minutes = int(minutes) + return cls(minutes) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, self.__class__.__name__) + if self._minutes is not None: + SubElement(element, "Minutes", str(self._minutes)) + return element + + +class Time(ReplicationTimeValue): + """Time.""" + + +class ReplicationTime: + """Replication time.""" + + def __init__(self, time, status): + if not time: + raise ValueError("time must be provided") + check_status(status) + self._time = time + self._status = status + + @property + def time(self): + """Get time value.""" + return self._time + + @property + def status(self): + """Get status.""" + return self._status + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "ReplicationTime") + time = Time.fromxml(element) + status = findtext(element, "Status", True) + return cls(time, status) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "ReplicationTime") + self._time.toxml(element) + SubElement(element, "Status", self._status) + return element + + +class EventThreshold(ReplicationTimeValue): + """Event threshold.""" + + +class Metrics: + """Metrics.""" + + def __init__(self, event_threshold, status): + if not event_threshold: + raise ValueError("event threshold must be provided") + check_status(status) + self._event_threshold = event_threshold + self._status = status + + @property + def event_threshold(self): + """Get event threshold.""" + return self._event_threshold + + @property + def status(self): + """Get status.""" + return self._status + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Metrics") + event_threshold = EventThreshold.fromxml(element) + status = findtext(element, "Status", True) + return cls(event_threshold, status) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Metrics") + self._event_threshold.toxml(element) + SubElement(element, "Status", self._status) + return element + + +class EncryptionConfig: + """Encryption configuration.""" + + def __init__(self, replica_kms_key_id=None): + self._replica_kms_key_id = replica_kms_key_id + + @property + def replica_kms_key_id(self): + """Get replica KMS key ID.""" + return self._replica_kms_key_id + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "EncryptionConfiguration") + return cls(findtext(element, "ReplicaKmsKeyID")) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "EncryptionConfiguration") + SubElement(element, "ReplicaKmsKeyID", self._replica_kms_key_id) + return element + + +class AccessControlTranslation: + """Access control translation.""" + + def __init__(self, owner="Destination"): + if not owner: + raise ValueError("owner must be provided") + self._owner = owner + + @property + def owner(self): + """Get owner.""" + return self._owner + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "AccessControlTranslation") + return cls(findtext(element, "Owner")) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "AccessControlTranslation") + SubElement(element, "Owner", self._owner) + return element + + +class Destination: + """Replication destination.""" + + def __init__(self, bucket_arn, + access_control_translation=None, account=None, + encryption_config=None, metrics=None, + replication_time=None, storage_class=None): + if not bucket_arn: + raise ValueError("bucket ARN must be provided") + self._bucket_arn = bucket_arn + self._access_control_translation = access_control_translation + self._account = account + self._encryption_config = encryption_config + self._metrics = metrics + self._replication_time = replication_time + self._storage_class = storage_class + + @property + def bucket_arn(self): + """Get bucket ARN.""" + return self._bucket_arn + + @property + def access_control_translation(self): + """Get access control translation. """ + return self._access_control_translation + + @property + def account(self): + """Get account.""" + return self._account + + @property + def encryption_config(self): + """Get encryption configuration.""" + return self._encryption_config + + @property + def metrics(self): + """Get metrics.""" + return self._metrics + + @property + def replication_time(self): + """Get replication time.""" + return self._replication_time + + @property + def storage_class(self): + """Get storage class.""" + return self._storage_class + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + element = find(element, "Destination") + access_control_translation = ( + None if find(element, "AccessControlTranslation") is None + else AccessControlTranslation.fromxml(element) + ) + account = findtext(element, "Account") + bucket_arn = findtext(element, "Bucket", True) + encryption_config = ( + None if find(element, "EncryptionConfiguration") is None + else EncryptionConfig.fromxml(element) + ) + metrics = ( + None if find(element, "Metrics") is None + else Metrics.fromxml(element) + ) + replication_time = ( + None if find(element, "ReplicationTime") is None + else ReplicationTime.fromxml(element) + ) + storage_class = findtext(element, "StorageClass") + return cls(bucket_arn, access_control_translation, account, + encryption_config, metrics, replication_time, storage_class) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Destination") + if self._access_control_translation: + self._access_control_translation.toxml(element) + if self._account is not None: + SubElement(element, "Account", self._account) + SubElement(element, "Bucket", self._bucket_arn) + if self._encryption_config: + self._encryption_config.toxml(element) + if self._metrics: + self._metrics.toxml(element) + if self._replication_time: + self._replication_time.toxml(element) + if self._storage_class: + SubElement(element, "StorageClass", self._storage_class) + return element + + +class Rule(BaseRule): + """Replication rule. """ + + def __init__(self, destination, status, + delete_marker_replication=None, + existing_object_replication=None, + rule_filter=None, rule_id=None, prefix=None, + priority=None, source_selection_criteria=None): + if not destination: + raise ValueError("destination must be provided") + + check_status(status) + + super().__init__(rule_filter, rule_id) + + self._destination = destination + self._status = status + if rule_filter and not delete_marker_replication: + delete_marker_replication = DeleteMarkerReplication() + self._delete_marker_replication = delete_marker_replication + self._existing_object_replication = existing_object_replication + self._prefix = prefix + self._priority = priority + self._source_selection_criteria = source_selection_criteria + + @property + def destination(self): + """Get destination.""" + return self._destination + + @property + def status(self): + """Get status.""" + return self._status + + @property + def delete_marker_replication(self): + """Get delete marker replication.""" + return self._delete_marker_replication + + @property + def existing_object_replication(self): + """Get existing object replication.""" + return self._existing_object_replication + + @property + def prefix(self): + """Get prefix.""" + return self._prefix + + @property + def priority(self): + """Get priority.""" + return self._priority + + @property + def source_selection_criteria(self): + """Get source selection criteria.""" + return self._source_selection_criteria + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + delete_marker_replication = ( + None if find(element, "DeleteMarkerReplication") is None + else DeleteMarkerReplication.fromxml(element) + ) + destination = Destination.fromxml(element) + existing_object_replication = ( + None if find(element, "ExistingObjectReplication") is None + else ExistingObjectReplication.fromxml(element) + ) + rule_filter, rule_id = cls.parsexml(element) + prefix = findtext(element, "Prefix") + priority = findtext(element, "Priority") + if priority: + priority = int(priority) + source_selection_criteria = ( + None if find(element, "SourceSelectionCriteria") is None + else SourceSelectionCriteria.fromxml(element) + ) + status = findtext(element, "Status", True) + + return cls(destination, status, delete_marker_replication, + existing_object_replication, rule_filter, + rule_id, prefix, priority, source_selection_criteria) + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "Rule") + if self._delete_marker_replication: + self._delete_marker_replication.toxml(element) + self._destination.toxml(element) + if self._existing_object_replication: + self._existing_object_replication.toxml(element) + super().toxml(element) + if self._prefix is not None: + SubElement(element, "Prefix", self._prefix) + if self._priority is not None: + SubElement(element, "Priority", str(self._priority)) + if self._source_selection_criteria: + self._source_selection_criteria.toxml(element) + SubElement(element, "Status", self._status) + return element + + +class ReplicationConfig: + """Replication configuration.""" + + def __init__(self, role, rules): + if not role: + raise ValueError("role must be provided") + if not rules: + raise ValueError("rules must be provided") + if len(rules) > 1000: + raise ValueError("more than 1000 rules are not supported") + self._role = role + self._rules = rules + + @property + def role(self): + """Get role.""" + return self._role + + @property + def rules(self): + """Get rules.""" + return self._rules + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + role = findtext(element, "Role", True) + elements = findall(element, "Rule") + rules = [] + for tag in elements: + rules.append(Rule.fromxml(tag)) + return cls(role, rules) + + def toxml(self, element): + """Convert to XML.""" + element = Element("ReplicationConfiguration") + SubElement(element, "Role", self._role) + for rule in self._rules: + rule.toxml(element) + return element diff --git a/testbed/minio__minio-py/minio/select/__init__.py b/testbed/minio__minio-py/minio/select/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4da89ef5fee433d5e715fd284664725c54f061fc --- /dev/null +++ b/testbed/minio__minio-py/minio/select/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +:copyright: (c) 2019 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. +""" + +__title__ = 'minio-py' +__author__ = 'MinIO, Inc.' +__version__ = '0.1.0' +__license__ = 'Apache 2.0' +__copyright__ = 'Copyright 2019 MinIO, Inc.' + +# pylint: disable=unused-import +from .errors import SelectCRCValidationError, SelectMessageError +from .helpers import (byte_int, calculate_crc, # pylint: disable=unused-import + validate_crc) +from .reader import SelectObjectReader # pylint: disable=unused-import diff --git a/testbed/minio__minio-py/minio/select/errors.py b/testbed/minio__minio-py/minio/select/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..b25867c5d45d9483f9becb1104c7b36a9abfeaa7 --- /dev/null +++ b/testbed/minio__minio-py/minio/select/errors.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.select.errors +~~~~~~~~~~~~~~~ + +This module implements the error classes for SelectObject responses. + +:copyright: (c) 2019 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + + +class SelectMessageError(Exception): + ''' + Raised in case of message type 'error' + ''' + + +class SelectCRCValidationError(Exception): + ''' + Raised in case of CRC mismatch + ''' diff --git a/testbed/minio__minio-py/minio/select/helpers.py b/testbed/minio__minio-py/minio/select/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..6d0147a9e5153a5dd481d0f9ea0c9a44be2aeacd --- /dev/null +++ b/testbed/minio__minio-py/minio/select/helpers.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.select.helpers +~~~~~~~~~~~~~~~ + +This module implements the helper functions for SelectObject responses. + +:copyright: (c) 2019 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +import codecs +from binascii import crc32 + +EVENT_RECORDS = 'Records' # Event Type is Records +EVENT_PROGRESS = 'Progress' # Event Type Progress +EVENT_STATS = 'Stats' # Event Type Stats +EVENT_CONT = 'Cont' # Event Type continue +EVENT_END = 'End' # Event Type is End +EVENT_CONTENT_TYPE = "text/xml" # Event content xml type +EVENT = 'event' # Message Type is event +ERROR = 'error' # Message Type is error + + +def calculate_crc(value): + ''' + Returns the CRC using crc32 + ''' + return crc32(value) & 0xffffffff + + +def validate_crc(current_value, expected_value): + ''' + Validate through CRC check + ''' + return calculate_crc(current_value) == byte_int(expected_value) + + +def byte_int(data_bytes): + ''' + Convert bytes to big-endian integer + ''' + return int(codecs.encode(data_bytes, 'hex'), 16) diff --git a/testbed/minio__minio-py/minio/select/reader.py b/testbed/minio__minio-py/minio/select/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..e63fc638f3573d432ec16021cbd3a7c5f51db8e7 --- /dev/null +++ b/testbed/minio__minio-py/minio/select/reader.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.select.reader +~~~~~~~~~~~~~~~ + +This module implements the reader for SelectObject response body. + +:copyright: (c) 2019 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from __future__ import absolute_import + +import io +import sys +from xml.etree import ElementTree + +from .errors import SelectCRCValidationError, SelectMessageError +from .helpers import (ERROR, EVENT, EVENT_CONTENT_TYPE, EVENT_RECORDS, + EVENT_STATS, byte_int, calculate_crc, validate_crc) + + +def _extract_header(header_bytes): + """ + populates the header map after reading the header in bytes + """ + header_map = {} + header_byte_parsed = 0 + # While loop ends when all the headers present are read + # header contains multipe headers + while header_byte_parsed < len(header_bytes): + header_name_byte_length = byte_int( + header_bytes[header_byte_parsed:header_byte_parsed+1]) + header_byte_parsed += 1 + header_name = header_bytes[ + header_byte_parsed:header_byte_parsed+header_name_byte_length + ] + header_byte_parsed += header_name_byte_length + # Header Value Type is of 1 bytes and is skipped + header_byte_parsed += 1 + value_string_byte_length = byte_int( + header_bytes[header_byte_parsed:header_byte_parsed+2] + ) + header_byte_parsed += 2 + header_value = header_bytes[ + header_byte_parsed:header_byte_parsed+value_string_byte_length + ] + header_byte_parsed += value_string_byte_length + header_map[header_name.decode( + "utf-8").lstrip(":")] = header_value.decode("utf-8").lstrip(":") + return header_map + + +def _parse_stats(stats): + """ + Parses stats XML and populates the stat dict. + """ + stat = {} + for attribute in ElementTree.fromstring(stats): + if attribute.tag == 'BytesScanned': + stat['BytesScanned'] = attribute.text + elif attribute.tag == 'BytesProcessed': + stat['BytesProcessed'] = attribute.text + elif attribute.tag == 'BytesReturned': + stat['BytesReturned'] = attribute.text + + return stat + + +class SelectObjectReader: + """ + SelectObjectReader returns a Reader that upon read + returns queried data, but stops when the response ends. + LimitedRandomReader is compatible with BufferedIOBase. + """ + + def __init__(self, response): + self.response = response + self.remaining_bytes = bytes() + self.stat = {} + self.prog = {} + + def readable(self): # pylint: disable=no-self-use + """Return this is readable.""" + return True + + def writeable(self): # pylint: disable=no-self-use + """Return this is not writeable.""" + return False + + def close(self): + """Close response.""" + self.response.close() + + def stats(self): + """Get stats information.""" + return self.stat + + def progress(self): + """Get progress information.""" + return self.prog + + def __extract_message(self): + """ + Process the response sent from server. + https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectSELECTContent.html + """ + + crc_bytes = io.BytesIO() + total_bytes_len = self.response.read(4) + if not total_bytes_len: + return {} + + total_length = byte_int(total_bytes_len) + header_bytes_len = self.response.read(4) + if not header_bytes_len: + return {} + + header_len = byte_int(header_bytes_len) + + crc_bytes.write(total_bytes_len) + crc_bytes.write(header_bytes_len) + + prelude_bytes_crc = self.response.read(4) + if not validate_crc(crc_bytes.getvalue(), prelude_bytes_crc): + raise SelectCRCValidationError( + {"Checksum Mismatch, PreludeCRC of " + + str(calculate_crc(crc_bytes.getvalue())) + + " does not equal expected CRC of " + + str(byte_int(prelude_bytes_crc))}) + + crc_bytes.write(prelude_bytes_crc) + + header_bytes = self.response.read(header_len) + if not header_bytes: + raise SelectMessageError( + "Premature truncation of select message header" + + ", server is sending corrupt message?") + + crc_bytes.write(header_bytes) + + header_map = _extract_header(header_bytes) + payload_length = total_length - header_len - int(16) + payload_bytes = b'' + event_type = header_map["event-type"] + + if header_map["message-type"] == ERROR: + raise SelectMessageError( + header_map["error-code"] + ":\"" + + header_map["error-message"] + "\"") + + if header_map["message-type"] != EVENT: + raise SelectMessageError( + "Unrecognized message-type {0}".format( + header_map["message-type"]) + ) + + if event_type == EVENT_STATS: + content_type = header_map["content-type"] + if content_type != EVENT_CONTENT_TYPE: + raise SelectMessageError( + "Unrecognized content-type {0}".format(content_type)) + + payload_bytes = self.response.read(payload_length) + self.stat = _parse_stats(payload_bytes) + elif event_type == EVENT_RECORDS: + payload_bytes = self.response.read(payload_length) + + crc_bytes.write(payload_bytes) + + message_crc = self.response.read(4) + if not message_crc: + return {} + + if not validate_crc(crc_bytes.getvalue(), message_crc): + raise SelectCRCValidationError( + {"Checksum Mismatch, MessageCRC of " + + str(calculate_crc(crc_bytes.getvalue())) + + " does not equal expected CRC of " + + str(byte_int(message_crc))}) + + message = {event_type: payload_bytes} + return message + + def stream(self, num_bytes=32*1024): + """ + extract each record from the response body ... and buffer it. + send only up to requested bytes such as message[:num_bytes] + rest is buffered and added to the next iteration. + + caller should call self.close() to close the stream. + """ + while not self.response.isclosed(): + if not self.remaining_bytes: + message = self.__extract_message() + if EVENT_RECORDS not in message: + continue + + self.remaining_bytes = message.get(EVENT_RECORDS, b'') + + result = self.remaining_bytes + if num_bytes < len(self.remaining_bytes): + result = self.remaining_bytes[:num_bytes] + self.remaining_bytes = self.remaining_bytes[len(result):] + + if result == b'': + break + if sys.version_info.major == 3: + yield result.decode('utf-8', errors='ignore') + else: + # Python 2.x needs explicit conversion. + yield result.decode('utf-8', errors='ignore').encode('utf-8') diff --git a/testbed/minio__minio-py/minio/selectrequest.py b/testbed/minio__minio-py/minio/selectrequest.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4156d81e0d797bf53734b6ae97e9e93f78acdd --- /dev/null +++ b/testbed/minio__minio-py/minio/selectrequest.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Request/response of PutBucketReplication and GetBucketReplication APIs.""" + +from __future__ import absolute_import + +from abc import ABCMeta + +from .xml import Element, SubElement + +COMPRESSION_TYPE_NONE = "NONE" +COMPRESSION_TYPE_GZIP = "GZIP" +COMPRESSION_TYPE_BZIP2 = "BZIP2" + +FILE_HEADER_INFO_USE = "USE" +FILE_HEADER_INFO_IGNORE = "IGNORE" +FILE_HEADER_INFO_NONE = "NONE" + +JSON_TYPE_DOCUMENT = "DOCUMENT" +JSON_TYPE_LINES = "LINES" + +QUOTE_FIELDS_ALWAYS = "ALWAYS" +QUOTE_FIELDS_ASNEEDED = "ASNEEDED" + + +class InputSerialization: + """Input serialization.""" + + __metaclass__ = ABCMeta + + def __init__(self, compression_type): + if ( + compression_type is not None and + compression_type not in [ + COMPRESSION_TYPE_NONE, + COMPRESSION_TYPE_GZIP, + COMPRESSION_TYPE_BZIP2, + ] + ): + raise ValueError( + "compression type must be {0}, {1} or {2}".format( + COMPRESSION_TYPE_NONE, + COMPRESSION_TYPE_GZIP, + COMPRESSION_TYPE_BZIP2, + ), + ) + self._compression_type = compression_type + + def toxml(self, element): + """Convert to XML.""" + if self._compression_type is not None: + SubElement(element, "CompressionType") + return element + + +class CSVInputSerialization(InputSerialization): + """CSV input serialization.""" + + def __init__(self, compression_type=None, + allow_quoted_record_delimiter=None, comments=None, + field_delimiter=None, file_header_info=None, + quote_character=None, quote_escape_character=None, + record_delimiter=None): + super().__init__(compression_type) + self._allow_quoted_record_delimiter = allow_quoted_record_delimiter + self._comments = comments + self._field_delimiter = field_delimiter + if ( + file_header_info is not None and + file_header_info not in [ + FILE_HEADER_INFO_USE, + FILE_HEADER_INFO_IGNORE, + FILE_HEADER_INFO_NONE, + ] + ): + raise ValueError( + "file header info must be {0}, {1} or {2}".format( + FILE_HEADER_INFO_USE, + FILE_HEADER_INFO_IGNORE, + FILE_HEADER_INFO_NONE, + ), + ) + self._file_header_info = file_header_info + self._quote_character = quote_character + self._quote_escape_character = quote_escape_character + self._record_delimiter = record_delimiter + + def toxml(self, element): + """Convert to XML.""" + super().toxml(element) + element = SubElement(element, "CSV") + if self._allow_quoted_record_delimiter is not None: + SubElement( + element, + "AllowQuotedRecordDelimiter", + self._allow_quoted_record_delimiter, + ) + if self._comments is not None: + SubElement(element, "Comments", self._comments) + if self._field_delimiter is not None: + SubElement(element, "FieldDelimiter", self._field_delimiter) + if self._file_header_info is not None: + SubElement(element, "FileHeaderInfo", self._file_header_info) + if self._quote_character is not None: + SubElement(element, "QuoteCharacter", self._quote_character) + if self._quote_escape_character is not None: + SubElement( + element, + "QuoteEscapeCharacter", + self._quote_escape_character, + ) + if self._record_delimiter is not None: + SubElement(element, "RecordDelimiter", self._record_delimiter) + + +class JSONInputSerialization(InputSerialization): + """JSON input serialization.""" + + def __init__(self, compression_type=None, json_type=None): + super().__init__(compression_type) + if ( + json_type is not None and + json_type not in [JSON_TYPE_DOCUMENT, JSON_TYPE_LINES] + ): + raise ValueError( + "json type must be {0} or {1}".format( + JSON_TYPE_DOCUMENT, JSON_TYPE_LINES, + ), + ) + self._json_type = json_type + + def toxml(self, element): + """Convert to XML.""" + super().toxml(element) + element = SubElement(element, "JSON") + if self._json_type is not None: + SubElement(element, "Type", self._json_type) + + +class ParquetInputSerialization(InputSerialization): + """Parquet input serialization.""" + + def __init__(self, compression_type=None): + super().__init__(compression_type) + + def toxml(self, element): + """Convert to XML.""" + super().toxml(element) + return SubElement(element, "Parquet") + + +class CSVOutputSerialization: + """CSV output serialization.""" + + def __init__(self, field_delimiter=None, quote_character=None, + quote_escape_character=None, quote_fields=None, + record_delimiter=None): + self._field_delimiter = field_delimiter + self._quote_character = quote_character + self._quote_escape_character = quote_escape_character + if ( + quote_fields is not None and + quote_fields not in [ + QUOTE_FIELDS_ALWAYS, QUOTE_FIELDS_ASNEEDED, + ] + ): + raise ValueError( + "quote fields must be {0} or {1}".format( + QUOTE_FIELDS_ALWAYS, QUOTE_FIELDS_ASNEEDED, + ), + ) + self._quote_fields = quote_fields + self._record_delimiter = record_delimiter + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "CSV") + if self._field_delimiter is not None: + SubElement(element, "FieldDelimiter", self._field_delimiter) + if self._quote_character is not None: + SubElement(element, "QuoteCharacter", self._quote_character) + if self._quote_escape_character is not None: + SubElement( + element, + "QuoteEscapeCharacter", + self._quote_escape_character, + ) + if self._quote_fields is not None: + SubElement(element, "QuoteFields", self._quote_fields) + if self._record_delimiter is not None: + SubElement(element, "RecordDelimiter", self._record_delimiter) + + +class JSONOutputSerialization: + """JSON output serialization.""" + + def __init__(self, record_delimiter=None): + self._record_delimiter = record_delimiter + + def toxml(self, element): + """Convert to XML.""" + element = SubElement(element, "JSON") + if self._record_delimiter is not None: + SubElement(element, "RecordDelimiter", self._record_delimiter) + + +class SelectRequest: + """Select object content request.""" + + def __init__(self, expression, input_serialization, output_serialization, + request_progress=False, scan_start_range=None, + scan_end_range=None): + self._expession = expression + if not isinstance( + input_serialization, + ( + CSVInputSerialization, + JSONInputSerialization, + ParquetInputSerialization, + ), + ): + raise ValueError( + "input serialization must be CSVInputSerialization, " + "JSONInputSerialization or ParquetInputSerialization type", + ) + self._input_serialization = input_serialization + if not isinstance( + output_serialization, + (CSVOutputSerialization, JSONOutputSerialization), + ): + raise ValueError( + "output serialization must be CSVOutputSerialization or " + "JSONOutputSerialization type", + ) + self._output_serialization = output_serialization + self._request_progress = request_progress + self._scan_start_range = scan_start_range + self._scan_end_range = scan_end_range + + def toxml(self, element): + """Convert to XML.""" + element = Element("SelectObjectContentRequest") + SubElement(element, "Expression", self._expession) + SubElement(element, "ExpressionType", "SQL") + self._input_serialization.toxml( + SubElement(element, "InputSerialization"), + ) + self._output_serialization.toxml( + SubElement(element, "OutputSerialization"), + ) + if self._request_progress: + SubElement( + SubElement(element, "RequestProgress"), "Enabled", "true", + ) + if self._scan_start_range or self._scan_end_range: + tag = SubElement(element, "ScanRange") + if self._scan_start_range: + SubElement(tag, "Start", self._scan_start_range) + if self._scan_end_range: + SubElement(tag, "End", self._scan_end_range) + return element diff --git a/testbed/minio__minio-py/minio/signer.py b/testbed/minio__minio-py/minio/signer.py new file mode 100644 index 0000000000000000000000000000000000000000..7777b11076337631d4601104e3456c95ab13d4d8 --- /dev/null +++ b/testbed/minio__minio-py/minio/signer.py @@ -0,0 +1,335 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015-2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""" +minio.signer +~~~~~~~~~~~~~~~ + +This module implements all helpers for AWS Signature version '4' support. + +:copyright: (c) 2015 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +import hashlib +import hmac +import re +from collections import OrderedDict +from urllib.parse import SplitResult + +from .helpers import queryencode, sha256_hash + +SIGN_V4_ALGORITHM = 'AWS4-HMAC-SHA256' +AMZ_DATE_FORMAT = "%Y%m%dT%H%M%SZ" +_MULTI_SPACE_REGEX = re.compile(r"( +)") +_SIGNER_DATE_FORMAT = "%Y%m%d" + + +def _hmac_hash(key, data, hexdigest=False): + """Return HMacSHA256 digest of given key and data.""" + + hasher = hmac.new(key, data, hashlib.sha256) + return hasher.hexdigest() if hexdigest else hasher.digest() + + +def _get_scope(date, region, service_name): + """Get scope string.""" + + return "{0}/{1}/{2}/aws4_request".format( + date.strftime(_SIGNER_DATE_FORMAT), region, service_name, + ) + + +def _get_canonical_headers(headers): + """Get canonical headers.""" + + canonical_headers = {} + for key, values in headers.items(): + key = key.lower() + if key not in ( + "authorization", "content-type", + "content-length", "user-agent", + ): + values = values if isinstance(values, (list, tuple)) else [values] + canonical_headers[key] = ",".join([ + _MULTI_SPACE_REGEX.sub(" ", value) for value in values + ]) + + canonical_headers = OrderedDict(sorted(canonical_headers.items())) + signed_headers = ";".join(canonical_headers.keys()) + canonical_headers = "\n".join( + [ + "{0}:{1}".format(key, value) + for key, value in canonical_headers.items() + ], + ) + return canonical_headers, signed_headers + + +def _get_canonical_query_string(query): + """Get canonical query string.""" + + query = query or "" + return "&".join( + [ + "=".join(pair) for pair in sorted( + [params.split("=") for params in query.split("&")], + ) + ], + ) + + +def _get_canonical_request_hash(method, url, headers, content_sha256): + """Get canonical request hash.""" + + canonical_headers, signed_headers = _get_canonical_headers(headers) + canonical_query_string = _get_canonical_query_string(url.query) + + # CanonicalRequest = + # HTTPRequestMethod + '\n' + + # CanonicalURI + '\n' + + # CanonicalQueryString + '\n' + + # CanonicalHeaders + '\n\n' + + # SignedHeaders + '\n' + + # HexEncode(Hash(RequestPayload)) + canonical_request = ( + "{method}\n" + "{canonical_uri}\n" + "{canonical_query_string}\n" + "{canonical_headers}\n\n" + "{signed_headers}\n" + "{content_sha256}" + ).format( + method=method, + canonical_uri=url.path, + canonical_query_string=canonical_query_string, + canonical_headers=canonical_headers, + signed_headers=signed_headers, + content_sha256=content_sha256, + ) + return sha256_hash(canonical_request), signed_headers + + +def _get_string_to_sign(date, scope, canonical_request_hash): + """Get string-to-sign.""" + + return ( + "AWS4-HMAC-SHA256\n{date}\n{scope}\n{canonical_request_hash}".format( + date=date.strftime(AMZ_DATE_FORMAT), + scope=scope, + canonical_request_hash=canonical_request_hash, + ) + ) + + +def _get_signing_key(secret_key, date, region, service_name): + """Get signing key.""" + + date_key = _hmac_hash( + ("AWS4" + secret_key).encode(), + date.strftime(_SIGNER_DATE_FORMAT).encode(), + ) + date_region_key = _hmac_hash(date_key, region.encode()) + date_region_service_key = _hmac_hash( + date_region_key, service_name.encode(), + ) + return _hmac_hash(date_region_service_key, b"aws4_request") + + +def _get_signature(signing_key, string_to_sign): + """Get signature.""" + + return _hmac_hash(signing_key, string_to_sign.encode(), hexdigest=True) + + +def _get_authorization(access_key, scope, signed_headers, signature): + """Get authorization.""" + + return ( + "AWS4-HMAC-SHA256 Credential={access_key}/{scope}, " + "SignedHeaders={signed_headers}, Signature={signature}" + ).format( + access_key=access_key, + scope=scope, + signed_headers=signed_headers, + signature=signature, + ) + + +def _sign_v4( + service_name, + method, + url, + region, + headers, + credentials, + content_sha256, + date, +): + """Do signature V4 of given request for given service name.""" + + scope = _get_scope(date, region, service_name) + canonical_request_hash, signed_headers = _get_canonical_request_hash( + method, url, headers, content_sha256, + ) + string_to_sign = _get_string_to_sign(date, scope, canonical_request_hash) + signing_key = _get_signing_key( + credentials.secret_key, date, region, service_name, + ) + signature = _get_signature(signing_key, string_to_sign) + authorization = _get_authorization( + credentials.access_key, scope, signed_headers, signature, + ) + headers["Authorization"] = authorization + return headers + + +def sign_v4_s3( + method, + url, + region, + headers, + credentials, + content_sha256, + date, +): + """Do signature V4 of given request for S3 service.""" + return _sign_v4( + "s3", + method, + url, + region, + headers, + credentials, + content_sha256, + date, + ) + + +def sign_v4_sts( + method, + url, + region, + headers, + credentials, + content_sha256, + date, +): + """Do signature V4 of given request for STS service.""" + return _sign_v4( + "sts", + method, + url, + region, + headers, + credentials, + content_sha256, + date, + ) + + +def _get_presign_canonical_request_hash( # pylint: disable=invalid-name + method, url, access_key, scope, date, expires, +): + """Get canonical request hash for presign request.""" + + canonical_headers, signed_headers = "host:" + url.netloc, "host" + + query = url.query+"&" if url.query else "" + query += ( + "X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Credential={0}" + "&X-Amz-Date={1}" + "&X-Amz-Expires={2}" + "&X-Amz-SignedHeaders={3}" + ).format( + queryencode(access_key + "/" + scope), + date.strftime(AMZ_DATE_FORMAT), + expires, + signed_headers, + ) + parts = list(url) + parts[3] = query + url = SplitResult(*parts) + + canonical_query_string = _get_canonical_query_string(query) + + # CanonicalRequest = + # HTTPRequestMethod + '\n' + + # CanonicalURI + '\n' + + # CanonicalQueryString + '\n' + + # CanonicalHeaders + '\n\n' + + # SignedHeaders + '\n' + + # HexEncode(Hash(RequestPayload)) + canonical_request = ( + "{method}\n" + "{canonical_uri}\n" + "{canonical_query_string}\n" + "{canonical_headers}\n\n" + "{signed_headers}\n" + "{content_sha256}" + ).format( + method=method, + canonical_uri=url.path, + canonical_query_string=canonical_query_string, + canonical_headers=canonical_headers, + signed_headers=signed_headers, + content_sha256="UNSIGNED-PAYLOAD", + ) + return sha256_hash(canonical_request), url + + +def presign_v4( + method, + url, + region, + credentials, + date, + expires, +): + """Do signature V4 of given presign request.""" + + scope = _get_scope(date, region, "s3") + canonical_request_hash, url = _get_presign_canonical_request_hash( + method, url, credentials.access_key, scope, date, expires, + ) + string_to_sign = _get_string_to_sign(date, scope, canonical_request_hash) + signing_key = _get_signing_key(credentials.secret_key, date, region, "s3") + signature = _get_signature(signing_key, string_to_sign) + + parts = list(url) + parts[3] = url.query + "&X-Amz-Signature=" + queryencode(signature) + url = SplitResult(*parts) + return url + + +def get_credential_string(access_key, date, region): + """Get credential string of given access key, date and region.""" + + return "{0}/{1}/{2}/s3/aws4_request".format( + access_key, + date.strftime(_SIGNER_DATE_FORMAT), + region, + ) + + +def post_presign_v4(string_to_sign, credentials, date, region): + """Do signature V4 of given presign POST form-data.""" + + signing_key = _get_signing_key(credentials.secret_key, date, region, "s3") + return _get_signature(signing_key, string_to_sign) diff --git a/testbed/minio__minio-py/minio/sse.py b/testbed/minio__minio-py/minio/sse.py new file mode 100644 index 0000000000000000000000000000000000000000..8188c7923f13b21300a1385e029d03da0a2ed02e --- /dev/null +++ b/testbed/minio__minio-py/minio/sse.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.sse +~~~~~~~~~~~~~~~~~~~ + +This module contains core API parsers. + +:copyright: (c) 2018 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" +import base64 +import hashlib +import json +from abc import ABCMeta, abstractmethod + + +class Sse: + """Server-side encryption base class.""" + __metaclass__ = ABCMeta + + @abstractmethod + def headers(self): + """Return headers.""" + + def tls_required(self): # pylint: disable=no-self-use + """Return TLS required to use this server-side encryption.""" + return True + + def copy_headers(self): # pylint: disable=no-self-use + """Return copy headers.""" + return {} + + +class SseCustomerKey(Sse): + """ Server-side encryption - customer key type.""" + + def __init__(self, key): + if len(key) != 32: + raise ValueError( + "SSE-C keys need to be 256 bit base64 encoded", + ) + b64key = base64.b64encode(key).decode() + md5 = hashlib.md5() + md5.update(key) + md5key = base64.b64encode(md5.digest()).decode() + self._headers = { + "X-Amz-Server-Side-Encryption-Customer-Algorithm": "AES256", + "X-Amz-Server-Side-Encryption-Customer-Key": b64key, + "X-Amz-Server-Side-Encryption-Customer-Key-MD5": md5key, + } + self._copy_headers = { + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": + "AES256", + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": b64key, + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-MD5": + md5key, + } + + def headers(self): + return self._headers.copy() + + def copy_headers(self): + return self._copy_headers.copy() + + +class SseKMS(Sse): + """Server-side encryption - KMS type.""" + + def __init__(self, key, context): + self._headers = { + "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": key, + "X-Amz-Server-Side-Encryption": "aws:kms" + } + if context: + data = bytes(json.dumps(context), "utf-8") + self._headers["X-Amz-Server-Side-Encryption-Context"] = ( + base64.b64encode(data).decode() + ) + + def headers(self): + return self._headers.copy() + + +class SseS3(Sse): + """Server-side encryption - S3 type.""" + + def headers(self): + return { + "X-Amz-Server-Side-Encryption": "AES256" + } + + def tls_required(self): + return False diff --git a/testbed/minio__minio-py/minio/thread_pool.py b/testbed/minio__minio-py/minio/thread_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..222cef44e2b639761b9a66c71a31573fd231da69 --- /dev/null +++ b/testbed/minio__minio-py/minio/thread_pool.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.thread_pool +~~~~~~~~~~~~ + +This module implements a thread pool API to run several tasks +in parallel. Tasks results can also be retrieved. + +:copyright: (c) 2017 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from queue import Queue +from threading import BoundedSemaphore, Thread + + +class Worker(Thread): + """ Thread executing tasks from a given tasks queue """ + + def __init__(self, tasks_queue, results_queue, exceptions_queue): + Thread.__init__(self) + self.tasks_queue = tasks_queue + self.results_queue = results_queue + self.exceptions_queue = exceptions_queue + self.daemon = True + self.start() + + def run(self): + """ Continously receive tasks and execute them """ + while True: + task = self.tasks_queue.get() + if not task: + self.tasks_queue.task_done() + break + # No exception detected in any thread, + # continue the execution. + if self.exceptions_queue.empty(): + # Execute the task + func, args, kargs, cleanup_func = task + try: + result = func(*args, **kargs) + self.results_queue.put(result) + except Exception as ex: # pylint: disable=broad-except + self.exceptions_queue.put(ex) + finally: + cleanup_func() + # Mark this task as done, whether an exception happened or not + self.tasks_queue.task_done() + + +class ThreadPool: + """ Pool of threads consuming tasks from a queue """ + + def __init__(self, num_threads): + self.results_queue = Queue() + self.exceptions_queue = Queue() + self.tasks_queue = Queue() + self.sem = BoundedSemaphore(num_threads) + self.num_threads = num_threads + + def add_task(self, func, *args, **kargs): + """ + Add a task to the queue. Calling this function can block + until workers have a room for processing new tasks. Blocking + the caller also prevents the latter from allocating a lot of + memory while workers are still busy running their assigned tasks. + """ + self.sem.acquire() + cleanup_func = self.sem.release + self.tasks_queue.put((func, args, kargs, cleanup_func)) + + def start_parallel(self): + """ Prepare threads to run tasks""" + for _ in range(self.num_threads): + Worker(self.tasks_queue, self.results_queue, self.exceptions_queue) + + def result(self): + """ Stop threads and return the result of all called tasks """ + # Send None to all threads to cleanly stop them + for _ in range(self.num_threads): + self.tasks_queue.put(None) + # Wait for completion of all the tasks in the queue + self.tasks_queue.join() + # Check if one of the thread raised an exception, if yes + # raise it here in the function + if not self.exceptions_queue.empty(): + raise self.exceptions_queue.get() + return self.results_queue diff --git a/testbed/minio__minio-py/minio/versioningconfig.py b/testbed/minio__minio-py/minio/versioningconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..488b4cc09de4a2a0e1ff3f23b837efa088af88f0 --- /dev/null +++ b/testbed/minio__minio-py/minio/versioningconfig.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Request/response of PutBucketVersioning and GetBucketVersioning APIs.""" + +from __future__ import absolute_import + +from .commonconfig import DISABLED, ENABLED +from .xml import Element, SubElement, findtext + +OFF = "Off" +SUSPENDED = "Suspended" + + +class VersioningConfig: + """Versioning configuration.""" + + def __init__(self, status=None, mfa_delete=None): + if status is not None and status not in [ENABLED, SUSPENDED]: + raise ValueError( + "status must be {0} or {1}".format(ENABLED, SUSPENDED), + ) + if mfa_delete is not None and mfa_delete not in [ENABLED, DISABLED]: + raise ValueError( + "MFA delete must be {0} or {1}".format(ENABLED, DISABLED), + ) + self._status = status + self._mfa_delete = mfa_delete + + @property + def status(self): + """Get status.""" + return self._status or OFF + + @property + def mfa_delete(self): + """Get MFA delete.""" + return self._mfa_delete + + @classmethod + def fromxml(cls, element): + """Create new object with values from XML element.""" + status = findtext(element, "Status") + mfa_delete = findtext(element, "MFADelete") + return cls(status, mfa_delete) + + def toxml(self, element): + """Convert to XML.""" + element = Element("VersioningConfiguration") + if self._status: + SubElement(element, "Status", self._status) + if self._mfa_delete: + SubElement(element, "MFADelete", self._mfa_delete) + return element diff --git a/testbed/minio__minio-py/minio/xml.py b/testbed/minio__minio-py/minio/xml.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ddd87181ef516f0d66a74679dfbe21a6e559ab --- /dev/null +++ b/testbed/minio__minio-py/minio/xml.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""XML utility module.""" + +from __future__ import absolute_import + +import io +from xml.etree import ElementTree as ET + +_S3_NAMESPACE = "http://s3.amazonaws.com/doc/2006-03-01/" + + +def Element(tag, namespace=_S3_NAMESPACE): # pylint: disable=invalid-name + """Create ElementTree.Element with tag and namespace.""" + return ET.Element(tag, {'xmlns': namespace} if namespace else {}) + + +def SubElement(parent, tag, text=None): # pylint: disable=invalid-name + """Create ElementTree.SubElement on parent with tag and text.""" + element = ET.SubElement(parent, tag) + if text is not None: + element.text = text + return element + + +def _get_namespace(element): + """Exact namespace if found.""" + start = element.tag.find("{") + if start < 0: + return "" + start += 1 + end = element.tag.find("}") + if end < 0: + return "" + return element.tag[start:end] + + +def findall(element, name): + """Namespace aware ElementTree.Element.findall().""" + namespace = _get_namespace(element) + return element.findall( + "ns:" + name if namespace else name, + {"ns": namespace} if namespace else {}, + ) + + +def find(element, name): + """Namespace aware ElementTree.Element.find().""" + namespace = _get_namespace(element) + return element.find( + "ns:" + name if namespace else name, + {"ns": namespace} if namespace else {}, + ) + + +def findtext(element, name, strict=False): + """ + Namespace aware ElementTree.Element.findtext() with strict flag + raises ValueError if element name not exist. + """ + element = find(element, name) + if element is None: + if strict: + raise ValueError("XML element <{0}> not found".format(name)) + return None + return element.text + + +def unmarshal(cls, xmlstring): + """Unmarshal given XML string to an object of passed class.""" + return cls.fromxml(ET.fromstring(xmlstring)) + + +def marshal(obj): + """Get XML data as bytes of ElementTree.Element.""" + data = io.BytesIO() + ET.ElementTree(obj.toxml(None)).write( + data, encoding=None, xml_declaration=False, + ) + return data.getvalue() diff --git a/testbed/minio__minio-py/minio/xml_marshal.py b/testbed/minio__minio-py/minio/xml_marshal.py new file mode 100644 index 0000000000000000000000000000000000000000..d8cfccb45f48d1179078b9aae7fde81464ef27f5 --- /dev/null +++ b/testbed/minio__minio-py/minio/xml_marshal.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2015, 2016, 2017, 2018, 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +minio.xml_marshal +~~~~~~~~~~~~~~~ + +This module contains the simple wrappers for XML marshaller's. + +:copyright: (c) 2015 by MinIO, Inc. +:license: Apache 2.0, see LICENSE for more details. + +""" + +from __future__ import absolute_import + +import io +from collections import defaultdict +from xml.etree import ElementTree as ET + +_S3_NAMESPACE = 'http://s3.amazonaws.com/doc/2006-03-01/' + + +def Element(tag, with_namespace=False): # pylint: disable=invalid-name + """Create ElementTree.Element with tag and namespace.""" + if with_namespace: + return ET.Element(tag, {'xmlns': _S3_NAMESPACE}) + return ET.Element(tag) + + +def SubElement(parent, tag, text=None): # pylint: disable=invalid-name + """Create ElementTree.SubElement on parent with tag and text.""" + element = ET.SubElement(parent, tag) + if text is not None: + element.text = text + return element + + +def _get_xml_data(element): + """Get XML data of ElementTree.Element.""" + data = io.BytesIO() + ET.ElementTree(element).write(data, encoding=None, xml_declaration=False) + return data.getvalue() + + +def _etree_to_dict(elem): + """Converts ElementTree object to dict.""" + ns = '{' + _S3_NAMESPACE + '}' # pylint: disable=invalid-name + elem.tag = elem.tag.replace(ns, '') + + d = {elem.tag: {} if elem.attrib else None} # pylint: disable=invalid-name + children = list(elem) + if children: + dd = defaultdict(list) # pylint: disable=invalid-name + is_rule = children[0].tag.replace(ns, "") == "Rule" + # pylint: disable=invalid-name + for dc in map(_etree_to_dict, children): + for k, v in dc.items(): # pylint: disable=invalid-name + dd[k].append([v] if is_rule else v) + # pylint: disable=invalid-name + d = {elem.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} + if elem.attrib: + d[elem.tag].update(('@' + k, v) for k, v in elem.attrib.items()) + if elem.text: + text = elem.text.strip() + if children or elem.attrib: + if text: + d[elem.tag]['#text'] = text + else: + d[elem.tag] = text + return d + + +def xml_to_dict(in_xml): + """Convert XML to dict.""" + elem = ET.XML(in_xml) + return _etree_to_dict(elem) + + +def xml_marshal_bucket_encryption(rules): + """Encode bucket encryption to XML.""" + + root = Element('ServerSideEncryptionConfiguration') + + if rules: + # As server supports only one rule, the first rule is taken due to + # no validation is done at server side. + apply_element = SubElement(SubElement(root, 'Rule'), + 'ApplyServerSideEncryptionByDefault') + SubElement(apply_element, 'SSEAlgorithm', + rules[0]['ApplyServerSideEncryptionByDefault'].get( + 'SSEAlgorithm', 'AES256')) + kms_text = rules[0]['ApplyServerSideEncryptionByDefault'].get( + 'KMSMasterKeyID') + if kms_text: + SubElement(apply_element, 'KMSMasterKeyID', kms_text) + + return _get_xml_data(root) + + +def marshal_complete_multipart(uploaded_parts): + """ + Marshal's complete multipart upload request based on *uploaded_parts*. + + :param uploaded_parts: List of all uploaded parts, ordered by part number. + :return: Marshalled XML data. + """ + root = Element('CompleteMultipartUpload', with_namespace=True) + for uploaded_part in uploaded_parts: + part = SubElement(root, 'Part') + SubElement(part, 'PartNumber', str(uploaded_part.part_number)) + SubElement(part, 'ETag', '"' + uploaded_part.etag + '"') + + return _get_xml_data(root) + + +def marshal_bucket_notifications(notifications): + """ + Marshals the notifications structure for sending to S3 compatible storage + + :param notifications: Dictionary with following structure: + + { + 'TopicConfigurations': [ + { + 'Id': 'string', + 'Arn': 'string', + 'Events': [ + 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'| + 's3:ObjectCreated:Put'|'s3:ObjectCreated:Post'| + 's3:ObjectCreated:Copy'| + 's3:ObjectCreated:CompleteMultipartUpload'| + 's3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'| + 's3:ObjectRemoved:DeleteMarkerCreated', + ], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix'|'suffix', + 'Value': 'string' + }, + ] + } + } + }, + ], + 'QueueConfigurations': [ + { + 'Id': 'string', + 'Arn': 'string', + 'Events': [ + 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'| + 's3:ObjectCreated:Put'|'s3:ObjectCreated:Post'| + 's3:ObjectCreated:Copy'| + 's3:ObjectCreated:CompleteMultipartUpload'| + 's3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'| + 's3:ObjectRemoved:DeleteMarkerCreated', + ], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix'|'suffix', + 'Value': 'string' + }, + ] + } + } + }, + ], + 'CloudFunctionConfigurations': [ + { + 'Id': 'string', + 'Arn': 'string', + 'Events': [ + 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'| + 's3:ObjectCreated:Put'|'s3:ObjectCreated:Post'| + 's3:ObjectCreated:Copy'| + 's3:ObjectCreated:CompleteMultipartUpload'| + 's3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'| + 's3:ObjectRemoved:DeleteMarkerCreated', + ], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix'|'suffix', + 'Value': 'string' + }, + ] + } + } + }, + ] + } + + :return: Marshalled XML data + """ + root = Element('NotificationConfiguration', with_namespace=True) + _add_notification_config_to_xml( + root, + 'TopicConfiguration', + notifications.get('TopicConfigurations', []) + ) + _add_notification_config_to_xml( + root, + 'QueueConfiguration', + notifications.get('QueueConfigurations', []) + ) + _add_notification_config_to_xml( + root, + 'CloudFunctionConfiguration', + notifications.get('CloudFunctionConfigurations', []) + ) + + return _get_xml_data(root) + + +NOTIFICATIONS_ARN_FIELDNAME_MAP = { + 'TopicConfiguration': 'Topic', + 'QueueConfiguration': 'Queue', + 'CloudFunctionConfiguration': 'CloudFunction', +} + + +def _add_notification_config_to_xml(node, element_name, configs): + """ + Internal function that builds the XML sub-structure for a given + kind of notification configuration. + + """ + for config in configs: + config_node = SubElement(node, element_name) + + if 'Id' in config: + SubElement(config_node, 'Id', config['Id']) + + SubElement(config_node, NOTIFICATIONS_ARN_FIELDNAME_MAP[element_name], + config['Arn']) + + for event in config['Events']: + SubElement(config_node, 'Event', event) + + filter_rules = config.get('Filter', {}).get( + 'Key', {}).get('FilterRules', []) + if filter_rules: + s3key_node = SubElement(SubElement(config_node, 'Filter'), 'S3Key') + for filter_rule in filter_rules: + filter_rule_node = SubElement(s3key_node, 'FilterRule') + SubElement(filter_rule_node, 'Name', filter_rule['Name']) + SubElement(filter_rule_node, 'Value', filter_rule['Value']) + return node + + +def xml_marshal_delete_objects(keys): + """ + Marshal Multi-Object Delete request body from object names. + + :param object_names: List of object keys to be deleted. + :return: Serialized XML string for multi-object delete request body. + """ + root = Element('Delete') + + # use quiet mode in the request - this causes the S3 Server to + # limit its response to only object keys that had errors during + # the delete operation. + SubElement(root, 'Quiet', "true") + + # add each object to the request. + for key in keys: + version_id = None + if not isinstance(key, (str, bytes)): + version_id = key[1] + key = key[0] + + element = SubElement(root, "Object") + SubElement(element, "Key", key) + if version_id: + SubElement(element, "VersionId", version_id) + + return _get_xml_data(root) diff --git a/testbed/minio__minio-py/pylintrc b/testbed/minio__minio-py/pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..d8d560d79758bfe46002094e678f0b08fa5efcd1 --- /dev/null +++ b/testbed/minio__minio-py/pylintrc @@ -0,0 +1,298 @@ +# lint Python modules using external checkers. +# +# This is the main checker controlling the other ones and the reports +# generation. It is itself both a raw checker and an astng checker in order +# to: +# * handle message activation / deactivation at the module level +# * handle some basic but necessary stats'data (number of classes, methods...) +# +[MASTER] + + +# Specify a configuration file. +#rcfile= + +# Profiled execution. +profile=no + +# Add to the black list. It should be a base name, not a +# path. You may set this option multiple times. +ignore=.svn + +# Pickle collected data for later comparisons. +persistent=yes + +# Set the cache size for astng objects. +cache-size=500 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + + +[MESSAGES CONTROL] + +# Enable only checker(s) with the given id(s). This option conflict with the +# disable-checker option +#enable-checker= + +# Enable all checker(s) except those with the given id(s). This option conflict +# with the disable-checker option +#disable-checker= + +# Enable all messages in the listed categories. +#enable-msg-cat= + +# Disable all messages in the listed categories. +#disable-msg-cat= + +# Enable the message(s) with the given id(s). +#enable-msg= + +# Disable the message(s) with the given id(s). +# disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201 +disable-msg=C0301,C0111,C0103,R0201,W0702,C0324 + +[REPORTS] + +# set the output format. Available formats are text, parseable, colorized and +# html +output-format=colorized + +# Put messages in a separate file for each module / package specified on the +# command line instead of printing them on stdout. Reports (if any) will be +# written in a file name "pylint_global.[txt|html]". +files-output=no + +# Tells wether to display a full report or only the messages +reports=yes + +# Python expression which should return a note less than 10 (10 is the highest +# note).You have access to the variables errors warning, statement which +# respectivly contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (R0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Add a comment according to your evaluation note. This is used by the global +# evaluation report (R0004). +comment=no + +# Enable the report(s) with the given id(s). +#enable-report= + +# Disable the report(s) with the given id(s). +#disable-report= + +# checks for +# * unused variables / imports +# * undefined variables +# * redefinition of variable from builtins or from an outer scope +# * use of variable before assigment +# +[VARIABLES] + +# Tells wether we should check for unused import in __init__ files. +init-import=yes + +# A regular expression matching names used for dummy variables (i.e. not used). +dummy-variables-rgx=_|dummy + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + + +# try to find bugs in the code using type inference +# +[TYPECHECK] + +# Tells wether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# When zope mode is activated, consider the acquired-members option to ignore +# access to some undefined attributes. +zope=no + +# List of members which are usually get through zope's acquisition mecanism and +# so shouldn't trigger E0201 when accessed (need zope=yes to be considered). +acquired-members=REQUEST,acl_users,aq_parent + + +# checks for : +# * doc strings +# * modules / classes / functions / methods / arguments / variables name +# * number of arguments, local variables, branches, returns and statements in +# functions, methods +# * required module attributes +# * dangerous default values as arguments +# * redefinition of function / method / class +# * uses of the global statement +# +[BASIC] + +# Required attributes for module, separated by a comma +required-attributes= + +# Regular expression which should only match functions or classes name which do +# not require a docstring +no-docstring-rgx=__.*__ + +# Regular expression which should only match correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression which should only match correct module level names +const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$ + +# Regular expression which should only match correct class names +class-rgx=[A-Z_][a-zA-Z0-9]+$ + +# Regular expression which should only match correct function names +function-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct method names +method-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct instance attribute names +attr-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct argument names +argument-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct variable names +variable-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct list comprehension / +# generator expression variable names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Good variable names which should always be accepted, separated by a comma +good-names=i,j,k,ex,Run,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# List of builtins function names that should not be used, separated by a comma +bad-functions=apply,input + + +# checks for sign of poor/misdesign: +# * number of methods, attributes, local variables... +# * size, complexity of functions, methods +# +[DESIGN] + +# Maximum number of arguments for function / method +max-args=12 + +# Maximum number of locals for function / method body +max-locals=30 + +# Maximum number of return / yield for function / method body +max-returns=12 + +# Maximum number of branch for function / method body +max-branchs=30 + +# Maximum number of statements in function / method body +max-statements=60 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of attributes for a class (see R0902). +max-attributes=20 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=0 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + + +# checks for +# * external modules dependencies +# * relative / wildcard imports +# * cyclic imports +# * uses of deprecated modules +# +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub,string,TERMIOS,Bastion,rexec + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report R0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report R0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report R0402 must +# not be disabled) +int-import-graph= + + +# checks for : +# * methods without self as first argument +# * overridden methods signature +# * access only to existant members via self +# * attributes not defined in the __init__ method +# * supported interfaces implementation +# * unreachable code +# +[CLASSES] + +# List of interface methods to ignore, separated by a comma. This is used for +# instance to not check methods defines in Zope's Interface base class. +# ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + + +# checks for similarities and duplicated code. This computation may be +# memory / CPU intensive, so you should disable it if you experiments some +# problems. +# +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=5 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + + +# checks for: +# * warning notes in the code like FIXME, XXX +# * PEP 263: source code with non ascii character but no encoding declaration +# +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO,BUG: + + +# checks for : +# * unauthorized constructions +# * strict indentation +# * line length +# * use of <> instead of != +# +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=80 + +# Maximum number of lines in a module +max-module-lines=1000 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' diff --git a/testbed/minio__minio-py/setup.py b/testbed/minio__minio-py/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..550638b0ed290f7366b2a01dbf2276ce0d839a88 --- /dev/null +++ b/testbed/minio__minio-py/setup.py @@ -0,0 +1,84 @@ +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import re +import sys +from codecs import open + +from setuptools import setup + +if sys.argv[-1] == 'publish': + os.system('python setup.py sdist upload') + sys.exit() + +version = '' +with open('minio/__init__.py', 'r') as fd: + version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', + fd.read(), re.MULTILINE).group(1) + +with open('README.md', 'r', 'utf-8') as f: + readme = f.read() + +packages = [ + 'minio', + 'minio.select', + 'minio.credentials' +] + +requires = [ + 'urllib3', + 'pytz', + 'certifi', + 'python-dateutil', + 'configparser', +] + +tests_requires = [ + 'nose', + 'mock', + 'Faker', +] + +setup( + name='minio', + description='MinIO Python Library for Amazon S3 Compatible Cloud Storage for Python', + author='MinIO, Inc.', + url='https://github.com/minio/minio-py', + download_url='https://github.com/minio/minio-py', + author_email='dev@min.io', + version=version, + long_description_content_type='text/markdown', + package_dir={'minio': 'minio'}, + packages=packages, + install_requires=requires, + tests_require=tests_requires, + license='Apache License 2.0', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Natural Language :: English', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + long_description=readme, + package_data={'': ['LICENSE', 'README.md']}, + include_package_data=True, +) diff --git a/testbed/minio__minio-py/tests/__init__.py b/testbed/minio__minio-py/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/minio__minio-py/tests/certs/private.key b/testbed/minio__minio-py/tests/certs/private.key new file mode 100644 index 0000000000000000000000000000000000000000..9061ede4a9c460c3d746a67effc07dafdada079d --- /dev/null +++ b/testbed/minio__minio-py/tests/certs/private.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC3G9IiC+adjf0p +i/2KYc+4dizeuzUFN7wraSdhiOMdQgCnu9Dc3t2YEsQhNdrARjOTyXd36KeM3TwI +rPJ61dRGQSuN12l+mzngFJQjE0sysZHUJOLQC3rVvIrHSQ57utPg8ifxt/SunlPY +fhcUcq03onMGq44yOfE6mIhoe0Y9wcPQ3RjjNNS44bgmXiXwa+Do0h2hEn6/essq +5KjHL8WW2vGg7G9edpYdxINA/A2fdLtr8BwPNrZhOx84eee2XcUNdBuTtUUxE+0L +9yRqItqddriRxJFwOXb5OPW8xx2WGaV2a0wbE4gB2PTwwDvfo72mo9HXHZUHM1A8 +4TD/RXMbAgMBAAECggEBAJ7r1oUWLyGvinn0tijUm6RNbMQjVvEgXoCO008jr3pF +PqxVpgEMrOa/4tmwFBus0jcCNF4t3r2zhddBw3I5A/O1vEdvHnBz6NdDBQ8sP6fP +1fF50iEe1Y2MBibQkXFxxVMG2QRB1Gt5nuvXA9ELdqtCovK3EsMk5ukkWb/UvjH5 +8hcmQsaSqvzFEF4wJSY2mkeGSGIJTphPhhuA22xbhaBMInQyhZu8EHsn0h6s/Wgy +C4Cp2+4qZTKaaf6x3/ZjJ8CuKiSX+ZsJKjOEv8sqx7j/Y7QFOmJPewInKDhwazr/ +xIK+N0KXPbUzeSEz6ZvExNDTxtR5ZlQP2UrRDg28yQECgYEA4Is1O2BvKVzNFOkj +bTVz25a/bb0Xrcfgi0Y9rdfLzlNdItFjAkxLTVRSW2Hv9ICl0RDDAG+wTlktXRdh +rfvDjwG2CvLQo1VEdMWTTkKVg03SwMEy2hFiWV69lENFGSaY8Y6unZDbia5HQinA +EgSS4sCojS+a2jtzG5FVVHJDKlkCgYEA0MKhMhD4SUhr2y1idPBrmLxuW5mVozuW +8bYaBeSzmfS0BRsN4fP9JGODPBPDdNbfGfGC9ezWLgD/lmCgjIEyBOq8EmqWSsiS +Kihds1+Z7hXtbzGsFGAFJJTIh7blBCsK5QFuyuih2UG0fL9z6K/dy+UUJkzrYqph +vSfKixyM8pMCgYEAmUPLsNyw4325aeV8TeWnUCJERaZFDFQa21W1cfyS2yEhuEtN +llr3JzBACqn9vFk3VU1onNqfb8sE4L696KCpKeqUFEMK0AG6eS4Gzus53Gb5TKJS +kHA/PhshsZp9Bp7G1FJ8s4YVo5N2hh2zQVkn3Wh9Y+kzfHQJrK51nO9lEvkCgYBi +BuKWle1gzAcJdnhDHRoJMIJJtQbVDYhFnBMALXJAmu1lcFzGe0GlMq1PKqCfXr6I +eiXawQmZtJJP1LPPBmOsd2U06KQGHcS00xucvQmVCOrjSdnZ/3SqxsqbH8DOgj+t +ZUzXLwHA+N99rJEK9Hob4kfh7ECjpgobPnIXfKKazQKBgQChAuiXHtf/Qq18hY3u +x48zFWjGgfd6GpOBZYkXOwGdCJgnYjZbE26LZEnYbwPh8ZUA2vp7mgHRJkD5e3Fj +ERuJLCw86WqyYZmLEuBciYGjCZqR5nbavfwsziWD00jeNruds2ZwKxRfFm4V7o2S +WLd/RUatd2Uu9f3B2J78OUdnxg== +-----END PRIVATE KEY----- diff --git a/testbed/minio__minio-py/tests/certs/public.crt b/testbed/minio__minio-py/tests/certs/public.crt new file mode 100644 index 0000000000000000000000000000000000000000..19f626969548a5ff0fc70eaaa59b4fbc881d1903 --- /dev/null +++ b/testbed/minio__minio-py/tests/certs/public.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCzCCAfOgAwIBAgIUaIUOMI78LCu+r1zl0mmFHK8n5/AwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTE5MTAyNDE5NTMxOVoYDzIxMTkw +OTMwMTk1MzE5WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQC3G9IiC+adjf0pi/2KYc+4dizeuzUFN7wraSdhiOMd +QgCnu9Dc3t2YEsQhNdrARjOTyXd36KeM3TwIrPJ61dRGQSuN12l+mzngFJQjE0sy +sZHUJOLQC3rVvIrHSQ57utPg8ifxt/SunlPYfhcUcq03onMGq44yOfE6mIhoe0Y9 +wcPQ3RjjNNS44bgmXiXwa+Do0h2hEn6/essq5KjHL8WW2vGg7G9edpYdxINA/A2f +dLtr8BwPNrZhOx84eee2XcUNdBuTtUUxE+0L9yRqItqddriRxJFwOXb5OPW8xx2W +GaV2a0wbE4gB2PTwwDvfo72mo9HXHZUHM1A84TD/RXMbAgMBAAGjUzBRMB0GA1Ud +DgQWBBSEWXQ2JRD+OK7/KTmlD+OW16pGmzAfBgNVHSMEGDAWgBSEWXQ2JRD+OK7/ +KTmlD+OW16pGmzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCF +0zYRaabB3X0jzGI9/Lr3Phrb90GvoL1DFLRuiOuTlDkz0vrm/HrZskwHCgMNrkCj +OTD9Vpas4D1QZBbQbRzfnf3OOoG4bgmcCwLFZl3dy27yIDAhrmbUP++g9l1Jmy4v +vBR/M4lt2scQ8LcZYEPqhEaE5EzFQEjtaxDcKdWDNKY9W1NUzSIABhF9eHiAUNdH +AFNJlYeBlCHxcWIeqgon184Dqp/CsvKtz3z3Ni+rlwPM/zuJCFHh1VF+z++0LJjG +roBCV0Tro4XyiEz9yp7Cb5kQYMaj1KL9TqBG0tZx0pmv7y+lXc4TT6DEllXz6USy +rbIba9/uUet3BqeIMTqj +-----END CERTIFICATE----- diff --git a/testbed/minio__minio-py/tests/functional/tests.py b/testbed/minio__minio-py/tests/functional/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..d8cb820ce51d27d232fd7c00b5a8a34e0876f834 --- /dev/null +++ b/testbed/minio__minio-py/tests/functional/tests.py @@ -0,0 +1,2041 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016, 2017, 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: disable=too-many-lines +"""Functional tests of minio-py.""" + +from __future__ import absolute_import, division + +import hashlib +import io +import json +import math +import os +import random +import shutil +import sys +import tempfile +import time +import traceback +from datetime import datetime, timedelta +from threading import Thread +from uuid import uuid4 + +import certifi +import urllib3 + +from minio import CopyConditions, Minio, PostPolicy +from minio.commonconfig import ENABLED +from minio.error import S3Error +from minio.select.helpers import calculate_crc +from minio.selectrequest import (CSVInputSerialization, CSVOutputSerialization, + SelectRequest) +from minio.sse import SseCustomerKey +from minio.versioningconfig import VersioningConfig + +if sys.version_info[0] == 2: + from datetime import tzinfo # pylint: disable=ungrouped-imports + + class UTC(tzinfo): + """UTC""" + + def utcoffset(self, dt): + return timedelta(0) + + def tzname(self, dt): + return "UTC" + + def dst(self, dt): + return timedelta(0) + + UTC = UTC() + from inspect import getargspec + GETARGSSPEC = getargspec +else: + from datetime import timezone # pylint: disable=ungrouped-imports + UTC = timezone.utc + from inspect import getfullargspec # pylint: disable=ungrouped-imports + GETARGSSPEC = getfullargspec + +_CLIENT = None # initialized in main(). +_TEST_FILE = None # initialized in main(). +_LARGE_FILE = None # initialized in main(). +_IS_AWS = None # initialized in main(). +KB = 1024 +MB = 1024 * KB +HTTP = urllib3.PoolManager( + cert_reqs='CERT_REQUIRED', + ca_certs=os.environ.get('SSL_CERT_FILE') or certifi.where() +) + + +def _gen_bucket_name(): + """Generate random bucket name.""" + return "minio-py-test-{0}".format(uuid4()) + + +def _get_sha256sum(filename): + """Get SHA-256 checksum of given file.""" + with open(filename, 'rb') as file: + contents = file.read() + return hashlib.sha256(contents).hexdigest() + + +def _get_random_string(size): + """Get random string of given size.""" + if not size: + return "" + + chars = "abcdefghijklmnopqrstuvwxyz" + chars *= int(math.ceil(size / len(chars))) + chars = list(chars[:size]) + random.shuffle(chars) + return "".join(chars) + + +class LimitedRandomReader: # pylint: disable=too-few-public-methods + """Random data reader of specified size.""" + + def __init__(self, limit): + self._limit = limit + + def read(self, size=64*KB): + """Read random data of specified size.""" + if size < 0 or size > self._limit: + size = self._limit + + data = _get_random_string(size) + self._limit -= size + return data.encode() + + +def _call(log_entry, func, *args, **kwargs): + """Execute given function.""" + log_entry["method"] = func + return func(*args, **kwargs) + + +class TestFailed(Exception): + """Indicate test failed error.""" + + +def _call_test(func, *args, **kwargs): + """Execute given test function.""" + + log_entry = { + "name": func.__name__, + "status": "PASS", + } + + start_time = time.time() + try: + func(log_entry, *args, **kwargs) + except S3Error as exc: + if exc.code == "NotImplemented": + log_entry["alert"] = "Not Implemented" + log_entry["status"] = "NA" + else: + log_entry["message"] = "{0}".format(exc) + log_entry["error"] = traceback.format_exc() + log_entry["status"] = "FAIL" + except Exception as exc: # pylint: disable=broad-except + log_entry["message"] = "{0}".format(exc) + log_entry["error"] = traceback.format_exc() + log_entry["status"] = "FAIL" + + if log_entry.get("method"): + log_entry["function"] = "{0}({1})".format( + log_entry["method"].__name__, + # pylint: disable=deprecated-method + ', '.join(GETARGSSPEC(log_entry["method"]).args[1:])) + log_entry["args"] = { + k: v for k, v in log_entry.get("args", {}).items() if v + } + log_entry["duration"] = int( + round((time.time() - start_time) * 1000)) + log_entry["name"] = 'minio-py:' + log_entry["name"] + log_entry["method"] = None + print(json.dumps({k: v for k, v in log_entry.items() if v})) + if log_entry["status"] == "FAIL": + raise TestFailed() + + +def test_make_bucket_default_region(log_entry): + """Test make_bucket() with default region.""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + + log_entry["args"] = { + "bucket_name": bucket_name, + "location": "default value ('us-east-1')", # Default location + } + + # Create a bucket with default bucket location + _call(log_entry, _CLIENT.make_bucket, bucket_name) + # Check if bucket was created properly + _call(log_entry, _CLIENT.bucket_exists, bucket_name) + # Remove bucket + _call(log_entry, _CLIENT.remove_bucket, bucket_name) + # Test passes + log_entry["method"] = _CLIENT.make_bucket + + +def test_make_bucket_with_region(log_entry): + """Test make_bucket() with region.""" + + # Only test make bucket with region against AWS S3 + if not _IS_AWS: + return + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + # A non-default location + location = 'us-west-1' + + log_entry["args"] = { + "bucket_name": bucket_name, + "location": location, + } + + # Create a bucket with default bucket location + _call(log_entry, _CLIENT.make_bucket, bucket_name, location) + # Check if bucket was created properly + _call(log_entry, _CLIENT.bucket_exists, bucket_name) + # Remove bucket + _call(log_entry, _CLIENT.remove_bucket, bucket_name) + # Test passes + log_entry["method"] = _CLIENT.make_bucket + + +def test_negative_make_bucket_invalid_name( # pylint: disable=invalid-name + log_entry): + """Test make_bucket() with invalid bucket name.""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + # Default location + log_entry["args"] = { + "location": "default value ('us-east-1')", + } + # Create an array of invalid bucket names to test + invalid_bucket_name_list = [ + bucket_name + '.', + '.' + bucket_name, + bucket_name + '...abcd' + ] + for name in invalid_bucket_name_list: + log_entry["args"]["bucket_name"] = name + try: + # Create a bucket with default bucket location + _call(log_entry, _CLIENT.make_bucket, name) + # Check if bucket was created properly + _call(log_entry, _CLIENT.bucket_exists, name) + # Remove bucket + _call(log_entry, _CLIENT.remove_bucket, name) + except ValueError: + pass + # Test passes + log_entry["method"] = _CLIENT.make_bucket + log_entry["args"]['bucket_name'] = invalid_bucket_name_list + + +def test_list_buckets(log_entry): + """Test list_buckets().""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + + # Create a bucket with default bucket location + _call(log_entry, _CLIENT.make_bucket, bucket_name) + + try: + buckets = _CLIENT.list_buckets() + for bucket in buckets: + # bucket object should be of a valid value. + if bucket.name and bucket.creation_date: + continue + raise ValueError('list_bucket api failure') + finally: + # Remove bucket + _call(log_entry, _CLIENT.remove_bucket, bucket_name) + + +def test_select_object_content(log_entry): + """Test select_object_content().""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + csvfile = 'test.csv' + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": csvfile, + } + + try: + _CLIENT.make_bucket(bucket_name) + content = io.BytesIO(b"col1,col2,col3\none,two,three\nX,Y,Z\n") + _CLIENT.put_object(bucket_name, csvfile, content, + len(content.getvalue())) + + request = SelectRequest( + "select * from s3object", + CSVInputSerialization(), + CSVOutputSerialization(), + request_progress=True, + ) + data = _CLIENT.select_object_content(bucket_name, csvfile, request) + # Get the records + records = io.BytesIO() + for data_bytes in data.stream(10*KB): + records.write(data_bytes.encode('utf-8')) + + expected_crc = calculate_crc(content.getvalue()) + generated_crc = calculate_crc(records.getvalue()) + if expected_crc != generated_crc: + raise ValueError( + 'Data mismatch Expected : ' + '"col1,col2,col3\none,two,three\nX,Y,Z\n"', + 'Received {}', records) + finally: + _CLIENT.remove_object(bucket_name, csvfile) + _CLIENT.remove_bucket(bucket_name) + + +def _test_fput_object(bucket_name, object_name, filename, metadata, sse): + """Test fput_object().""" + try: + _CLIENT.make_bucket(bucket_name) + if _IS_AWS: + _CLIENT.fput_object(bucket_name, object_name, filename, + metadata=metadata, sse=sse) + else: + _CLIENT.fput_object(bucket_name, object_name, filename, sse=sse) + + _CLIENT.stat_object(bucket_name, object_name, sse=sse) + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_fput_object_small_file(log_entry, sse=None): + """Test fput_object() with small file.""" + + if sse: + log_entry["name"] += "_with_SSE-C" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}-f".format(uuid4()) + metadata = {'x-amz-storage-class': 'STANDARD_IA'} + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "file_path": _TEST_FILE, + "metadata": metadata, + } + + _test_fput_object(bucket_name, object_name, _TEST_FILE, metadata, sse) + + +def test_fput_object_large_file(log_entry, sse=None): + """Test fput_object() with large file.""" + + if sse: + log_entry["name"] += "_with_SSE-C" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}-large".format(uuid4()) + metadata = {'x-amz-storage-class': 'STANDARD_IA'} + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "file_path": _LARGE_FILE, + "metadata": metadata, + } + + # upload local large file through multipart. + _test_fput_object(bucket_name, object_name, _LARGE_FILE, metadata, sse) + + +def test_fput_object_with_content_type( # pylint: disable=invalid-name + log_entry): + """Test fput_object() with content-type.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}-f".format(uuid4()) + metadata = {'x-amz-storage-class': 'STANDARD_IA'} + content_type = 'application/octet-stream' + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "file_path": _TEST_FILE, + "metadata": metadata, + "content_type": content_type, + } + + _test_fput_object(bucket_name, object_name, _TEST_FILE, metadata, None) + + +def _validate_stat(st_obj, expected_size, expected_meta, version_id=None): + """Validate stat information.""" + + expected_meta = { + key.lower(): value for key, value in (expected_meta or {}).items() + } + received_modification_time = st_obj.last_modified + received_etag = st_obj.etag + received_metadata = { + key.lower(): value for key, value in (st_obj.metadata or {}).items() + } + received_content_type = st_obj.content_type + received_size = st_obj.size + received_is_dir = st_obj.is_dir + + if not isinstance(received_modification_time, time.struct_time): + raise ValueError('Incorrect last_modified time type' + ', received type: ', type(received_modification_time)) + + if not received_etag: + raise ValueError('No Etag value is returned.') + + if st_obj.version_id != version_id: + raise ValueError( + "version-id mismatch. expected={0}, got={1}".format( + version_id, st_obj.version_id, + ), + ) + + # content_type by default can be either application/octet-stream or + # binary/octet-stream + if received_content_type not in [ + 'application/octet-stream', 'binary/octet-stream']: + raise ValueError('Incorrect content type. Expected: ', + "'application/octet-stream' or 'binary/octet-stream'," + " received: ", received_content_type) + + if received_size != expected_size: + raise ValueError('Incorrect file size. Expected: 11534336', + ', received: ', received_size) + + if received_is_dir: + raise ValueError('Incorrect file type. Expected: is_dir=False', + ', received: is_dir=', received_is_dir) + + if not all(i in received_metadata.items() for i in expected_meta.items()): + raise ValueError("Metadata key 'x-amz-meta-testing' not found") + + +def test_copy_object_no_copy_condition( # pylint: disable=invalid-name + log_entry, ssec_copy=None, ssec=None): + """Test copy_object() with no conditiions.""" + + if ssec_copy or ssec: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size, sse=ssec) + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + source_sse=ssec_copy, sse=ssec) + st_obj = _CLIENT.stat_object(bucket_name, object_copy, sse=ssec) + _validate_stat(st_obj, size, {}) + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_copy_object_with_metadata(log_entry): + """Test copy_object() with metadata.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + metadata = {"testing-string": "string", + "testing-int": 1} + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + "metadata": metadata, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size) + # Perform a server side copy of an object + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + metadata=metadata) + # Verification + st_obj = _CLIENT.stat_object(bucket_name, object_copy) + expected_metadata = {'x-amz-meta-testing-int': '1', + 'x-amz-meta-testing-string': 'string'} + _validate_stat(st_obj, size, expected_metadata) + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_copy_object_etag_match(log_entry): + """Test copy_object() with etag match condition.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size) + # Perform a server side copy of an object + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source) + # Verification + source_etag = _CLIENT.stat_object(bucket_name, object_source).etag + copy_conditions = CopyConditions() + copy_conditions.set_match_etag(source_etag) + log_entry["args"]["conditions"] = {'set_match_etag': source_etag} + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + copy_conditions) + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_copy_object_negative_etag_match( # pylint: disable=invalid-name + log_entry): + """Test copy_object() with etag not match condition.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size) + try: + # Perform a server side copy of an object + # with incorrect pre-conditions and fail + etag = 'test-etag' + copy_conditions = CopyConditions() + copy_conditions.set_match_etag(etag) + log_entry["args"]["conditions"] = {'set_match_etag': etag} + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + copy_conditions) + except S3Error as exc: + if exc.code != "PreconditionFailed": + raise + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_copy_object_modified_since(log_entry): + """Test copy_object() with modified since condition.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size) + # Set up the 'modified_since' copy condition + copy_conditions = CopyConditions() + mod_since = datetime(2014, 4, 1, tzinfo=UTC) + copy_conditions.set_modified_since(mod_since) + log_entry["args"]["conditions"] = { + 'set_modified_since': mod_since.strftime('%c')} + # Perform a server side copy of an object + # and expect the copy to complete successfully + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + copy_conditions) + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_copy_object_unmodified_since( # pylint: disable=invalid-name + log_entry): + """Test copy_object() with unmodified since condition.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + object_source = object_name + "-source" + object_copy = object_name + "-copy" + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_source": object_source, + "object_name": object_copy, + } + + try: + _CLIENT.make_bucket(bucket_name) + # Upload a streaming object of 1 KiB + size = 1 * KB + reader = LimitedRandomReader(size) + _CLIENT.put_object(bucket_name, object_source, reader, size) + # Set up the 'unmodified_since' copy condition + copy_conditions = CopyConditions() + unmod_since = datetime(2014, 4, 1, tzinfo=UTC) + copy_conditions.set_unmodified_since(unmod_since) + log_entry["args"]["conditions"] = { + 'set_unmodified_since': unmod_since.strftime('%c')} + try: + # Perform a server side copy of an object and expect + # the copy to fail since the creation/modification + # time is now, way later than unmodification time, April 1st, 2014 + _CLIENT.copy_object(bucket_name, object_copy, + '/' + bucket_name + '/' + object_source, + copy_conditions) + except S3Error as exc: + if exc.code != "PreconditionFailed": + raise + finally: + _CLIENT.remove_object(bucket_name, object_source) + _CLIENT.remove_object(bucket_name, object_copy) + _CLIENT.remove_bucket(bucket_name) + + +def test_put_object(log_entry, sse=None): + """Test put_object().""" + + if sse: + log_entry["name"] += "_SSE" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + length = 1 * MB + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "length": length, + "data": "LimitedRandomReader(1 * MB)" + } + + try: + _CLIENT.make_bucket(bucket_name) + # Put/Upload a streaming object of 1 MiB + reader = LimitedRandomReader(length) + _CLIENT.put_object(bucket_name, object_name, reader, length, sse=sse) + _CLIENT.stat_object(bucket_name, object_name, sse=sse) + + # Put/Upload a streaming object of 11 MiB + log_entry["args"]["length"] = length = 11 * MB + reader = LimitedRandomReader(length) + log_entry["args"]["data"] = "LimitedRandomReader(11 * MB)" + log_entry["args"]["metadata"] = metadata = { + 'x-amz-meta-testing': 'value', 'test-key': 'value2'} + log_entry["args"]["content_type"] = content_type = ( + "application/octet-stream") + log_entry["args"]["object_name"] = object_name + "-metadata" + _CLIENT.put_object(bucket_name, object_name + "-metadata", reader, + length, content_type, metadata, sse=sse) + # Stat on the uploaded object to check if it exists + # Fetch saved stat metadata on a previously uploaded object with + # metadata. + st_obj = _CLIENT.stat_object(bucket_name, object_name + "-metadata", + sse=sse) + normalized_meta = { + key.lower(): value for key, value in ( + st_obj.metadata or {}).items() + } + if 'x-amz-meta-testing' not in normalized_meta: + raise ValueError("Metadata key 'x-amz-meta-testing' not found") + value = normalized_meta['x-amz-meta-testing'] + if value != 'value': + raise ValueError('Metadata key has unexpected' + ' value {0}'.format(value)) + if 'x-amz-meta-test-key' not in normalized_meta: + raise ValueError("Metadata key 'x-amz-meta-test-key' not found") + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_object(bucket_name, object_name+'-metadata') + _CLIENT.remove_bucket(bucket_name) + + +def test_negative_put_object_with_path_segment( # pylint: disable=invalid-name + log_entry): + """Test put_object() failure with path segment.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "/a/b/c/{0}".format(uuid4()) + length = 0 + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "length": length, + "data": "", + } + + try: + _CLIENT.make_bucket(bucket_name) + _CLIENT.put_object(bucket_name, object_name, io.BytesIO(b''), 0) + _CLIENT.remove_object(bucket_name, object_name) + except S3Error as err: + if err.code != 'XMinioInvalidObjectName': + raise + finally: + _CLIENT.remove_bucket(bucket_name) + + +def _test_stat_object(log_entry, sse=None, version_check=False): + """Test stat_object().""" + + if sse: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + length = 1 * MB + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "length": length, + "data": "LimitedRandomReader(1 * MB)" + } + + version_id1 = None + version_id2 = None + + _CLIENT.make_bucket(bucket_name) + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + # Put/Upload a streaming object of 1 MiB + reader = LimitedRandomReader(length) + _, version_id1 = _CLIENT.put_object( + bucket_name, object_name, reader, length, sse=sse, + ) + _CLIENT.stat_object( + bucket_name, object_name, sse=sse, version_id=version_id1, + ) + + # Put/Upload a streaming object of 11 MiB + log_entry["args"]["length"] = length = 11 * MB + reader = LimitedRandomReader(length) + log_entry["args"]["data"] = "LimitedRandomReader(11 * MB)" + log_entry["args"]["metadata"] = metadata = { + 'X-Amz-Meta-Testing': 'value'} + log_entry["args"]["content_type"] = content_type = ( + "application/octet-stream") + log_entry["args"]["object_name"] = object_name + "-metadata" + _, version_id2 = _CLIENT.put_object( + bucket_name, object_name + "-metadata", reader, + length, content_type, metadata, sse=sse, + ) + # Stat on the uploaded object to check if it exists + # Fetch saved stat metadata on a previously uploaded object with + # metadata. + st_obj = _CLIENT.stat_object( + bucket_name, object_name + "-metadata", + sse=sse, version_id=version_id2, + ) + # Verify the collected stat data. + _validate_stat( + st_obj, length, metadata, version_id=version_id2, + ) + finally: + _CLIENT.remove_object(bucket_name, object_name, version_id=version_id1) + _CLIENT.remove_object( + bucket_name, object_name+'-metadata', version_id=version_id2, + ) + _CLIENT.remove_bucket(bucket_name) + + +def test_stat_object(log_entry, sse=None): + """Test stat_object().""" + _test_stat_object(log_entry, sse) + + +def test_stat_object_version(log_entry, sse=None): + """Test stat_object() of versioned object.""" + _test_stat_object(log_entry, sse, version_check=True) + + +def _test_remove_object(log_entry, version_check=False): + """Test remove_object().""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + length = 1 * KB + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + _, version_id = _CLIENT.put_object( + bucket_name, object_name, LimitedRandomReader(length), length, + ) + _CLIENT.remove_object(bucket_name, object_name, version_id=version_id) + finally: + _CLIENT.remove_bucket(bucket_name) + + +def test_remove_object(log_entry): + """Test remove_object().""" + _test_remove_object(log_entry) + + +def test_remove_object_version(log_entry): + """Test remove_object() of versioned object.""" + _test_remove_object(log_entry, version_check=True) + + +def _test_get_object(log_entry, sse=None, version_check=False): + """Test get_object().""" + + if sse: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + length = 1 * MB + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + version_id = None + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + _, version_id = _CLIENT.put_object( + bucket_name, object_name, LimitedRandomReader(length), + length, sse=sse, + ) + # Get/Download a full object, iterate on response to save to disk + object_data = _CLIENT.get_object( + bucket_name, object_name, sse=sse, version_id=version_id, + ) + newfile = 'newfile جديد' + with open(newfile, 'wb') as file_data: + shutil.copyfileobj(object_data, file_data) + os.remove(newfile) + finally: + _CLIENT.remove_object(bucket_name, object_name, version_id=version_id) + _CLIENT.remove_bucket(bucket_name) + + +def test_get_object(log_entry, sse=None): + """Test get_object().""" + _test_get_object(log_entry, sse) + + +def test_get_object_version(log_entry, sse=None): + """Test get_object() for versioned object.""" + _test_get_object(log_entry, sse, version_check=True) + + +def _test_fget_object(log_entry, sse=None, version_check=False): + """Test fget_object().""" + + if sse: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + tmpfd, tmpfile = tempfile.mkstemp() + os.close(tmpfd) + length = 1 * MB + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "file_path": tmpfile + } + + _CLIENT.make_bucket(bucket_name) + version_id = None + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + _, version_id = _CLIENT.put_object( + bucket_name, object_name, LimitedRandomReader(length), + length, sse=sse, + ) + # Get/Download a full object and save locally at path + _CLIENT.fget_object( + bucket_name, object_name, tmpfile, sse=sse, version_id=version_id, + ) + os.remove(tmpfile) + finally: + _CLIENT.remove_object(bucket_name, object_name, version_id=version_id) + _CLIENT.remove_bucket(bucket_name) + + +def test_fget_object(log_entry, sse=None): + """Test fget_object().""" + _test_fget_object(log_entry, sse) + + +def test_fget_object_version(log_entry, sse=None): + """Test fget_object() of versioned object.""" + _test_fget_object(log_entry, sse, version_check=True) + + +def test_get_object_with_default_length( # pylint: disable=invalid-name + log_entry, sse=None): + """Test get_object() with default length.""" + + if sse: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + size = 1 * MB + length = 1000 + offset = size - length + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "offset": offset + } + + _CLIENT.make_bucket(bucket_name) + try: + _CLIENT.put_object(bucket_name, object_name, + LimitedRandomReader(size), size, sse=sse) + # Get half of the object + object_data = _CLIENT.get_object(bucket_name, object_name, + offset=offset, sse=sse) + newfile = 'newfile' + with open(newfile, 'wb') as file_data: + for data in object_data: + file_data.write(data) + # Check if the new file is the right size + new_file_size = os.path.getsize(newfile) + os.remove(newfile) + if new_file_size != length: + raise ValueError('Unexpected file size after running ') + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_get_partial_object(log_entry, sse=None): + """Test get_object() by offset/length.""" + + if sse: + log_entry["name"] += "_SSEC" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + size = 1 * MB + offset = int(size / 2) + length = offset - 1000 + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "offset": offset + } + + _CLIENT.make_bucket(bucket_name) + try: + _CLIENT.put_object(bucket_name, object_name, + LimitedRandomReader(size), size, sse=sse) + # Get half of the object + object_data = _CLIENT.get_object(bucket_name, object_name, + offset=offset, length=length, sse=sse) + newfile = 'newfile' + with open(newfile, 'wb') as file_data: + for data in object_data: + file_data.write(data) + # Check if the new file is the right size + new_file_size = os.path.getsize(newfile) + os.remove(newfile) + if new_file_size != length: + raise ValueError('Unexpected file size after running ') + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def _test_list_objects(log_entry, use_api_v1=False, version_check=False): + """Test list_objects().""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + is_recursive = True + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "recursive": is_recursive, + } + + _CLIENT.make_bucket(bucket_name) + version_id1 = None + version_id2 = None + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + size = 1 * KB + _, version_id1 = _CLIENT.put_object( + bucket_name, object_name + "-1", LimitedRandomReader(size), size, + ) + _, version_id2 = _CLIENT.put_object( + bucket_name, object_name + "-2", LimitedRandomReader(size), size, + ) + # List all object paths in bucket. + objects = _CLIENT.list_objects( + bucket_name, '', is_recursive, include_version=version_check, + use_api_v1=use_api_v1, + ) + for obj in objects: + _ = (obj.bucket_name, obj.object_name, obj.last_modified, + obj.etag, obj.size, obj.content_type) + if obj.version_id not in [version_id1, version_id2]: + raise ValueError( + "version ID mismatch. expected=any{0}, got:{1}".format( + [version_id1, version_id2], obj.verion_id, + ) + ) + finally: + _CLIENT.remove_object( + bucket_name, object_name + "-1", version_id=version_id1, + ) + _CLIENT.remove_object( + bucket_name, object_name + "-2", version_id=version_id2, + ) + _CLIENT.remove_bucket(bucket_name) + + +def test_list_objects_v1(log_entry): + """Test list_objects().""" + _test_list_objects(log_entry, use_api_v1=True) + + +def test_list_object_v1_versions(log_entry): + """Test list_objects().""" + _test_list_objects(log_entry, use_api_v1=True, version_check=True) + + +def _test_list_objects_api(bucket_name, expected_no, *argv): + """Test list_objects().""" + + # argv is composed of prefix and recursive arguments of + # list_objects api. They are both supposed to be passed as strings. + objects = _CLIENT.list_objects(bucket_name, *argv) + + # expect all objects to be listed + no_of_files = 0 + for obj in objects: + _ = (obj.bucket_name, obj.object_name, obj.last_modified, obj.etag, + obj.size, obj.content_type) + no_of_files += 1 + + if expected_no != no_of_files: + raise ValueError( + ("Listed no of objects ({}), does not match the " + "expected no of objects ({})").format(no_of_files, expected_no)) + + +def test_list_objects_with_prefix(log_entry): + """Test list_objects() with prefix.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + size = 1 * KB + no_of_created_files = 4 + path_prefix = "" + # Create files and directories + for i in range(no_of_created_files): + _CLIENT.put_object(bucket_name, + "{0}{1}_{2}".format( + path_prefix, + i, + object_name, + ), + LimitedRandomReader(size), size) + path_prefix = "{0}{1}/".format(path_prefix, i) + + # Created files and directory structure + # ._/ + # |___0_ + # |___0/ + # |___1_ + # |___1/ + # |___2_ + # |___2/ + # |___3_ + # + + # Test and verify list_objects api outputs + # List objects recursively with NO prefix + log_entry["args"]["prefix"] = prefix = "" # no prefix + log_entry["args"]["recursive"] = recursive = "" + _test_list_objects_api(bucket_name, no_of_created_files, prefix, True) + + # List objects at the top level with no prefix and no recursive option + # Expect only the top 2 objects to be listed + _test_list_objects_api(bucket_name, 2) + + # List objects for '0' directory/prefix without recursive option + # Expect 2 object (directory '0' and '0_' object) to be listed + log_entry["args"]["prefix"] = prefix = "0" + _test_list_objects_api(bucket_name, 2, prefix) + + # List objects for '0/' directory/prefix without recursive option + # Expect only 2 objects under directory '0/' to be listed, + # non-recursive + log_entry["args"]["prefix"] = prefix = "0/" + _test_list_objects_api(bucket_name, 2, prefix) + + # List objects for '0/' directory/prefix, recursively + # Expect 2 objects to be listed + log_entry["args"]["prefix"] = prefix = "0/" + log_entry["args"]["recursive"] = recursive = "True" + _test_list_objects_api(bucket_name, 3, prefix, recursive) + + # List object with '0/1/2/' directory/prefix, non-recursive + # Expect the single object under directory '0/1/2/' to be listed + log_entry["args"]["prefix"] = prefix = "0/1/2/" + _test_list_objects_api(bucket_name, 1, prefix) + finally: + path_prefix = "" + for i in range(no_of_created_files): + _CLIENT.remove_object( + bucket_name, + "{0}{1}_{2}".format(path_prefix, i, object_name)) + path_prefix = "{0}{1}/".format(path_prefix, i) + _CLIENT.remove_bucket(bucket_name) + # Test passes + log_entry["args"]["prefix"] = ( + "Several prefix/recursive combinations are tested") + log_entry["args"]["recursive"] = ( + 'Several prefix/recursive combinations are tested') + + +def test_list_objects_with_1001_files( # pylint: disable=invalid-name + log_entry): + """Test list_objects() with more 1000 objects.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": "{0}_0 ~ {0}_1000".format(object_name), + } + + _CLIENT.make_bucket(bucket_name) + try: + size = 1 * KB + no_of_created_files = 2000 + # Create files and directories + for i in range(no_of_created_files): + _CLIENT.put_object(bucket_name, + "{0}_{1}".format(object_name, i), + LimitedRandomReader(size), size) + + # List objects and check if 1001 files are returned + _test_list_objects_api(bucket_name, no_of_created_files) + finally: + for i in range(no_of_created_files): + _CLIENT.remove_object(bucket_name, + "{0}_{1}".format(object_name, i)) + _CLIENT.remove_bucket(bucket_name) + + +def test_list_objects(log_entry): + """Test list_objects().""" + _test_list_objects(log_entry) + + +def test_list_object_versions(log_entry): + """Test list_objects() of versioned object.""" + _test_list_objects(log_entry, version_check=True) + + +def test_presigned_get_object_default_expiry( # pylint: disable=invalid-name + log_entry): + """Test presigned_get_object() with default expiry.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + size = 1 * KB + _CLIENT.put_object(bucket_name, object_name, LimitedRandomReader(size), + size) + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name) + response = HTTP.urlopen('GET', presigned_get_object_url) + if response.status != 200: + raise Exception( + ( + "Presigned GET object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_get_object_url, response.code, response.data, + ), + ) + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_get_object_expiry( # pylint: disable=invalid-name + log_entry): + """Test presigned_get_object() with expiry.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + size = 1 * KB + _CLIENT.put_object(bucket_name, object_name, LimitedRandomReader(size), + size) + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name, timedelta(seconds=120)) + response = HTTP.urlopen('GET', presigned_get_object_url) + if response.status != 200: + raise Exception( + ( + "Presigned GET object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_get_object_url, response.code, response.data, + ), + ) + + log_entry["args"]["presigned_get_object_url"] = ( + presigned_get_object_url) + + response = HTTP.urlopen('GET', presigned_get_object_url) + + log_entry["args"]['response.status'] = response.status + log_entry["args"]['response.reason'] = response.reason + log_entry["args"]['response.headers'] = json.dumps( + response.headers.__dict__) + # pylint: disable=protected-access + log_entry["args"]['response._body'] = response._body.decode('utf-8') + + if response.status != 200: + raise Exception( + ( + "Presigned GET object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_get_object_url, response.code, response.data, + ), + ) + + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name, timedelta(seconds=1)) + + # Wait for 2 seconds for the presigned url to expire + time.sleep(2) + response = HTTP.urlopen('GET', presigned_get_object_url) + + log_entry["args"]['response.status-2'] = response.status + log_entry["args"]['response.reason-2'] = response.reason + log_entry["args"]['response.headers-2'] = json.dumps( + response.headers.__dict__) + log_entry["args"]['response._body-2'] = response._body.decode('utf-8') + + # Success with an expired url is considered to be a failure + if response.status == 200: + raise ValueError('Presigned get url failed to expire!') + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_get_object_response_headers( # pylint: disable=invalid-name + log_entry): + """Test presigned_get_object() with headers.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + content_type = 'text/plain' + content_language = 'en_US' + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + "content_type": content_type, + "content_language": content_language, + } + + _CLIENT.make_bucket(bucket_name) + try: + size = 1 * KB + _CLIENT.put_object(bucket_name, object_name, LimitedRandomReader(size), + size) + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name, timedelta(seconds=120)) + + response_headers = { + 'response-content-type': content_type, + 'response-content-language': content_language + } + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name, timedelta(seconds=120), response_headers) + + log_entry["args"]["presigned_get_object_url"] = ( + presigned_get_object_url) + + response = HTTP.urlopen('GET', presigned_get_object_url) + returned_content_type = response.headers['Content-Type'] + returned_content_language = response.headers['Content-Language'] + + log_entry["args"]['response.status'] = response.status + log_entry["args"]['response.reason'] = response.reason + log_entry["args"]['response.headers'] = json.dumps( + response.headers.__dict__) + # pylint: disable=protected-access + log_entry["args"]['response._body'] = response._body.decode('utf-8') + log_entry["args"]['returned_content_type'] = returned_content_type + log_entry["args"]['returned_content_language'] = ( + returned_content_language) + + if (response.status != 200 or + returned_content_type != content_type or + returned_content_language != content_language): + raise Exception( + ( + "Presigned GET object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_get_object_url, response.code, response.data, + ), + ) + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_get_object_version( # pylint: disable=invalid-name + log_entry): + """Test presigned_get_object() of versioned object.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + version_id = None + try: + _CLIENT.set_bucket_versioning(bucket_name, VersioningConfig(ENABLED)) + size = 1 * KB + _, version_id = _CLIENT.put_object( + bucket_name, object_name, LimitedRandomReader(size), size, + ) + presigned_get_object_url = _CLIENT.presigned_get_object( + bucket_name, object_name, version_id=version_id, + ) + response = HTTP.urlopen('GET', presigned_get_object_url) + if response.status != 200: + raise Exception( + ( + "Presigned GET object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_get_object_url, response.code, response.data, + ), + ) + finally: + _CLIENT.remove_object(bucket_name, object_name, version_id=version_id) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_put_object_default_expiry( # pylint: disable=invalid-name + log_entry): + """Test presigned_put_object() with default expiry.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + presigned_put_object_url = _CLIENT.presigned_put_object( + bucket_name, object_name) + response = HTTP.urlopen('PUT', + presigned_put_object_url, + LimitedRandomReader(1 * KB)) + if response.status != 200: + raise Exception( + ( + "Presigned PUT object URL {0} failed; " + "code: {1}, error: {2}" + ).format( + presigned_put_object_url, response.code, response.data, + ), + ) + _CLIENT.stat_object(bucket_name, object_name) + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_put_object_expiry( # pylint: disable=invalid-name + log_entry): + """Test presigned_put_object() with expiry.""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + presigned_put_object_url = _CLIENT.presigned_put_object( + bucket_name, object_name, timedelta(seconds=1)) + # Wait for 2 seconds for the presigned url to expire + time.sleep(2) + response = HTTP.urlopen('PUT', + presigned_put_object_url, + LimitedRandomReader(1 * KB)) + if response.status == 200: + raise ValueError('Presigned put url failed to expire!') + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_presigned_post_policy(log_entry): + """Test presigned_post_policy().""" + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + + log_entry["args"] = { + "bucket_name": bucket_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + no_of_days = 10 + prefix = 'objectPrefix/' + + # Post policy. + policy = PostPolicy() + policy.set_bucket_name(bucket_name) + policy.set_key_startswith(prefix) + expires_date = datetime.utcnow() + timedelta(days=no_of_days) + policy.set_expires(expires_date) + # post_policy arg is a class. To avoid displaying meaningless value + # for the class, policy settings are made part of the args for + # clarity and debugging purposes. + log_entry["args"]["post_policy"] = {'prefix': prefix, + 'expires_in_days': no_of_days} + _CLIENT.presigned_post_policy(policy) + finally: + _CLIENT.remove_bucket(bucket_name) + + +def test_thread_safe(log_entry): + """Test thread safety.""" + + # Create sha-sum value for the user provided + # source file, 'test_file' + test_file_sha_sum = _get_sha256sum(_LARGE_FILE) + + # Get a unique bucket_name and object_name + bucket_name = _gen_bucket_name() + object_name = "{0}".format(uuid4()) + + log_entry["args"] = { + "bucket_name": bucket_name, + "object_name": object_name, + } + + # A list of exceptions raised by get_object_and_check + # called in multiple threads. + exceptions = [] + + # get_object_and_check() downloads an object, stores it in a file + # and then calculates its checksum. In case of mismatch, a new + # exception is generated and saved in exceptions. + def get_object_and_check(index): + try: + local_file = "copied_file_{0}".format(index) + _CLIENT.fget_object(bucket_name, object_name, local_file) + copied_file_sha_sum = _get_sha256sum(local_file) + # Compare sha-sum values of the source file and the copied one + if test_file_sha_sum != copied_file_sha_sum: + raise ValueError( + 'Sha-sum mismatch on multi-threaded put and ' + 'get objects') + except Exception as exc: # pylint: disable=broad-except + exceptions.append(exc) + finally: + # Remove downloaded file + _ = os.path.isfile(local_file) and os.remove(local_file) + + _CLIENT.make_bucket(bucket_name) + no_of_threads = 5 + try: + # Put/Upload 'no_of_threads' many objects + # simultaneously using multi-threading + for _ in range(no_of_threads): + thread = Thread(target=_CLIENT.fput_object, + args=(bucket_name, object_name, _LARGE_FILE)) + thread.start() + thread.join() + + # Get/Download 'no_of_threads' many objects + # simultaneously using multi-threading + thread_list = [] + for i in range(no_of_threads): + # Create dynamic/varying names for to be created threads + thread_name = 'thread_{0}'.format(i) + vars()[thread_name] = Thread( + target=get_object_and_check, args=(i,)) + vars()[thread_name].start() + thread_list.append(vars()[thread_name]) + + # Wait until all threads to finish + for thread in thread_list: + thread.join() + + if exceptions: + raise exceptions[0] + finally: + _CLIENT.remove_object(bucket_name, object_name) + _CLIENT.remove_bucket(bucket_name) + + +def test_get_bucket_policy(log_entry): + """Test get_bucket_policy().""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + log_entry["args"] = { + "bucket_name": bucket_name, + } + _CLIENT.make_bucket(bucket_name) + try: + _CLIENT.get_bucket_policy(bucket_name) + except S3Error as exc: + if exc.code != "NoSuchBucketPolicy": + raise + finally: + _CLIENT.remove_bucket(bucket_name) + + +def _get_policy_actions(stat): + """Get policy actions from stat information.""" + + def listit(value): + return value if isinstance(value, list) else [value] + actions = [listit(s.get("Action")) for s in stat if s.get("Action")] + actions = list(set( + item.replace("s3:", "") for sublist in actions for item in sublist + )) + actions.sort() + return actions + + +def _validate_policy(bucket_name, policy): + """Validate policy.""" + policy_dict = json.loads(_CLIENT.get_bucket_policy(bucket_name)) + actions = _get_policy_actions(policy_dict.get('Statement')) + expected_actions = _get_policy_actions(policy.get('Statement')) + return expected_actions == actions + + +def test_get_bucket_notification(log_entry): + """Test get_bucket_notification().""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + log_entry["args"] = { + "bucket_name": bucket_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + notification = _CLIENT.get_bucket_notification(bucket_name) + if notification: + raise ValueError("Failed to receive an empty bucket notification") + finally: + _CLIENT.remove_bucket(bucket_name) + + +def test_set_bucket_policy_readonly(log_entry): + """Test set_bucket_policy() with readonly policy.""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + log_entry["args"] = { + "bucket_name": bucket_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + # read-only policy + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetBucketLocation", + "Resource": "arn:aws:s3:::" + bucket_name + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::" + bucket_name + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::{0}/*".format(bucket_name) + } + ] + } + # Set read-only policy + _CLIENT.set_bucket_policy(bucket_name, json.dumps(policy)) + # Validate if the policy is set correctly + if not _validate_policy(bucket_name, policy): + raise ValueError('Failed to set ReadOnly bucket policy') + finally: + _CLIENT.remove_bucket(bucket_name) + + +def test_set_bucket_policy_readwrite( # pylint: disable=invalid-name + log_entry): + """Test set_bucket_policy() with read/write policy.""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + log_entry["args"] = { + "bucket_name": bucket_name, + } + + _CLIENT.make_bucket(bucket_name) + try: + # Read-write policy + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Action": ["s3:GetBucketLocation"], + "Sid": "", + "Resource": ["arn:aws:s3:::" + bucket_name], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListBucket"], + "Sid": "", + "Resource": ["arn:aws:s3:::" + bucket_name], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListBucketMultipartUploads"], + "Sid": "", + "Resource": ["arn:aws:s3:::" + bucket_name], + "Effect": "Allow", + "Principal": {"AWS": "*"} + }, + { + "Action": ["s3:ListMultipartUploadParts", + "s3:GetObject", + "s3:AbortMultipartUpload", + "s3:DeleteObject", + "s3:PutObject"], + "Sid": "", + "Resource": ["arn:aws:s3:::{0}/*".format(bucket_name)], + "Effect": "Allow", + "Principal": {"AWS": "*"} + } + ] + } + # Set read-write policy + _CLIENT.set_bucket_policy(bucket_name, json.dumps(policy)) + # Validate if the policy is set correctly + if not _validate_policy(bucket_name, policy): + raise ValueError('Failed to set ReadOnly bucket policy') + finally: + _CLIENT.remove_bucket(bucket_name) + + +def _test_remove_objects(log_entry, version_check=False): + """Test remove_objects().""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + log_entry["args"] = { + "bucket_name": bucket_name, + } + + _CLIENT.make_bucket(bucket_name) + object_names = [] + try: + if version_check: + _CLIENT.set_bucket_versioning( + bucket_name, VersioningConfig(ENABLED), + ) + size = 1 * KB + # Upload some new objects to prepare for multi-object delete test. + for i in range(10): + object_name = "prefix-{0}".format(i) + _, version_id = _CLIENT.put_object( + bucket_name, object_name, LimitedRandomReader(size), size, + ) + object_names.append( + (object_name, version_id) if version_check else object_name, + ) + log_entry["args"]["objects_iter"] = object_names + + # delete the objects in a single library call. + for err in _CLIENT.remove_objects(bucket_name, object_names): + raise ValueError("Remove objects err: {}".format(err)) + finally: + # Try to clean everything to keep our server intact + for err in _CLIENT.remove_objects(bucket_name, object_names): + raise ValueError("Remove objects err: {}".format(err)) + _CLIENT.remove_bucket(bucket_name) + + +def test_remove_objects(log_entry): + """Test remove_objects().""" + _test_remove_objects(log_entry) + + +def test_remove_object_versions(log_entry): + """Test remove_objects().""" + _test_remove_objects(log_entry, version_check=True) + + +def test_remove_bucket(log_entry): + """Test remove_bucket().""" + + # Get a unique bucket_name + bucket_name = _gen_bucket_name() + if _IS_AWS: + bucket_name += ".unique" + + log_entry["args"] = { + "bucket_name": bucket_name, + } + + if _IS_AWS: + log_entry["args"]["location"] = location = "us-east-1" + _CLIENT.make_bucket(bucket_name, location) + else: + _CLIENT.make_bucket(bucket_name) + + # Removing bucket. This operation will only work if your bucket is empty. + _CLIENT.remove_bucket(bucket_name) + + +def main(): + """ + Functional testing of minio python library. + """ + # pylint: disable=global-statement + global _CLIENT, _TEST_FILE, _LARGE_FILE, _IS_AWS + + access_key = os.getenv('ACCESS_KEY') + secret_key = os.getenv('SECRET_KEY') + server_endpoint = os.getenv('SERVER_ENDPOINT', 'play.min.io') + secure = os.getenv('ENABLE_HTTPS', '1') == '1' + + if server_endpoint == 'play.min.io': + access_key = 'Q3AM3UQ867SPQQA43P2F' + secret_key = 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG' + secure = True + + _CLIENT = Minio(server_endpoint, access_key, secret_key, secure=secure) + _IS_AWS = ".amazonaws.com" in server_endpoint + + # Check if we are running in the mint environment. + data_dir = os.getenv('DATA_DIR', '/mint/data') + + is_mint_env = ( + os.path.exists(data_dir) and + os.path.exists(os.path.join(data_dir, 'datafile-1-MB')) and + os.path.exists(os.path.join(data_dir, 'datafile-11-MB')) + ) + + # Enable trace + # _CLIENT.trace_on(sys.stderr) + + _TEST_FILE = 'datafile-1-MB' + _LARGE_FILE = 'datafile-11-MB' + if is_mint_env: + # Choose data files + _TEST_FILE = os.path.join(data_dir, 'datafile-1-MB') + _LARGE_FILE = os.path.join(data_dir, 'datafile-11-MB') + else: + with open(_TEST_FILE, 'wb') as file_data: + shutil.copyfileobj(LimitedRandomReader(1 * MB), file_data) + with open(_LARGE_FILE, 'wb') as file_data: + shutil.copyfileobj(LimitedRandomReader(11 * MB), file_data) + + ssec = None + if secure: + # Create a Customer Key of 32 Bytes for Server Side Encryption (SSE-C) + cust_key = b'AABBCCDDAABBCCDDAABBCCDDAABBCCDD' + # Create an SSE-C object with provided customer key + ssec = SseCustomerKey(cust_key) + + if os.getenv("MINT_MODE") == "full": + tests = { + test_make_bucket_default_region: None, + test_make_bucket_with_region: None, + test_negative_make_bucket_invalid_name: None, + test_list_buckets: None, + test_fput_object_small_file: {"sse": ssec} if ssec else None, + test_fput_object_large_file: {"sse": ssec} if ssec else None, + test_fput_object_with_content_type: None, + test_copy_object_no_copy_condition: { + "ssec_copy": ssec, "ssec": ssec} if ssec else None, + test_copy_object_etag_match: None, + test_copy_object_with_metadata: None, + test_copy_object_negative_etag_match: None, + test_copy_object_modified_since: None, + test_copy_object_unmodified_since: None, + test_put_object: {"sse": ssec} if ssec else None, + test_negative_put_object_with_path_segment: None, + test_stat_object: {"sse": ssec} if ssec else None, + test_stat_object_version: {"sse": ssec} if ssec else None, + test_get_object: {"sse": ssec} if ssec else None, + test_get_object_version: {"sse": ssec} if ssec else None, + test_fget_object: {"sse": ssec} if ssec else None, + test_fget_object_version: {"sse": ssec} if ssec else None, + test_get_object_with_default_length: None, + test_get_partial_object: {"sse": ssec} if ssec else None, + test_list_objects_v1: None, + test_list_object_v1_versions: None, + test_list_objects_with_prefix: None, + test_list_objects_with_1001_files: None, + test_list_objects: None, + test_list_object_versions: None, + test_presigned_get_object_default_expiry: None, + test_presigned_get_object_expiry: None, + test_presigned_get_object_response_headers: None, + test_presigned_get_object_version: None, + test_presigned_put_object_default_expiry: None, + test_presigned_put_object_expiry: None, + test_presigned_post_policy: None, + test_thread_safe: None, + test_get_bucket_policy: None, + test_set_bucket_policy_readonly: None, + test_set_bucket_policy_readwrite: None, + test_get_bucket_notification: None, + test_select_object_content: None, + } + else: + tests = { + test_make_bucket_default_region: None, + test_list_buckets: None, + test_put_object: {"sse": ssec} if ssec else None, + test_stat_object: {"sse": ssec} if ssec else None, + test_stat_object_version: {"sse": ssec} if ssec else None, + test_get_object: {"sse": ssec} if ssec else None, + test_get_object_version: {"sse": ssec} if ssec else None, + test_list_objects: None, + test_presigned_get_object_default_expiry: None, + test_presigned_put_object_default_expiry: None, + test_presigned_post_policy: None, + test_copy_object_no_copy_condition: { + "ssec_copy": ssec, "ssec": ssec} if ssec else None, + test_select_object_content: None, + test_get_bucket_policy: None, + test_set_bucket_policy_readonly: None, + test_get_bucket_notification: None, + } + + tests.update( + { + test_remove_object: None, + test_remove_object_version: None, + test_remove_objects: None, + test_remove_object_versions: None, + test_remove_bucket: None, + }, + ) + + for test_name, arg_list in tests.items(): + args = () + kwargs = {} + _call_test(test_name, *args, **kwargs) + + if arg_list: + args = () + kwargs = arg_list + _call_test(test_name, *args, **kwargs) + + # Remove temporary files. + if not is_mint_env: + os.remove(_TEST_FILE) + os.remove(_LARGE_FILE) + + +if __name__ == "__main__": + try: + main() + except TestFailed: + sys.exit(1) + except Exception as exc: # pylint: disable=broad-except + print(exc) + sys.exit(-1) diff --git a/testbed/minio__minio-py/tests/functional_test.sh b/testbed/minio__minio-py/tests/functional_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b10ff288f531db1a1aeb302d4b21ba26339e0898 --- /dev/null +++ b/testbed/minio__minio-py/tests/functional_test.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +main () { + echo "Running python tests..." + + echo "building..." + (cd ..; python setup.py install --prefix ${HOME}/.local; cd -) + + echo "running..." + python ./functional/tests.py +} + +# invoke the script +# Move to the directory which contains this script and invoke it +cd $(dirname $(realpath $0)) && main "$@" diff --git a/testbed/minio__minio-py/tests/unit/__init__.py b/testbed/minio__minio-py/tests/unit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c15edd87ce7470a7b2fab8806fa2104bc8fb143e --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/testbed/minio__minio-py/tests/unit/bucket_exist_test.py b/testbed/minio__minio-py/tests/unit/bucket_exist_test.py new file mode 100644 index 0000000000000000000000000000000000000000..67c0cfe99c7d85ac1da80bcc84c1dee6c45a6718 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/bucket_exist_test.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import eq_, raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT +from minio.error import S3Error + +from .minio_mocks import MockConnection, MockResponse + + +class BucketExists(TestCase): + @raises(TypeError) + def test_bucket_is_string(self): + client = Minio('localhost:9000') + client.bucket_exists(1234) + + @raises(ValueError) + def test_bucket_is_not_empty_string(self): + client = Minio('localhost:9000') + client.bucket_exists(' \t \n ') + + @raises(ValueError) + def test_bucket_exists_invalid_name(self): + client = Minio('localhost:9000') + client.bucket_exists('AB*CD') + + @mock.patch('urllib3.PoolManager') + @raises(S3Error) + def test_bucket_exists_bad_request(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('HEAD', + 'https://localhost:9000/hello', + {'User-Agent': _DEFAULT_USER_AGENT}, + 400) + ) + client = Minio('localhost:9000') + client.bucket_exists('hello') + + @mock.patch('urllib3.PoolManager') + def test_bucket_exists_works(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('HEAD', + 'https://localhost:9000/hello', + {'User-Agent': _DEFAULT_USER_AGENT}, + 200) + ) + client = Minio('localhost:9000') + result = client.bucket_exists('hello') + eq_(True, result) + mock_server.mock_add_request( + MockResponse('HEAD', + 'https://localhost:9000/goodbye', + {'User-Agent': _DEFAULT_USER_AGENT}, + 404) + ) + false_result = client.bucket_exists('goodbye') + eq_(False, false_result) diff --git a/testbed/minio__minio-py/tests/unit/config.json.sample b/testbed/minio__minio-py/tests/unit/config.json.sample new file mode 100644 index 0000000000000000000000000000000000000000..2f654f954c83a9eaafa697d1af1ef8aa4713197b --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/config.json.sample @@ -0,0 +1,17 @@ +{ + "version": "8", + "hosts": { + "play": { + "url": "https://play.minio.io:9000", + "accessKey": "Q3AM3UQ867SPQQA43P2F", + "secretKey": "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", + "api": "S3v2" + }, + "s3": { + "url": "https://s3.amazonaws.com", + "accessKey": "accessKey", + "secretKey": "secret", + "api": "S3v4" + } + } +} diff --git a/testbed/minio__minio-py/tests/unit/copy_object_test.py b/testbed/minio__minio-py/tests/unit/copy_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..544bbd4c2f2aadf6b27a54fccad8b204217a225a --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/copy_object_test.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import raises + +from minio import Minio +from minio.copy_conditions import CopyConditions + + +class CopyObjectTest(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.copy_object('hello', 12, 12) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.copy_object('hello', ' \t \n ', '') + + @raises(ValueError) + def test_length_is_string(self): + client = Minio('localhost:9000') + client.copy_object('..hello', '1', '/testbucket/object') + + +class CopyConditionTest(TestCase): + @raises(ValueError) + def test_match_etag_is_not_empty(self): + conds = CopyConditions() + conds.set_match_etag('') + + @raises(ValueError) + def test_match_etag_is_not_empty_except(self): + conds = CopyConditions() + conds.set_match_etag_except('') + + @raises(AttributeError) + def test_unmodified_since(self): + conds = CopyConditions() + conds.set_unmodified_since('') + + @raises(AttributeError) + def test_modified_since(self): + conds = CopyConditions() + conds.set_modified_since('') diff --git a/testbed/minio__minio-py/tests/unit/credentials.empty b/testbed/minio__minio-py/tests/unit/credentials.empty new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/minio__minio-py/tests/unit/credentials.sample b/testbed/minio__minio-py/tests/unit/credentials.sample new file mode 100644 index 0000000000000000000000000000000000000000..e72bd803dd704539388c5fd8e682da444d3150c3 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/credentials.sample @@ -0,0 +1,12 @@ +[default] +aws_access_key_id = accessKey +aws_secret_access_key = secret +aws_session_token = token + +[no_token] +aws_access_key_id = accessKey +aws_secret_access_key = secret + +[with_colon] +aws_access_key_id: accessKey +aws_secret_access_key: secret \ No newline at end of file diff --git a/testbed/minio__minio-py/tests/unit/credentials_test.py b/testbed/minio__minio-py/tests/unit/credentials_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f4a5a54cdb26a71f201c0d72176899050e634d --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/credentials_test.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) +# 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from datetime import datetime, timedelta +from unittest import TestCase + +import mock +from nose.tools import eq_, raises + +from minio.credentials.credentials import Credentials +from minio.credentials.providers import (AWSConfigProvider, ChainedProvider, + EnvAWSProvider, EnvMinioProvider, + IamAwsProvider, + MinioClientConfigProvider, + StaticProvider) + +CONFIG_JSON_SAMPLE = "tests/unit/config.json.sample" +CREDENTIALS_SAMPLE = "tests/unit/credentials.sample" +CREDENTIALS_EMPTY = "tests/unit/credentials.empty" + + +class CredentialsTest(TestCase): + def test_credentials_get(self): + provider = MinioClientConfigProvider( + filename=CONFIG_JSON_SAMPLE, + alias="play", + ) + creds = provider.retrieve() + eq_(creds.access_key, "Q3AM3UQ867SPQQA43P2F") + eq_(creds.secret_key, "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + eq_(creds.session_token, None) + + +class CredListResponse(object): + status = 200 + data = b"test-s3-full-access-for-minio-ec2" + + +class CredsResponse(object): + status = 200 + data = json.dumps({ + "Code": "Success", + "Type": "AWS-HMAC", + "AccessKeyId": "accessKey", + "SecretAccessKey": "secret", + "Token": "token", + "Expiration": "2014-12-16T01:51:37Z", + "LastUpdated": "2009-11-23T0:00:00Z" + }) + + +class IamAwsProviderTest(TestCase): + @mock.patch("urllib3.PoolManager.urlopen") + def test_iam(self, mock_connection): + mock_connection.side_effect = [CredListResponse(), CredsResponse()] + provider = IamAwsProvider() + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, "token") + eq_(creds._expiration, datetime(2014, 12, 16, 1, 51, 37)) + + +class ChainedProviderTest(TestCase): + def test_chain_retrieve(self): + # clear environment + os.environ.clear() + # prepare env for env_aws provider + os.environ["AWS_ACCESS_KEY_ID"] = "access_aws" + os.environ["AWS_SECRET_ACCESS_KEY"] = "secret_aws" + os.environ["AWS_SESSION_TOKEN"] = "token_aws" + # prepare env for env_minio + os.environ["MINIO_ACCESS_KEY"] = "access_minio" + os.environ["MINIO_SECRET_KEY"] = "secret_minio" + # create chain provider with env_aws and env_minio providers + + provider = ChainedProvider( + [ + EnvAWSProvider(), EnvMinioProvider(), + ] + ) + # retireve provider (env_aws) has priority + creds = provider.retrieve() + # assert provider credentials + eq_(creds.access_key, "access_aws") + eq_(creds.secret_key, "secret_aws") + eq_(creds.session_token, "token_aws") + + +class EnvAWSProviderTest(TestCase): + def test_env_aws_retrieve(self): + os.environ.clear() + os.environ["AWS_ACCESS_KEY_ID"] = "access" + os.environ["AWS_SECRET_ACCESS_KEY"] = "secret" + os.environ["AWS_SESSION_TOKEN"] = "token" + provider = EnvAWSProvider() + creds = provider.retrieve() + eq_(creds.access_key, "access") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, "token") + + def test_env_aws_retrieve_no_token(self): + os.environ.clear() + os.environ["AWS_ACCESS_KEY_ID"] = "access" + os.environ["AWS_SECRET_ACCESS_KEY"] = "secret" + provider = EnvAWSProvider() + creds = provider.retrieve() + eq_(creds.access_key, "access") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, None) + + +class EnvMinioTest(TestCase): + def test_env_minio_retrieve(self): + os.environ.clear() + os.environ['MINIO_ACCESS_KEY'] = "access" + os.environ["MINIO_SECRET_KEY"] = "secret" + provider = EnvMinioProvider() + creds = provider.retrieve() + eq_(creds.access_key, "access") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, None) + + +class AWSConfigProviderTest(TestCase): + def test_file_aws(self): + os.environ.clear() + provider = AWSConfigProvider(CREDENTIALS_SAMPLE) + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, "token") + + def test_file_aws_from_env(self): + os.environ.clear() + os.environ["AWS_SHARED_CREDENTIALS_FILE"] = ( + CREDENTIALS_SAMPLE + ) + provider = AWSConfigProvider() + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, "token") + + def test_file_aws_env_profile(self): + os.environ.clear() + os.environ["AWS_PROFILE"] = "no_token" + provider = AWSConfigProvider(CREDENTIALS_SAMPLE) + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, None) + + def test_file_aws_arg_profile(self): + os.environ.clear() + provider = AWSConfigProvider( + CREDENTIALS_SAMPLE, + "no_token", + ) + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, None) + + def test_file_aws_no_creds(self): + os.environ.clear() + provider = AWSConfigProvider( + CREDENTIALS_EMPTY, + "no_token", + ) + try: + provider.retrieve() + except ValueError: + pass + + +class MinioClientConfigProviderTest(TestCase): + def test_file_minio_(self): + os.environ.clear() + provider = MinioClientConfigProvider(filename=CONFIG_JSON_SAMPLE) + creds = provider.retrieve() + eq_(creds.access_key, "accessKey") + eq_(creds.secret_key, "secret") + eq_(creds.session_token, None) + + def test_file_minio_env_alias(self): + os.environ.clear() + os.environ["MINIO_ALIAS"] = "play" + provider = MinioClientConfigProvider(filename=CONFIG_JSON_SAMPLE) + creds = provider.retrieve() + eq_(creds.access_key, "Q3AM3UQ867SPQQA43P2F") + eq_(creds.secret_key, "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + eq_(creds.session_token, None) + + def test_file_minio_arg_alias(self): + os.environ.clear() + provider = MinioClientConfigProvider( + filename=CONFIG_JSON_SAMPLE, + alias="play", + ) + creds = provider.retrieve() + eq_(creds.access_key, "Q3AM3UQ867SPQQA43P2F") + eq_(creds.secret_key, "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + eq_(creds.session_token, None) + + +class StaticProviderTest(TestCase): + def test_static_credentials(self): + provider = StaticProvider("UXHW", "SECRET") + creds = provider.retrieve() + eq_(creds.access_key, "UXHW") + eq_(creds.secret_key, "SECRET") + eq_(creds.session_token, None) diff --git a/testbed/minio__minio-py/tests/unit/generate_xml_test.py b/testbed/minio__minio-py/tests/unit/generate_xml_test.py new file mode 100644 index 0000000000000000000000000000000000000000..830c7bf5e33836495217ac59a16e56b0849b11cf --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/generate_xml_test.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016, 2017, 2018, 2019 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import eq_ + +from minio.definitions import Part +from minio.xml_marshal import marshal_complete_multipart + + +class GenerateRequestTest(TestCase): + def test_generate_complete_multipart_upload(self): + expected_string = (b'' + b'1' + b'"a54357aff0632cce46d942af68356b38"' + b'' + b'2' + b'"0c78aef83f66abc1fa1e8477f296d394"' + b'' + b'3' + b'"acbd18db4cc2f85cedef654fccc4a4d8"' + b'' + b'') + + etags = [ + Part(1, 'a54357aff0632cce46d942af68356b38'), + Part(2, '0c78aef83f66abc1fa1e8477f296d394'), + Part(3, 'acbd18db4cc2f85cedef654fccc4a4d8'), + ] + actual_string = marshal_complete_multipart(etags) + eq_(expected_string, actual_string) diff --git a/testbed/minio__minio-py/tests/unit/get_bucket_policy_test.py b/testbed/minio__minio-py/tests/unit/get_bucket_policy_test.py new file mode 100644 index 0000000000000000000000000000000000000000..04956f0ffbc024ad90bc37ea0632e6a57343ecfe --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/get_bucket_policy_test.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import json +from unittest import TestCase + +import mock +from nose.tools import eq_, raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT +from minio.error import S3Error +from tests.unit.minio_mocks import MockConnection, MockResponse + + +class GetBucketPolicyTest(TestCase): + @mock.patch('urllib3.PoolManager') + @raises(S3Error) + def test_get_policy_for_non_existent_bucket(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + bucket_name = 'non-existent-bucket' + error = ("" + "NoSuchBucket" + "No such bucket1234" + "/non-existent-bucket" + "abcd" + "non-existent-bucket" + "") + mock_server.mock_add_request( + MockResponse( + 'GET', + 'https://localhost:9000/' + bucket_name + '?policy=', + {'User-Agent': _DEFAULT_USER_AGENT}, + 404, + response_headers={"Content-Type": "application/xml"}, + content=error.encode() + ) + ) + client = Minio('localhost:9000') + client.get_bucket_policy(bucket_name) + + @mock.patch('urllib3.PoolManager') + def test_get_policy_for_existent_bucket(self, mock_connection): + mock_data = json.dumps({ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetBucketLocation", + "Resource": "arn:aws:s3:::test-bucket" + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::test-bucket" + }, + { + "Sid": "", + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::test-bucket/*" + } + ] + }).encode() + mock_server = MockConnection() + mock_connection.return_value = mock_server + bucket_name = 'test-bucket' + mock_server.mock_add_request( + MockResponse( + 'GET', + 'https://localhost:9000/' + bucket_name + '?policy=', + {'User-Agent': _DEFAULT_USER_AGENT}, + 200, + content=mock_data + ) + ) + client = Minio('localhost:9000') + response = client.get_bucket_policy(bucket_name) + eq_(response, mock_data.decode()) diff --git a/testbed/minio__minio-py/tests/unit/get_object_test.py b/testbed/minio__minio-py/tests/unit/get_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..72fda3449dc60ec4a6c84bc94530d3589f6f1e69 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/get_object_test.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT +from minio.error import S3Error + +from .helpers import generate_error +from .minio_mocks import MockConnection, MockResponse + + +class GetObjectTest(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.get_object('hello', 1234) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.get_object('hello', ' \t \n ') + + @mock.patch('urllib3.PoolManager') + @raises(S3Error) + def test_get_object_throws_fail(self, mock_connection): + error_xml = generate_error('code', 'message', 'request_id', + 'host_id', 'resource', 'bucket', + 'object') + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('GET', + 'https://localhost:9000/hello/key', + {'User-Agent': _DEFAULT_USER_AGENT}, + 404, + response_headers={"Content-Type": "application/xml"}, + content=error_xml.encode()) + ) + client = Minio('localhost:9000') + client.get_object('hello', 'key') diff --git a/testbed/minio__minio-py/tests/unit/header_value_test.py b/testbed/minio__minio-py/tests/unit/header_value_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9777dd5a1cb03179b18dd530cc15ba2b7b013b99 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/header_value_test.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2018 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import eq_ + +from minio.helpers import (amzprefix_user_metadata, is_amz_header, + is_storageclass_header, is_supported_header) + + +class HeaderTests(TestCase): + header_variants = { + "content-type": [ + "content-type", + "Content-Type", + "CONTENT-TYPE", + "cONTENT-tYPE", + "cOntent-TypE", + "CoNTENT-tYPe", + ], + "x-amz-meta-me": [ + "x-amz-meta-me", + "X-Amz-Meta-Me", + "X-AMZ-META-ME", + "x-aMZ-mETA-mE", + ], + "cache-control": [ + "cache-control", + "Cache-Control", + "CACHE-CONTROL", + "cACHE-cONTROL", + "CacHe-conTrol", + ], + "content-disposition": [ + "content-disposition", + "Content-Disposition", + "CONTENT-DISPOSITION", + "cONTENT-dISPOSITION", + "conTent-disPositioN", + ], + "content-language": [ + "content-language", + "Content-Language", + "CONTENT-LANGUAGE", + "conTent-Language", + ], + "x-amz-website-redirect-location": [ + "x-amz-website-redirect-location", + "X-Amz-Website-Redirect-Location", + "X-AMZ-WEBSITE-REDIRECT-LOCATION", + "x-aMZ-wEBSITE-rEDIRECT-lOCATION", + ], + "x-amz-meta-status-code": [ + "x-amz-meta-status-code", + "X-Amz-Meta-Status-Code", + "X-AMZ-META-STATUS-CODE", + "x-aMZ-mETA-sTATUS-cODE", + ], + "x-amz-server-side-encryption": [ + "x-amz-server-side-encryption", + "X-Amz-Server-Side-Encryption", + "X-AMZ-SERVER-SIDE-ENCRYPTION", + "x-aMZ-sERVER-sIDE-eNCRYPTION", + ], + "x-amz-storage-class": [ + "x-amz-storage-class", + "X-Amz-Storage-Class", + "X-AMZ-STORAGE-CLASS", + "x-aMZ-sTORAGE-cLASS", + ], + } + + def check_ok_header(self, check_fun, header): + for header_variant in self.header_variants.get(header, [header]): + eq_(check_fun(header_variant), True) + + def check_bad_header(self, check_fun, header): + for header_variant in self.header_variants.get(header, [header]): + eq_(check_fun(header_variant), False) + + def test_is_supported_header(self): + self.check_ok_header(is_supported_header, "content-type") + self.check_ok_header(is_supported_header, "cache-control") + self.check_ok_header(is_supported_header, "content-disposition") + self.check_ok_header(is_supported_header, "content-encoding") + self.check_ok_header(is_supported_header, "content-language") + self.check_ok_header(is_supported_header, + "x-amz-website-redirect-location") + + def test_is_not_supported_header(self): + self.check_bad_header(is_supported_header, "x-amz-meta-me") + + def test_is_amz_header(self): + self.check_ok_header(is_amz_header, "x-amz-meta-status-code") + self.check_ok_header(is_amz_header, "x-amz-server-side-encryption") + + def test_is_not_amz_header(self): + self.check_bad_header(is_amz_header, "X_AMZ_META-VALUE") + self.check_bad_header(is_amz_header, "content-type") + + def test_is_storageclass_header(self): + self.check_ok_header(is_storageclass_header, "x-amz-storage-class") + + def test_is_not_storageclass_header(self): + self.check_bad_header(is_storageclass_header, "x-amz-storage-classs") + + def test_amzprefix_user_metadata(self): + metadata = { + 'x-amz-meta-testing': 'values', + 'x-amz-meta-setting': 'zombies', + 'amz-meta-setting': 'zombiesddd', + 'hhh': 34, + 'u_u': 'dd', + 'y-fu-bar': 'zoo', + 'Content-Type': 'application/csv', + 'x-amz-storage-class': 'REDUCED_REDUNDANCY', + 'content-language': 'fr' + } + m = amzprefix_user_metadata(metadata) + self.assertTrue('Content-Type' in m) + self.assertTrue('content-language' in m) + + self.assertTrue('X-Amz-Meta-hhh' in m) + self.assertTrue('x-amz-storage-class' in m) + self.assertTrue('X-Amz-Meta-amz-meta-setting' in m) diff --git a/testbed/minio__minio-py/tests/unit/helpers.py b/testbed/minio__minio-py/tests/unit/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c37fc5c5396a2477dfba55d454444dfe8f1687c1 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/helpers.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def generate_error(code, message, request_id, host_id, + resource, bucket_name, object_name): + return ''' + + {0} + {1} + {2} + {3} + {4} + {5} + {6} + + '''.format(code, message, request_id, host_id, + resource, bucket_name, object_name) diff --git a/testbed/minio__minio-py/tests/unit/lifecycleconfig.py b/testbed/minio__minio-py/tests/unit/lifecycleconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ecde85fda22145bc7c29e2e2f5fb6ff16d9ab2 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/lifecycleconfig.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from minio import xml +from minio.commonconfig import ENABLED, Filter +from minio.lifecycleconfig import Expiration, LifecycleConfig, Rule, Transition + + +class LifecycleConfigTest(TestCase): + def test_config(self): + config = LifecycleConfig( + [ + Rule( + ENABLED, + rule_filter=Filter(prefix="documents/"), + rule_id="rule1", + transition=Transition(days=30, storage_class="GLACIER"), + ), + Rule( + ENABLED, + rule_filter=Filter(prefix="logs/"), + rule_id="rule2", + expiration=Expiration(days=365), + ), + ], + ) + xml.marshal(config) + + config = xml.unmarshal( + LifecycleConfig, + """ + + DeleteAfterBecomingNonCurrent + + logs/ + + Enabled + + 100 + + + + TransitionAfterBecomingNonCurrent + + documents/ + + Enabled + + 30 + GLACIER + + +""", + ) + xml.marshal(config) diff --git a/testbed/minio__minio-py/tests/unit/list_buckets_test.py b/testbed/minio__minio-py/tests/unit/list_buckets_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d351e3f55635cb35a443a719912c7ceee173c0 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/list_buckets_test.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timezone +from unittest import TestCase + +import mock +from nose.tools import eq_ + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class ListBucketsTest(TestCase): + @mock.patch('urllib3.PoolManager') + def test_empty_list_buckets_works(self, mock_connection): + mock_data = ('' + 'minio' + 'minio') + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('GET', 'https://localhost:9000/', + {'User-Agent': _DEFAULT_USER_AGENT}, + 200, content=mock_data) + ) + client = Minio('localhost:9000') + buckets = client.list_buckets() + count = 0 + for bucket in buckets: + count += 1 + eq_(0, count) + + @mock.patch('urllib3.PoolManager') + def test_list_buckets_works(self, mock_connection): + mock_data = ('' + 'hello' + '2015-06-22T23:07:43.240Z' + 'world' + '2015-06-22T23:07:56.766Z' + 'minio' + 'minio' + '') + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('GET', 'https://localhost:9000/', + {'User-Agent': _DEFAULT_USER_AGENT}, + 200, content=mock_data) + ) + client = Minio('localhost:9000') + buckets = client.list_buckets() + buckets_list = [] + count = 0 + for bucket in buckets: + count += 1 + buckets_list.append(bucket) + eq_(2, count) + eq_('hello', buckets_list[0].name) + eq_(datetime(2015, 6, 22, 23, 7, 43, 240000, + timezone.utc), buckets_list[0].creation_date) + eq_('world', buckets_list[1].name) + eq_(datetime(2015, 6, 22, 23, 7, 56, 766000, + timezone.utc), buckets_list[1].creation_date) diff --git a/testbed/minio__minio-py/tests/unit/list_objects_test.py b/testbed/minio__minio-py/tests/unit/list_objects_test.py new file mode 100644 index 0000000000000000000000000000000000000000..306fe8ce20e0c3e9fc7d301daf183bc38bd42df2 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/list_objects_test.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015-2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import eq_, timed + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class ListObjectsTest(TestCase): + @mock.patch('urllib3.PoolManager') + def test_empty_list_objects_works(self, mock_connection): + mock_data = ''' + + bucket + + 0 + 1000 + + false +''' + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket?delimiter=&list-type=2" + "&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data, + ), + ) + client = Minio('localhost:9000') + object_iter = client.list_objects('bucket', recursive=True) + objects = [] + for obj in object_iter: + objects.append(obj) + eq_(0, len(objects)) + + @timed(1) + @mock.patch('urllib3.PoolManager') + def test_list_objects_works(self, mock_connection): + mock_data = ''' + + bucket + + 2 + 1000 + false + + 6/f/9/6f9898076bb08572403f95dbb86c5b9c85e1e1b3 + 2016-11-27T07:55:53.000Z + "5d5512301b6b6e247b8aec334b2cf7ea" + 493 + REDUCED_REDUNDANCY + + + b/d/7/bd7f6410cced55228902d881c2954ebc826d7464 + 2016-11-27T07:10:27.000Z + "f00483d523ffc8b7f2883ae896769d85" + 493 + REDUCED_REDUNDANCY + +''' + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket?delimiter=%2F&list-type=2" + "&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data, + ), + ) + client = Minio('localhost:9000') + objects_iter = client.list_objects('bucket') + objects = [] + for obj in objects_iter: + objects.append(obj) + + eq_(2, len(objects)) diff --git a/testbed/minio__minio-py/tests/unit/list_objects_v1_test.py b/testbed/minio__minio-py/tests/unit/list_objects_v1_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c0bb584fd0bedebcf8c0687d2d73238740cebb83 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/list_objects_v1_test.py @@ -0,0 +1,222 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015-2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import eq_, timed + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class ListObjectsV1Test(TestCase): + @mock.patch('urllib3.PoolManager') + def test_empty_list_objects_works(self, mock_connection): + mock_data = ''' + + bucket + + + false + 1000 + +''' + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket" + "?delimiter=&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data, + ), + ) + client = Minio('localhost:9000') + bucket_iter = client.list_objects( + 'bucket', recursive=True, use_api_v1=True, + ) + buckets = [] + for bucket in bucket_iter: + buckets.append(bucket) + eq_(0, len(buckets)) + + @timed(1) + @mock.patch('urllib3.PoolManager') + def test_list_objects_works(self, mock_connection): + mock_data = ''' + + bucket + + + 1000 + + false + + key1 + 2015-05-05T02:21:15.716Z + 5eb63bbbe01eeed093cb22bb8f5acdc3 + 11 + STANDARD + + minio + minio + + + + key2 + 2015-05-05T20:36:17.498Z + 2a60eaffa7a82804bdc682ce1df6c2d4 + 1661 + STANDARD + + minio + minio + + +''' + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket" + "?delimiter=%2F&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data, + ), + ) + client = Minio('localhost:9000') + bucket_iter = client.list_objects('bucket', use_api_v1=True) + buckets = [] + for bucket in bucket_iter: + # cause an xml exception and fail if we try retrieving again + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket" + "?delimiter=%2F&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content="", + ), + ) + buckets.append(bucket) + + eq_(2, len(buckets)) + + @timed(1) + @mock.patch('urllib3.PoolManager') + def test_list_objects_works_well(self, mock_connection): + mock_data1 = ''' + + bucket + + + marker + 1000 + + true + + key1 + 2015-05-05T02:21:15.716Z + 5eb63bbbe01eeed093cb22bb8f5acdc3 + 11 + STANDARD + + minio + minio + + + + key2 + 2015-05-05T20:36:17.498Z + 2a60eaffa7a82804bdc682ce1df6c2d4 + 1661 + STANDARD + + minio + minio + + +''' + mock_data2 = ''' + + bucket + + + 1000 + + false + + key3 + 2015-05-05T02:21:15.716Z + 5eb63bbbe01eeed093cb22bb8f5acdc3 + 11 + STANDARD + + minio + minio + + + + key4 + 2015-05-05T20:36:17.498Z + 2a60eaffa7a82804bdc682ce1df6c2d4 + 1661 + STANDARD + + minio + minio + + +''' + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket" + "?delimiter=&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data1, + ), + ) + client = Minio('localhost:9000') + bucket_iter = client.list_objects( + 'bucket', recursive=True, use_api_v1=True, + ) + buckets = [] + for bucket in bucket_iter: + mock_server.mock_add_request( + MockResponse( + "GET", + "https://localhost:9000/bucket" + "?delimiter=&marker=marker&max-keys=1000&prefix=", + {"User-Agent": _DEFAULT_USER_AGENT}, + 200, + content=mock_data2, + ), + ) + buckets.append(bucket) + + eq_(4, len(buckets)) diff --git a/testbed/minio__minio-py/tests/unit/make_bucket_test.py b/testbed/minio__minio-py/tests/unit/make_bucket_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b894dd54d754034bdf8fdfc2ca00c5983256948e --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/make_bucket_test.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT +from minio.error import S3Error + +from .helpers import generate_error +from .minio_mocks import MockConnection, MockResponse + + +class MakeBucket(TestCase): + @raises(TypeError) + def test_bucket_is_string(self): + client = Minio('localhost:9000') + client.make_bucket(1234) + + @raises(ValueError) + def test_bucket_is_not_empty_string(self): + client = Minio('localhost:9000') + client.make_bucket(' \t \n ') + + @mock.patch('urllib3.PoolManager') + def test_make_bucket_works(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('PUT', + 'https://localhost:9000/hello', + {'User-Agent': _DEFAULT_USER_AGENT}, + 200) + ) + Minio('localhost:9000') + + @mock.patch('urllib3.PoolManager') + @raises(S3Error) + def test_make_bucket_throws_fail(self, mock_connection): + error_xml = generate_error('code', 'message', 'request_id', + 'host_id', 'resource', 'bucket', + 'object') + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('PUT', + 'https://localhost:9000/hello', + {'User-Agent': _DEFAULT_USER_AGENT}, + 409, + response_headers={"Content-Type": "application/xml"}, + content=error_xml.encode()) + ) + client = Minio('localhost:9000') + client.make_bucket('hello') diff --git a/testbed/minio__minio-py/tests/unit/minio_mocks.py b/testbed/minio__minio-py/tests/unit/minio_mocks.py new file mode 100644 index 0000000000000000000000000000000000000000..51f0ea63f501d9b48dbae2ea17a781b43574ee39 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/minio_mocks.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015-2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from http import client as httplib + +from nose.tools import eq_ + + +class MockResponse(object): + def __init__(self, method, url, headers, status_code, + response_headers=None, content=None): + self.method = method + self.url = url + self.request_headers = { + key.lower(): value for key, value in headers.items() + } + self.status = status_code + self.headers = { + key.lower(): value for key, value in ( + response_headers or {}).items() + } + self.data = content + if content is None: + self.reason = httplib.responses[status_code] + + # noinspection PyUnusedLocal + def read(self, *args, **kwargs): + return self.data + + def mock_verify(self, method, url, headers): + eq_(self.method, method) + eq_(self.url, url) + headers = { + key.lower(): value for key, value in headers.items() + } + for header in self.request_headers: + eq_(self.request_headers[header], headers[header]) + + # noinspection PyUnusedLocal + def stream(self, chunk_size=1, decode_unicode=False): + if self.data is not None: + return iter(bytearray(self.data, 'utf-8')) + return iter([]) + + # dummy release connection call. + def release_conn(self): + return + + def getheader(self, key, value=None): + return self.headers.get(key, value) if self.headers else value + + def __getitem__(self, key): + if key == "status": + return self.status + + +class MockConnection(object): + def __init__(self): + self.requests = [] + + def mock_add_request(self, request): + self.requests.append(request) + + # noinspection PyUnusedLocal + def request(self, method, url, headers, redirect=False): + # only pop off matching requests + return_request = self.requests[0] + return_request.mock_verify(method, url, headers) + return self.requests.pop(0) + + # noinspection PyRedeclaration,PyUnusedLocal,PyUnusedLocal + + def urlopen(self, method, url, headers={}, preload_content=False, + body=None, redirect=False): + return self.request(method, url, headers) diff --git a/testbed/minio__minio-py/tests/unit/minio_test.py b/testbed/minio__minio-py/tests/unit/minio_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e35fc675d66baffded91851378b87521c1ecf40d --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/minio_test.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016, 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase +from urllib.parse import urlunsplit + +from nose.tools import eq_, raises + +from minio import Minio +from minio import __version__ as minio_version +from minio.api import _DEFAULT_USER_AGENT +from minio.definitions import BaseURL +from minio.helpers import check_bucket_name + + +class ValidBucketName(TestCase): + @raises(ValueError) + def test_bucket_name(self): + check_bucket_name('bucketName=', False) + + @raises(ValueError) + def test_bucket_name_invalid_characters(self): + check_bucket_name('$$$bcuket', False) + + @raises(ValueError) + def test_bucket_name_length(self): + check_bucket_name('dd', False) + + @raises(ValueError) + def test_bucket_name_periods(self): + check_bucket_name('dd..mybucket', False) + + @raises(ValueError) + def test_bucket_name_begins_period(self): + check_bucket_name('.ddmybucket', False) + + +class GetURLTests(TestCase): + def test_url_build(self): + url = BaseURL('http://localhost:9000', None) + eq_( + urlunsplit(url.build("GET", None, bucket_name='bucket-name')), + 'http://localhost:9000/bucket-name', + ) + eq_( + urlunsplit( + url.build("GET", None, bucket_name='bucket-name', + object_name='objectName'), + ), + 'http://localhost:9000/bucket-name/objectName', + ) + eq_( + urlunsplit( + url.build("GET", 'us-east-1', bucket_name='bucket-name', + object_name='objectName', + query_params={'foo': 'bar'}), + ), + 'http://localhost:9000/bucket-name/objectName?foo=bar', + ) + eq_( + urlunsplit( + url.build("GET", 'us-east-1', bucket_name='bucket-name', + object_name='objectName', + query_params={'foo': 'bar', 'b': 'c', 'a': 'b'}), + ), + 'http://localhost:9000/bucket-name/objectName?a=b&b=c&foo=bar', + ) + eq_( + urlunsplit( + url.build("GET", 'us-east-1', bucket_name='bucket-name', + object_name='path/to/objectName/'), + ), + 'http://localhost:9000/bucket-name/path/to/objectName/', + ) + + # S3 urls. + url = BaseURL('https://s3.amazonaws.com', None) + eq_( + urlunsplit(url.build("GET", "us-east-1")), + 'https://s3.us-east-1.amazonaws.com/', + ) + eq_( + urlunsplit( + url.build("GET", "eu-west-1", bucket_name='my.bucket.name'), + ), + 'https://s3.eu-west-1.amazonaws.com/my.bucket.name', + ) + eq_( + urlunsplit( + url.build("GET", 'us-west-2', bucket_name='bucket-name', + object_name='objectName'), + ), + 'https://bucket-name.s3.us-west-2.amazonaws.com/objectName', + ) + eq_( + urlunsplit( + url.build("GET", "us-east-1", bucket_name='bucket-name', + object_name='objectName', + query_params={'versionId': 'uuid'}), + ), + "https://bucket-name.s3.us-east-1.amazonaws.com" + "/objectName?versionId=uuid", + ) + + @raises(TypeError) + def test_minio_requires_string(self): + Minio(10) + + @raises(ValueError) + def test_minio_requires_hostname(self): + Minio('http://') + + +class UserAgentTests(TestCase): + def test_default_user_agent(self): + client = Minio('localhost') + eq_(client._user_agent, _DEFAULT_USER_AGENT) + + def test_set_app_info(self): + client = Minio('localhost') + expected_user_agent = _DEFAULT_USER_AGENT + ' hello/' + minio_version + client.set_app_info('hello', minio_version) + eq_(client._user_agent, expected_user_agent) + + @raises(ValueError) + def test_set_app_info_requires_non_empty_name(self): + client = Minio('localhost:9000') + client.set_app_info('', minio_version) + + @raises(ValueError) + def test_set_app_info_requires_non_empty_version(self): + client = Minio('localhost:9000') + client.set_app_info('hello', '') + + +class GetRegionTests(TestCase): + def test_region_none(self): + region = BaseURL('http://localhost', None).region + eq_(region, None) + + def test_region_us_west(self): + region = BaseURL('https://s3-us-west-1.amazonaws.com', None).region + eq_(region, None) + + def test_region_with_dot(self): + region = BaseURL('https://s3.us-west-1.amazonaws.com', None).region + eq_(region, 'us-west-1') + + def test_region_with_dualstack(self): + region = BaseURL( + 'https://s3.dualstack.us-west-1.amazonaws.com', None, + ).region + eq_(region, 'us-west-1') + + def test_region_us_east(self): + region = BaseURL('http://s3.amazonaws.com', None).region + eq_(region, None) + + @raises(ValueError) + def test_invalid_value(self): + BaseURL(None, None) diff --git a/testbed/minio__minio-py/tests/unit/presigned_get_object_test.py b/testbed/minio__minio-py/tests/unit/presigned_get_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c806c66abbe22d37e1be6cca5ce3c8121454f500 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/presigned_get_object_test.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import timedelta +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio + + +class PresignedGetObjectTest(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.presigned_get_object('hello', 1234) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.presigned_get_object('hello', ' \t \n ') + + @raises(ValueError) + def test_expiry_limit(self): + client = Minio('localhost:9000') + client.presigned_get_object('hello', 'key', expires=timedelta(days=8)) + + def test_can_include_response_headers(self): + client = Minio('localhost:9000', 'my_access_key', 'my_secret_key', + secure=True) + client._get_region = mock.Mock(return_value='us-east-1') + r = client.presigned_get_object( + 'mybucket', 'myfile.pdf', + response_headers={ + 'Response-Content-Type': 'application/pdf', + 'Response-Content-Disposition': 'inline; filename="test.pdf"' + }) + self.assertIn('inline', r) + self.assertIn('test.pdf', r) + self.assertIn('application%2Fpdf', r) diff --git a/testbed/minio__minio-py/tests/unit/presigned_put_object_test.py b/testbed/minio__minio-py/tests/unit/presigned_put_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4e742980443bcc055a8bcb6a963383465cc925 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/presigned_put_object_test.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import timedelta +from unittest import TestCase + +from nose.tools import raises + +from minio import Minio + + +class PresignedPutObjectTest(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.presigned_put_object('hello', 1234) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.presigned_put_object('hello', ' \t \n ') + + @raises(ValueError) + def test_expiry_limit(self): + client = Minio('localhost:9000') + client.presigned_put_object('hello', 'key', expires=timedelta(days=8)) diff --git a/testbed/minio__minio-py/tests/unit/put_object_test.py b/testbed/minio__minio-py/tests/unit/put_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8794a85f1652ee0b37b26731dbae77b344636f --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/put_object_test.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import raises + +from minio import Minio + + +class PutObjectTest(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.put_object('hello', 1234, 1, iter([1, 2, 3])) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.put_object('hello', ' \t \n ', 1, iter([1, 2, 3])) + + @raises(TypeError) + def test_length_is_string(self): + client = Minio('localhost:9000') + client.put_object('hello', 1234, '1', iter([1, 2, 3])) + + @raises(ValueError) + def test_length_is_not_empty_string(self): + client = Minio('localhost:9000') + client.put_object('hello', ' \t \n ', -1, iter([1, 2, 3])) diff --git a/testbed/minio__minio-py/tests/unit/remove_bucket_test.py b/testbed/minio__minio-py/tests/unit/remove_bucket_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8be2ba96e783e256236bc4b649f782a51cc79f78 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/remove_bucket_test.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class RemoveBucket(TestCase): + @raises(TypeError) + def test_bucket_is_string(self): + client = Minio('localhost:9000') + client.remove_bucket(1234) + + @raises(ValueError) + def test_bucket_is_not_empty_string(self): + client = Minio('localhost:9000') + client.remove_bucket(' \t \n ') + + @raises(ValueError) + def test_remove_bucket_invalid_name(self): + client = Minio('localhost:9000') + client.remove_bucket('AB*CD') + + @mock.patch('urllib3.PoolManager') + def test_remove_bucket_works(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('DELETE', + 'https://localhost:9000/hello', + {'User-Agent': _DEFAULT_USER_AGENT}, 204) + ) + client = Minio('localhost:9000') + client.remove_bucket('hello') diff --git a/testbed/minio__minio-py/tests/unit/remove_object_test.py b/testbed/minio__minio-py/tests/unit/remove_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c3ec898bac0c61e74f814b6e59cff3f7eaa4313c --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/remove_object_test.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class StatObject(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.remove_object('hello', 1234) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.remove_object('hello', ' \t \n ') + + @raises(ValueError) + def test_remove_bucket_invalid_name(self): + client = Minio('localhost:9000') + client.remove_object('AB*CD', 'world') + + @mock.patch('urllib3.PoolManager') + def test_remove_object_works(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('DELETE', + 'https://localhost:9000/hello/world', + {'User-Agent': _DEFAULT_USER_AGENT}, 204) + ) + client = Minio('localhost:9000') + client.remove_object('hello', 'world') diff --git a/testbed/minio__minio-py/tests/unit/remove_objects_test.py b/testbed/minio__minio-py/tests/unit/remove_objects_test.py new file mode 100644 index 0000000000000000000000000000000000000000..af2dbc26dc668865da0dc1167e562dbade5663be --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/remove_objects_test.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class RemoveObjectsTest(TestCase): + @raises(TypeError) + def test_object_is_non_string_iterable_1(self): + client = Minio('localhost:9000') + for err in client.remove_objects('hello', 1234): + print(err) + + @raises(TypeError) + def test_object_is_non_string_iterable_2(self): + client = Minio('localhost:9000') + for err in client.remove_objects('hello', u'abc'): + print(err) + + @raises(TypeError) + def test_object_is_non_string_iterable_3(self): + client = Minio('localhost:9000') + for err in client.remove_objects('hello', b'abc'): + print(err) + + @raises(ValueError) + def test_bucket_invalid_name(self): + client = Minio('localhost:9000') + for err in client.remove_objects('AB&CD', 'world'): + print(err) + + @mock.patch('urllib3.PoolManager') + def test_object_is_list(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('POST', + 'https://localhost:9000/hello?delete=', + {'User-Agent': _DEFAULT_USER_AGENT, + 'Content-Md5': u'5Tg5SmU9Or43L4+iIyfPrQ=='}, 200, + content='') + ) + client = Minio('localhost:9000') + for err in client.remove_objects('hello', ["Ab", "c"]): + print(err) + + @mock.patch('urllib3.PoolManager') + def test_object_is_tuple(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('POST', + 'https://localhost:9000/hello?delete=', + {'User-Agent': _DEFAULT_USER_AGENT, + 'Content-Md5': u'5Tg5SmU9Or43L4+iIyfPrQ=='}, 200, + content='') + ) + client = Minio('localhost:9000') + for err in client.remove_objects('hello', ('Ab', 'c')): + print(err) + + @mock.patch('urllib3.PoolManager') + def test_object_is_iterator(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('POST', + 'https://localhost:9000/hello?delete=', + {'User-Agent': _DEFAULT_USER_AGENT, + 'Content-Md5': u'5Tg5SmU9Or43L4+iIyfPrQ=='}, 200, + content='') + ) + client = Minio('localhost:9000') + it = itertools.chain(('Ab', 'c')) + for err in client.remove_objects('hello', it): + print(err) diff --git a/testbed/minio__minio-py/tests/unit/replicationconfig.py b/testbed/minio__minio-py/tests/unit/replicationconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..86e389032de625364174eace1769d22967e5b8b5 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/replicationconfig.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from minio import xml +from minio.commonconfig import DISABLED, ENABLED, AndOperator, Filter +from minio.replicationconfig import (DeleteMarkerReplication, Destination, + ReplicationConfig, Rule) + + +class ReplicationConfigTest(TestCase): + def test_config(self): + config = ReplicationConfig( + "REPLACE-WITH-ACTUAL-ROLE", + [ + Rule( + Destination( + "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", + ), + ENABLED, + delete_marker_replication=DeleteMarkerReplication( + DISABLED, + ), + rule_filter=Filter( + AndOperator( + "TaxDocs", + {"key1": "value1", "key2": "value2"}, + ), + ), + rule_id="rule1", + priority=1, + ), + ], + ) + xml.marshal(config) + + config = xml.unmarshal( + ReplicationConfig, + """ + arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3 + + rule1 + Enabled + 1 + + Disabled + + + + TaxDocs + + key1 + value1 + + + key1 + value1 + + + + + arn:aws:s3:::exampletargetbucket + + +""", + ) + xml.marshal(config) diff --git a/testbed/minio__minio-py/tests/unit/set_bucket_notification_test.py b/testbed/minio__minio-py/tests/unit/set_bucket_notification_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7da3b928aca99d66defe59fa1c27e2e93c2bfb18 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/set_bucket_notification_test.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class SetBucketNotificationTest(TestCase): + @raises(TypeError) + def test_notification_is_dict_1(self): + client = Minio('localhost:9000') + client.set_bucket_notification('my-test-bucket', 'abc') + + @raises(TypeError) + def test_notification_is_dict_2(self): + client = Minio('localhost:9000') + client.set_bucket_notification('my-test-bucket', ['myconfig1']) + + @raises(ValueError) + def test_notification_config_is_nonempty(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + {} + ) + + @raises(ValueError) + def test_notification_config_has_valid_keys(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfiguration': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_arn_key_is_present(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Events': ['s3:ObjectCreated:*'], + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_id_key_is_string(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': 1, + 'Arn': 'abc', + 'Events': ['s3:ObjectCreated:*'], + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_events_key_is_present(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_event_values_are_valid(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['object_created'] + } + ] + } + ) + + @mock.patch('urllib3.PoolManager') + def test_notification_config_id_key_is_optional(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + 'PUT', + 'https://localhost:9000/my-test-bucket?notification=', + { + 'Content-Md5': 'f+TfVp/A4pNnI7S4S+MkFg==', + 'User-Agent': _DEFAULT_USER_AGENT, + }, + 200, content="" + ) + ) + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_has_valid_event_names(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['object_created'], + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_1(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': [] + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_2(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'S3Key': { + } + } + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_3(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + } + } + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_4(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [] + } + } + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_5(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'rule1': 'ab', + 'val1': 'abc' + } + ] + } + } + } + ] + } + ) + + @raises(ValueError) + def test_notification_config_filterspec_is_valid_6(self): + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'ab', + 'Value': 'abc' + } + ] + } + } + } + ] + } + ) + + @mock.patch('urllib3.PoolManager') + def test_notification_config_filterspec_is_valid_7(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + 'PUT', + 'https://localhost:9000/my-test-bucket?notification=', + { + 'Content-Md5': 'k97dHBBUq9MR7ZViy7oUsw==', + 'User-Agent': _DEFAULT_USER_AGENT, + }, + 200, content="" + ) + ) + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'prefix', + 'Value': 'abc' + } + ] + } + } + } + ] + } + ) + + @mock.patch('urllib3.PoolManager') + def test_notification_config_filterspec_is_valid_8(self, mock_connection): + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse( + 'PUT', + 'https://localhost:9000/my-test-bucket?notification=', + { + 'Content-Md5': '2aIwAt1lAd5JShphHCD4GA==', + 'User-Agent': _DEFAULT_USER_AGENT, + }, + 200, content="" + ) + ) + client = Minio('localhost:9000') + client.set_bucket_notification( + 'my-test-bucket', + { + 'QueueConfigurations': [ + { + 'Id': '1', + 'Arn': 'arn1', + 'Events': ['s3:ObjectCreated:*'], + 'Filter': { + 'Key': { + 'FilterRules': [ + { + 'Name': 'suffix', + 'Value': 'abc' + } + ] + } + } + } + ] + } + ) diff --git a/testbed/minio__minio-py/tests/unit/sign_test.py b/testbed/minio__minio-py/tests/unit/sign_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ce095f717c92c874bd3fe468a548d9bdd5c348 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/sign_test.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import hashlib +import hmac +from datetime import datetime +from unittest import TestCase +from urllib.parse import urlsplit, urlunsplit + +import mock +import pytz as pytz +from nose.tools import eq_, raises + +from minio import Minio +from minio.credentials import Credentials +from minio.helpers import RFC3339NANO, queryencode, quote, sha256_hash +from minio.signer import (_get_authorization, _get_canonical_request_hash, + _get_scope, _get_signing_key, _get_string_to_sign, + presign_v4, sign_v4_s3) + +empty_hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' +dt = datetime(2015, 6, 20, 1, 2, 3, 0, pytz.utc) + + +class CanonicalRequestTest(TestCase): + def test_simple_request(self): + url = urlsplit('http://localhost:9000/hello') + expected_signed_headers = ['x-amz-content-sha256', 'x-amz-date'] + expected_request_array = ['PUT', '/hello', '', + 'x-amz-content-sha256:' + + empty_hash, 'x-amz-date:dateString', + '', ';'.join(expected_signed_headers), + empty_hash] + headers_to_sign = {'x-amz-date': 'dateString', + 'x-amz-content-sha256': empty_hash} + + expected_request = sha256_hash('\n'.join(expected_request_array)) + actual_request = _get_canonical_request_hash( + "PUT", url, headers_to_sign, empty_hash, + ) + eq_(expected_request, actual_request[0]) + + def test_request_with_query(self): + url = urlsplit('http://localhost:9000/hello?c=d&e=f&a=b') + expected_signed_headers = ['x-amz-content-sha256', 'x-amz-date'] + expected_request_array = ['PUT', '/hello', 'a=b&c=d&e=f', + 'x-amz-content-sha256:' + empty_hash, + 'x-amz-date:dateString', + '', ';'.join(expected_signed_headers), + empty_hash] + + expected_request = sha256_hash('\n'.join(expected_request_array)) + + headers_to_sign = {'x-amz-date': 'dateString', + 'x-amz-content-sha256': empty_hash} + actual_request = _get_canonical_request_hash( + "PUT", url, headers_to_sign, empty_hash, + ) + eq_(expected_request, actual_request[0]) + + +class StringToSignTest(TestCase): + def test_signing_key(self): + expected_signing_key_list = [ + 'AWS4-HMAC-SHA256', '20150620T010203Z', + '20150620/us-east-1/s3/aws4_request', + 'b93e86965c269a0dfef37a8bec231ef8acf8cdb101a64eb700a46c452c1ad233' + ] + + actual_signing_key = _get_string_to_sign( + dt, _get_scope(dt, 'us-east-1', "s3"), + 'b93e86965c269a0dfef37a8bec231ef8acf8cdb101a64eb700a46c452c1ad233') + eq_('\n'.join(expected_signing_key_list), actual_signing_key) + + +class SigningKeyTest(TestCase): + def test_generate_signing_key(self): + key1_string = 'AWS4' + 'S3CR3T' + key1 = key1_string.encode('utf-8') + key2 = hmac.new(key1, '20150620'.encode( + 'utf-8'), hashlib.sha256).digest() + key3 = hmac.new(key2, 'region'.encode( + 'utf-8'), hashlib.sha256).digest() + key4 = hmac.new(key3, 's3'.encode('utf-8'), hashlib.sha256).digest() + expected_result = hmac.new(key4, 'aws4_request'.encode( + 'utf-8'), hashlib.sha256).digest() + + actual_result = _get_signing_key('S3CR3T', dt, 'region', "s3") + eq_(expected_result, actual_result) + + +class AuthorizationHeaderTest(TestCase): + def test_generate_authentication_header(self): + expected_authorization_header = ( + 'AWS4-HMAC-SHA256 Credential=' + 'public_key/20150620/region/s3/aws4_request, ' + 'SignedHeaders=host;X-Amz-Content-Sha256;X-Amz-Date, ' + 'Signature=signed_request' + ) + actual_authorization_header = _get_authorization( + 'public_key', _get_scope(dt, 'region', "s3"), + 'host;X-Amz-Content-Sha256;X-Amz-Date', 'signed_request') + eq_(expected_authorization_header, actual_authorization_header) + + +class PresignURLTest(TestCase): + def test_presigned_versioned_id(self): + credentials = Credentials("minio", "minio123") + url = presign_v4('GET', urlsplit('http://localhost:9000/bucket-name/objectName?versionId=uuid'), + 'us-east-1', credentials, dt, 604800) + + eq_(urlunsplit(url), 'http://localhost:9000/bucket-name/objectName?versionId=uuid&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minio%2F20150620%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20150620T010203Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=3ce13e2ca929fafa20581a05730e4e9435f2a5e20ec7c5a082d175692fb0a663') + + +class SignV4Test(TestCase): + def test_signv4(self): + client = Minio("localhost:9000", access_key="minio", + secret_key="minio123", secure=False) + creds = client._provider.retrieve() + headers = { + 'Host': 'localhost:9000', + 'x-amz-content-sha256': + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', + 'x-amz-date': '20150620T010203Z', + } + url = client._base_url.build( + "PUT", + "us-east-1", + bucket_name="testbucket", + object_name="~testobject", + query_params={"partID": "1", "uploadID": "~abcd"}, + ) + headers = sign_v4_s3( + "PUT", + url, + "us-east-1", + headers, + creds, + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + dt, + ) + eq_(headers['Authorization'], + 'AWS4-HMAC-SHA256 Credential=' + 'minio/20150620/us-east-1/s3/aws4_request, ' + 'SignedHeaders=host;x-amz-content-sha256;x-amz-date, ' + 'Signature=' + 'a2f4546f647981732bd90dfa5a7599c44dca92f44bea48ecc7565df06032c25b') + + +class UnicodeEncodeTest(TestCase): + def test_unicode_quote(self): + eq_(quote('/test/123/汉字'), '/test/123/%E6%B1%89%E5%AD%97') + + def test_unicode_queryencode(self): + eq_(queryencode('/test/123/汉字'), '%2Ftest%2F123%2F%E6%B1%89%E5%AD%97') + + def test_unicode_quote_u(self): + eq_(quote(u'/test/123/汉字'), '/test/123/%E6%B1%89%E5%AD%97') + + def test_unicode_queryencode_u(self): + eq_(queryencode(u'/test/123/汉字'), '%2Ftest%2F123%2F%E6%B1%89%E5%AD%97') + + def test_unicode_quote_b(self): + eq_(quote(b'/test/123/\xe6\xb1\x89\xe5\xad\x97'), + '/test/123/%E6%B1%89%E5%AD%97') + + def test_unicode_queryencode_b(self): + eq_(queryencode(b'/test/123/\xe6\xb1\x89\xe5\xad\x97'), + '%2Ftest%2F123%2F%E6%B1%89%E5%AD%97') diff --git a/testbed/minio__minio-py/tests/unit/stat_object_test.py b/testbed/minio__minio-py/tests/unit/stat_object_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5f705494ddcb90f71823d5742c6fdc606091569f --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/stat_object_test.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +import mock +from nose.tools import raises + +from minio import Minio +from minio.api import _DEFAULT_USER_AGENT + +from .minio_mocks import MockConnection, MockResponse + + +class StatObject(TestCase): + @raises(TypeError) + def test_object_is_string(self): + client = Minio('localhost:9000') + client.stat_object('hello', 1234) + + @raises(ValueError) + def test_object_is_not_empty_string(self): + client = Minio('localhost:9000') + client.stat_object('hello', ' \t \n ') + + @raises(ValueError) + def test_stat_object_invalid_name(self): + client = Minio('localhost:9000') + client.stat_object('AB#CD', 'world') + + @mock.patch('urllib3.PoolManager') + def test_stat_object_works(self, mock_connection): + mock_headers = { + 'content-type': 'application/octet-stream', + 'last-modified': 'Fri, 26 Jun 2015 19:05:37 GMT', + 'content-length': 11, + 'etag': '5eb63bbbe01eeed093cb22bb8f5acdc3' + } + mock_server = MockConnection() + mock_connection.return_value = mock_server + mock_server.mock_add_request( + MockResponse('HEAD', + 'https://localhost:9000/hello/world', + {'User-Agent': _DEFAULT_USER_AGENT}, 200, + response_headers=mock_headers) + ) + client = Minio('localhost:9000') + client.stat_object('hello', 'world') diff --git a/testbed/minio__minio-py/tests/unit/trace_test.py b/testbed/minio__minio-py/tests/unit/trace_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8077c7a5df021a225220516816a900417aba1bcf --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/trace_test.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2015, 2016 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import raises + +from minio import Minio + + +class TraceTest(TestCase): + @raises(ValueError) + def test_bucket_is_string(self): + client = Minio('localhost:9000') + client.trace_on(None) diff --git a/testbed/minio__minio-py/tests/unit/versioningconfig.py b/testbed/minio__minio-py/tests/unit/versioningconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4b68cceb2467f8afbe4c827e1bc83ea402c5e6 --- /dev/null +++ b/testbed/minio__minio-py/tests/unit/versioningconfig.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, +# (C) 2020 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase + +from nose.tools import eq_ + +from minio import xml +from minio.commonconfig import DISABLED, ENABLED +from minio.versioningconfig import OFF, SUSPENDED, VersioningConfig + + +class VersioningConfigTest(TestCase): + def test_config(self): + config = VersioningConfig(ENABLED) + xml.marshal(config) + + config = xml.unmarshal( + VersioningConfig, + """ +""", + ) + xml.marshal(config) + eq_(config.status, OFF) + + config = xml.unmarshal( + VersioningConfig, + """ + Enabled +""", + ) + xml.marshal(config) + eq_(config.status, ENABLED) + + config = xml.unmarshal( + VersioningConfig, + """ + Suspended + Disabled +""", + ) + xml.marshal(config) + eq_(config.status, SUSPENDED) + eq_(config.mfa_delete, DISABLED) diff --git a/testbed/minio__minio-py/tests/unit_test.sh b/testbed/minio__minio-py/tests/unit_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4c1173aa6d0394c5efb768f38b480d715e5e1c8a --- /dev/null +++ b/testbed/minio__minio-py/tests/unit_test.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# +# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +echo "Running unit tests... " && python setup.py nosetests diff --git a/testbed/mwaskom__seaborn/.github/CONTRIBUTING.md b/testbed/mwaskom__seaborn/.github/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..7f44550f93075169ec036bcec532992fc81c6fea --- /dev/null +++ b/testbed/mwaskom__seaborn/.github/CONTRIBUTING.md @@ -0,0 +1,29 @@ +Contributing to seaborn +======================= + +General support +--------------- + +General support questions ("how do I do X?") are most at home on [StackOverflow](https://stackoverflow.com/), which has a larger audience of people who will see your post and may be able to offer assistance. Your chance of getting a quick answer will be higher if you include runnable code, a precise statement of what you are hoping to achieve, and a clear explanation of the problems that you have encountered. + +Reporting bugs +-------------- + +If you think you've encountered a bug in seaborn, please report it on the [Github issue tracker](https://github.com/mwaskom/seaborn/issues/new). To be useful, bug reports *must* include the following information: + +- A reproducible code example that demonstrates the problem +- The output that you are seeing (an image of a plot, or the error message) +- A clear explanation of why you think something is wrong +- The specific versions of seaborn and matplotlib that you are working with + +Bug reports are easiest to address if they can be demonstrated using one of the example datasets from the seaborn docs (i.e. with `seaborn.load_dataset`). Otherwise, it is preferable that your example generate synthetic data to reproduce the problem. If you can only demonstrate the issue with your actual dataset, you will need to share it, ideally as a csv. Note that you can upload a csv directly to a github issue thread, but it must have a `.txt` suffix. + +If you've encountered an error, searching the specific text of the message before opening a new issue can often help you solve the problem quickly and avoid making a duplicate report. + +Because matplotlib handles the actual rendering, errors or incorrect outputs may be due to a problem in matplotlib rather than one in seaborn. It can save time if you try to reproduce the issue in an example that uses only matplotlib, so that you can report it in the right place. But it is alright to skip this step if it's not obvious how to do it. + + +New features +------------ + +If you think there is a new feature that should be added to seaborn, you can open an issue to discuss it. But please be aware that current development efforts are mostly focused on standardizing the API and internals, and there may be relatively low enthusiasm for novel features that do not fit well into short- and medium-term development plans. diff --git a/testbed/mwaskom__seaborn/.github/dependabot.yml b/testbed/mwaskom__seaborn/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..ac27a84869a2cb5b416c12fc1fcf57aa6f626958 --- /dev/null +++ b/testbed/mwaskom__seaborn/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "weekly" diff --git a/testbed/mwaskom__seaborn/.github/workflows/ci.yaml b/testbed/mwaskom__seaborn/.github/workflows/ci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4fc9cff3032cfaf79a1f905c122a1a0fd03ba89f --- /dev/null +++ b/testbed/mwaskom__seaborn/.github/workflows/ci.yaml @@ -0,0 +1,109 @@ +name: CI + +on: + push: + branches: [master, v0.*] + pull_request: + branches: master + schedule: + - cron: '0 6 * * 1,4' # Each Monday and Thursday at 06:00 UTC + workflow_dispatch: + +env: + NB_KERNEL: python + MPLBACKEND: Agg + SEABORN_DATA: ${{ github.workspace }}/seaborn-data + +jobs: + build-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Python 3.11 + uses: actions/setup-python@v4 + with: + python-version: "3.11" + + - name: Install seaborn + run: | + pip install --upgrade pip + pip install .[stats,docs] + + - name: Install pandoc + run: | + sudo apt-get install pandoc + + - name: Cache datasets + run: | + git clone https://github.com/mwaskom/seaborn-data.git + ls $SEABORN_DATA + + - name: Build docs + env: + SPHINXOPTS: -j `nproc` + run: | + cd doc + make -j `nproc` notebooks + make html + + + run-tests: + runs-on: ubuntu-latest + + strategy: + matrix: + python: ["3.8", "3.9", "3.10", "3.11"] + install: [full] + deps: [latest] + + include: + - python: "3.8" + install: full + deps: pinned + - python: "3.11" + install: light + deps: latest + + steps: + - uses: actions/checkout@v3 + + - name: Setup Python ${{ matrix.python }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + + - name: Install seaborn + run: | + pip install --upgrade pip wheel + if [[ ${{matrix.install}} == 'full' ]]; then EXTRAS=',stats'; fi + if [[ ${{matrix.deps }} == 'pinned' ]]; then DEPS='-r ci/deps_pinned.txt'; fi + pip install .[dev$EXTRAS] $DEPS + + - name: Run tests + run: make test + + - name: Upload coverage + uses: codecov/codecov-action@v3 + if: ${{ success() }} + + lint: + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup Python + uses: actions/setup-python@v4 + + - name: Install tools + run: pip install mypy flake8 + + - name: Flake8 + run: make lint + + - name: Type checking + run: make typecheck diff --git a/testbed/mwaskom__seaborn/.gitignore b/testbed/mwaskom__seaborn/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c9e7058fe9ed42728f901ff7a1cbe8990f3b0de4 --- /dev/null +++ b/testbed/mwaskom__seaborn/.gitignore @@ -0,0 +1,16 @@ +*.pyc +*.sw* +build/ +.ipynb_checkpoints/ +dist/ +seaborn.egg-info/ +.cache/ +.coverage +cover/ +htmlcov/ +.idea/ +.vscode/ +.pytest_cache/ +.DS_Store +notes/ +notebooks/ diff --git a/testbed/mwaskom__seaborn/.pre-commit-config.yaml b/testbed/mwaskom__seaborn/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2d04a52a430e23ca4698e815fe1772753a2009a --- /dev/null +++ b/testbed/mwaskom__seaborn/.pre-commit-config.yaml @@ -0,0 +1,20 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.3.0 + hooks: + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + exclude: \.svg$ +- repo: https://github.com/pycqa/flake8 + rev: 5.0.4 + hooks: + - id: flake8 + exclude: seaborn/(cm\.py|external/) + types: [file, python] +- repo: https://github.com/pre-commit/mirrors-mypy + rev: v0.971 + hooks: + - id: mypy + args: [--follow-imports=skip] + files: seaborn/_(core|marks|stats)/ diff --git a/testbed/mwaskom__seaborn/CITATION.cff b/testbed/mwaskom__seaborn/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..ee4d598e110619d075986bb82196b5c5ef22f107 --- /dev/null +++ b/testbed/mwaskom__seaborn/CITATION.cff @@ -0,0 +1,16 @@ +cff-version: 1.2.0 +message: "If seaborn is integral to a scientific publication, please cite the following paper:" +preferred-citation: + type: article + authors: + - family-names: "Waskom" + given-names: "Michael Lawrence" + orcid: "https://orcid.org/0000-0002-9817-6869" + doi: "10.21105/joss.03021" + journal: "Journal of Open Source Software" + month: April + title: "seaborn: statistical data visualization" + issue: 6 + volume: 60 + year: 2021 + url: "https://joss.theoj.org/papers/10.21105/joss.03021" diff --git a/testbed/mwaskom__seaborn/LICENSE.md b/testbed/mwaskom__seaborn/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b5ebba626349f543886619b6007dee5430b3f345 --- /dev/null +++ b/testbed/mwaskom__seaborn/LICENSE.md @@ -0,0 +1,27 @@ +Copyright (c) 2012-2021, Michael L. Waskom +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the project nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/testbed/mwaskom__seaborn/Makefile b/testbed/mwaskom__seaborn/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..86b406ee551d5422177a6cb6855bb150fd666eb1 --- /dev/null +++ b/testbed/mwaskom__seaborn/Makefile @@ -0,0 +1,10 @@ +export SHELL := /bin/bash + +test: + pytest -n auto --cov=seaborn --cov=tests --cov-config=setup.cfg tests + +lint: + flake8 seaborn + +typecheck: + mypy --follow-imports=skip seaborn/_core seaborn/_marks seaborn/_stats diff --git a/testbed/mwaskom__seaborn/README.md b/testbed/mwaskom__seaborn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f642e553f108318fad2a360c4d37d8f63e4506d9 --- /dev/null +++ b/testbed/mwaskom__seaborn/README.md @@ -0,0 +1,70 @@ +
+ +-------------------------------------- + +seaborn: statistical data visualization +======================================= + +[![PyPI Version](https://img.shields.io/pypi/v/seaborn.svg)](https://pypi.org/project/seaborn/) +[![License](https://img.shields.io/pypi/l/seaborn.svg)](https://github.com/mwaskom/seaborn/blob/master/LICENSE) +[![DOI](https://joss.theoj.org/papers/10.21105/joss.03021/status.svg)](https://doi.org/10.21105/joss.03021) +[![Tests](https://github.com/mwaskom/seaborn/workflows/CI/badge.svg)](https://github.com/mwaskom/seaborn/actions) +[![Code Coverage](https://codecov.io/gh/mwaskom/seaborn/branch/master/graph/badge.svg)](https://codecov.io/gh/mwaskom/seaborn) + +Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics. + + +Documentation +------------- + +Online documentation is available at [seaborn.pydata.org](https://seaborn.pydata.org). + +The docs include a [tutorial](https://seaborn.pydata.org/tutorial.html), [example gallery](https://seaborn.pydata.org/examples/index.html), [API reference](https://seaborn.pydata.org/api.html), [FAQ](https://seaborn.pydata.org/faq), and other useful information. + +To build the documentation locally, please refer to [`doc/README.md`](doc/README.md). + +Dependencies +------------ + +Seaborn supports Python 3.8+. + +Installation requires [numpy](https://numpy.org/), [pandas](https://pandas.pydata.org/), and [matplotlib](https://matplotlib.org/). Some advanced statistical functionality requires [scipy](https://www.scipy.org/) and/or [statsmodels](https://www.statsmodels.org/). + + +Installation +------------ + +The latest stable release (and required dependencies) can be installed from PyPI: + + pip install seaborn + +It is also possible to include optional statistical dependencies: + + pip install seaborn[stats] + +Seaborn can also be installed with conda: + + conda install seaborn + +Note that the main anaconda repository lags PyPI in adding new releases, but conda-forge (`-c conda-forge`) typically updates quickly. + +Citing +------ + +A paper describing seaborn has been published in the [Journal of Open Source Software](https://joss.theoj.org/papers/10.21105/joss.03021). The paper provides an introduction to the key features of the library, and it can be used as a citation if seaborn proves integral to a scientific publication. + +Testing +------- + +Testing seaborn requires installing additional dependencies; they can be installed with the `dev` extra (e.g., `pip install .[dev]`). + +To test the code, run `make test` in the source directory. This will exercise the unit tests (using [pytest](https://docs.pytest.org/)) and generate a coverage report. + +Code style is enforced with `flake8` using the settings in the [`setup.cfg`](./setup.cfg) file. Run `make lint` to check. Alternately, you can use `pre-commit` to automatically run lint checks on any files you are committing: just run `pre-commit install` to set it up, and then commit as usual going forward. + +Development +----------- + +Seaborn development takes place on Github: https://github.com/mwaskom/seaborn + +Please submit bugs that you encounter to the [issue tracker](https://github.com/mwaskom/seaborn/issues) with a reproducible example demonstrating the problem. Questions about usage are more at home on StackOverflow, where there is a [seaborn tag](https://stackoverflow.com/questions/tagged/seaborn). diff --git a/testbed/mwaskom__seaborn/ci/cache_datasets.py b/testbed/mwaskom__seaborn/ci/cache_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf744416408ecfd4a92ec4dd030a106ef03c5b8 --- /dev/null +++ b/testbed/mwaskom__seaborn/ci/cache_datasets.py @@ -0,0 +1,27 @@ +""" +Cache test datasets before running tests / building docs. + +Avoids race conditions that would arise from parallelization. +""" +import pathlib +import re + +from seaborn import load_dataset + +path = pathlib.Path(".") +py_files = path.rglob("*.py") +ipynb_files = path.rglob("*.ipynb") + +datasets = [] + +for fname in py_files: + with open(fname) as fid: + datasets += re.findall(r"load_dataset\(['\"](\w+)['\"]", fid.read()) + +for p in ipynb_files: + with p.open() as fid: + datasets += re.findall(r"load_dataset\(\\['\"](\w+)\\['\"]", fid.read()) + +for name in sorted(set(datasets)): + print(f"Caching {name}") + load_dataset(name) diff --git a/testbed/mwaskom__seaborn/ci/check_gallery.py b/testbed/mwaskom__seaborn/ci/check_gallery.py new file mode 100644 index 0000000000000000000000000000000000000000..60db2e12c66936c51cb118100d0b904f7c1313a1 --- /dev/null +++ b/testbed/mwaskom__seaborn/ci/check_gallery.py @@ -0,0 +1,14 @@ +"""Execute the scripts that comprise the example gallery in the online docs.""" +from glob import glob +import matplotlib.pyplot as plt + +if __name__ == "__main__": + + fnames = sorted(glob("examples/*.py")) + + for fname in fnames: + + print(f"- {fname}") + with open(fname) as fid: + exec(fid.read()) + plt.close("all") diff --git a/testbed/mwaskom__seaborn/ci/deps_pinned.txt b/testbed/mwaskom__seaborn/ci/deps_pinned.txt new file mode 100644 index 0000000000000000000000000000000000000000..27a51b40431f49e855d38fc81f16d871fe20fe07 --- /dev/null +++ b/testbed/mwaskom__seaborn/ci/deps_pinned.txt @@ -0,0 +1,5 @@ +numpy~=1.20.0 +pandas~=1.2.0 +matplotlib~=3.3.0 +scipy~=1.7.0 +statsmodels~=0.12.0 diff --git a/testbed/mwaskom__seaborn/ci/getmsfonts.sh b/testbed/mwaskom__seaborn/ci/getmsfonts.sh new file mode 100644 index 0000000000000000000000000000000000000000..bb8feba027a31b29331d8846719037bde28d10d4 --- /dev/null +++ b/testbed/mwaskom__seaborn/ci/getmsfonts.sh @@ -0,0 +1,2 @@ +echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections +apt-get install msttcorefonts -qq diff --git a/testbed/mwaskom__seaborn/doc/.gitignore b/testbed/mwaskom__seaborn/doc/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a1d3570a82b4da5858817e87c77c34144ec0f3cb --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/.gitignore @@ -0,0 +1,9 @@ +*_files/ +_build/ +generated/ +examples/ +example_thumbs/*.png +docstrings/ +tutorial/ +tutorial/_images +tutorial.rst diff --git a/testbed/mwaskom__seaborn/doc/Makefile b/testbed/mwaskom__seaborn/doc/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..c9a433e4e951827bed13873f4b9f9bb7a0e9aa98 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/Makefile @@ -0,0 +1,173 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " clean to remove generated output" + @echo " html to make standalone HTML files" + @echo " notebooks to make the Jupyter notebook-based tutorials" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + -rm -rf examples/* + -rm -rf example_thumbs/* + -rm -rf generated/* + -rm -rf tutorial.rst + -$(MAKE) -C _docstrings clean + -$(MAKE) -C _tutorial clean + +.PHONY: tutorials +tutorials: + @mkdir -p tutorial + @$(MAKE) -C _tutorial + +.PHONY: docstrings +docstrings: + @mkdir -p docstrings + @$(MAKE) -C _docstrings + +notebooks: tutorials docstrings + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/lyman.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/lyman.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/lyman" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/lyman" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/testbed/mwaskom__seaborn/doc/README.md b/testbed/mwaskom__seaborn/doc/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78cfc1ef645b5ccbd82a5830a1dd298b1c1cb2d9 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/README.md @@ -0,0 +1,12 @@ +Building the seaborn docs +========================= + +Building the docs requires additional dependencies; they can be installed with `pip install seaborn[stats,docs]`. + +The build process involves conversion of Jupyter notebooks to `rst` files. To facilitate this, you may need to set `NB_KERNEL` environment variable to the name of a kernel on your machine (e.g. `export NB_KERNEL="python3"`). To get a list of available Python kernels, run `jupyter kernelspec list`. + +After you're set up, run `make notebooks html` from the `doc` directory to convert all notebooks, generate all gallery examples, and build the documentation itself. The site will live in `_build/html`. + +Run `make clean` to delete the built site and all intermediate files. Run `make -C docstrings clean` or `make -C tutorial clean` to remove intermediate files for the API or tutorial components. + +If your goal is to obtain an offline copy of the docs for a released version, it may be easier to clone the [website repository](https://github.com/seaborn/seaborn.github.io) or to download a zipfile corresponding to a [specific version](https://github.com/seaborn/seaborn.github.io/tags). diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/FacetGrid.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/FacetGrid.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..28af34c3c5672c1f38b8159f5126abeabd91e25c --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/FacetGrid.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"ticks\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Calling the constructor requires a long-form data object. This initializes the grid, but doesn't plot anything on it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.FacetGrid(tips)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assign column and/or row variables to add more subplots to the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.FacetGrid(tips, col=\"time\", row=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To draw a plot on every facet, pass a function and the name of one or more columns in the dataframe to :meth:`FacetGrid.map`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\", row=\"sex\")\n", + "g.map(sns.scatterplot, \"total_bill\", \"tip\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The variable specification in :meth:`FacetGrid.map` requires a positional argument mapping, but if the function has a ``data`` parameter and accepts named variable assignments, you can also use :meth:`FacetGrid.map_dataframe`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\", row=\"sex\")\n", + "g.map_dataframe(sns.histplot, x=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Notice how the bins have different widths in each facet. A separate plot is drawn on each facet, so if the plotting function derives any parameters from the data, they may not be shared across facets. You can pass additional keyword arguments to synchronize them. But when possible, using a figure-level function like :func:`displot` will take care of this bookkeeping for you:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\", row=\"sex\")\n", + "g.map_dataframe(sns.histplot, x=\"total_bill\", binwidth=2, binrange=(0, 60))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :class:`FacetGrid` constructor accepts a ``hue`` parameter. Setting this will condition the data on another variable and make multiple plots in different colors. Where possible, label information is tracked so that a single legend can be drawn:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\", hue=\"sex\")\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When ``hue`` is set on the :class:`FacetGrid`, however, a separate plot is drawn for each level of the variable. If the plotting function understands ``hue``, it is better to let it handle that logic. But it is important to ensure that each facet will use the same hue mapping. In the sample ``tips`` data, the ``sex`` column has a categorical datatype, which ensures this. Otherwise, you may want to use the `hue_order` or similar parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\")\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\", hue=\"sex\")\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The size and shape of the plot is specified at the level of each subplot using the ``height`` and ``aspect`` parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"day\", height=3.5, aspect=.65)\n", + "g.map(sns.histplot, \"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If the variable assigned to ``col`` has many levels, it is possible to \"wrap\" it so that it spans multiple rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"size\", height=2.5, col_wrap=3)\n", + "g.map(sns.histplot, \"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To add horizontal or vertical reference lines on every facet, use :meth:`FacetGrid.refline`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\", margin_titles=True)\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n", + "g.refline(y=tips[\"tip\"].median())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can pass custom functions to plot with, or to annotate each facet. Your custom function must use the matplotlib state-machine interface to plot on the \"current\" axes, and it should catch additional keyword arguments:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "def annotate(data, **kws):\n", + " n = len(data)\n", + " ax = plt.gca()\n", + " ax.text(.1, .6, f\"N = {n}\", transform=ax.transAxes)\n", + "\n", + "g = sns.FacetGrid(tips, col=\"time\")\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n", + "g.map_dataframe(annotate)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :class:`FacetGrid` object has some other useful parameters and methods for tweaking the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"sex\", row=\"time\", margin_titles=True)\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n", + "g.set_axis_labels(\"Total bill ($)\", \"Tip ($)\")\n", + "g.set_titles(col_template=\"{col_name} patrons\", row_template=\"{row_name}\")\n", + "g.set(xlim=(0, 60), ylim=(0, 12), xticks=[10, 30, 50], yticks=[2, 6, 10])\n", + "g.tight_layout()\n", + "g.savefig(\"facet_plot.png\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import os\n", + "if os.path.exists(\"facet_plot.png\"):\n", + " os.remove(\"facet_plot.png\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You also have access to the underlying matplotlib objects for additional tweaking:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"sex\", row=\"time\", margin_titles=True, despine=False)\n", + "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n", + "g.figure.subplots_adjust(wspace=0, hspace=0)\n", + "for (row_val, col_val), ax in g.axes_dict.items():\n", + " if row_val == \"Lunch\" and col_val == \"Female\":\n", + " ax.set_facecolor(\".95\")\n", + " else:\n", + " ax.set_facecolor((0, 0, 0, 0))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/JointGrid.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/JointGrid.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..272bf3c3e7a58550423c22af4b398c27a579246c --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/JointGrid.ipynb @@ -0,0 +1,244 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Calling the constructor initializes the figure, but it does not plot anything:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The simplest plotting method, :meth:`JointGrid.plot` accepts a pair of functions (one for the joint axes and one for both marginal axes):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot(sns.scatterplot, sns.histplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :meth:`JointGrid.plot` function also accepts additional keyword arguments, but it passes them to both functions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot(sns.scatterplot, sns.histplot, alpha=.7, edgecolor=\".2\", linewidth=.5)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If you need to pass different keyword arguments to each function, you'll have to invoke :meth:`JointGrid.plot_joint` and :meth:`JointGrid.plot_marginals`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot_joint(sns.scatterplot, s=100, alpha=.5)\n", + "g.plot_marginals(sns.histplot, kde=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can also set up the grid without assigning any data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can then plot by accessing the ``ax_joint``, ``ax_marg_x``, and ``ax_marg_y`` attributes, which are :class:`matplotlib.axes.Axes` objects:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid()\n", + "x, y = penguins[\"bill_length_mm\"], penguins[\"bill_depth_mm\"]\n", + "sns.scatterplot(x=x, y=y, ec=\"b\", fc=\"none\", s=100, linewidth=1.5, ax=g.ax_joint)\n", + "sns.histplot(x=x, fill=False, linewidth=2, ax=g.ax_marg_x)\n", + "sns.kdeplot(y=y, linewidth=2, ax=g.ax_marg_y)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The plotting methods can use any seaborn functions that accept ``x`` and ``y`` variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot(sns.regplot, sns.boxplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If the functions accept a ``hue`` variable, you can use it by assigning ``hue`` when you call the constructor:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\")\n", + "g.plot(sns.scatterplot, sns.histplot)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Horizontal and/or vertical reference lines can be added to the joint and/or marginal axes using :meth:`JointGrid.refline`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot(sns.scatterplot, sns.histplot)\n", + "g.refline(x=45, y=16)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The figure will always be square (unless you resize it at the matplotlib layer), but its overall size and layout are configurable. The size is controlled by the ``height`` parameter. The relative ratio between the joint and marginal axes is controlled by ``ratio``, and the amount of space between the plots is controlled by ``space``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.JointGrid(height=4, ratio=2, space=.05)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the ticks on the density axis of the marginal plots are turned off, but this is configurable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.JointGrid(marginal_ticks=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Limits on the two data axes (which are shared across plots) can also be defined when setting up the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.JointGrid(xlim=(-2, 5), ylim=(0, 10))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/Makefile b/testbed/mwaskom__seaborn/doc/_docstrings/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..11657fef0e5ef14c04ef5cb6957194ed6f1672f5 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/Makefile @@ -0,0 +1,14 @@ +rst_files := $(patsubst %.ipynb,../docstrings/%.rst,$(wildcard *.ipynb)) +export MPLBACKEND := module://matplotlib_inline.backend_inline + +docstrings: ${rst_files} + +../docstrings/%.rst: %.ipynb + ../tools/nb_to_doc.py $*.ipynb ../docstrings + @cp -r ../docstrings/$*_files ../generated/ + @if [ -f ../generated/seaborn.$*.rst ]; then \ + touch ../generated/seaborn.$*.rst; \ + fi + +clean: + rm -rf ../docstrings diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/PairGrid.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/PairGrid.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1a9c897c0d7f440c705a3b4f2c334bbb1857f1c0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/PairGrid.ipynb @@ -0,0 +1,271 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns; sns.set_theme()\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Calling the constructor sets up a blank grid of subplots with each row and one column corresponding to a numeric variable in the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "g = sns.PairGrid(penguins)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Passing a bivariate function to :meth:`PairGrid.map` will draw a bivariate plot on every axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins)\n", + "g.map(sns.scatterplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Passing separate functions to :meth:`PairGrid.map_diag` and :meth:`PairGrid.map_offdiag` will show each variable's marginal distribution on the diagonal:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins)\n", + "g.map_diag(sns.histplot)\n", + "g.map_offdiag(sns.scatterplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to use different functions on the upper and lower triangles of the plot (which are otherwise redundant):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, diag_sharey=False)\n", + "g.map_upper(sns.scatterplot)\n", + "g.map_lower(sns.kdeplot)\n", + "g.map_diag(sns.kdeplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or to avoid the redundancy altogether:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, diag_sharey=False, corner=True)\n", + "g.map_lower(sns.scatterplot)\n", + "g.map_diag(sns.kdeplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :class:`PairGrid` constructor accepts a ``hue`` variable. This variable is passed directly to functions that understand it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"species\")\n", + "g.map_diag(sns.histplot)\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "But you can also pass matplotlib functions, in which case a groupby is performed internally and a separate plot is drawn for each level:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"species\")\n", + "g.map_diag(plt.hist)\n", + "g.map_offdiag(plt.scatter)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Additional semantic variables can be assigned by passing data vectors directly while mapping the function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"species\")\n", + "g.map_diag(sns.histplot)\n", + "g.map_offdiag(sns.scatterplot, size=penguins[\"sex\"])\n", + "g.add_legend(title=\"\", adjust_subtitles=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When using seaborn functions that can implement a numeric hue mapping, you will want to disable mapping of the variable on the diagonal axes. Note that the ``hue`` variable is excluded from the list of variables shown by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"body_mass_g\")\n", + "g.map_diag(sns.histplot, hue=None, color=\".3\")\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``vars`` parameter can be used to control exactly which variables are used:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "variables = [\"body_mass_g\", \"bill_length_mm\", \"flipper_length_mm\"]\n", + "g = sns.PairGrid(penguins, hue=\"body_mass_g\", vars=variables)\n", + "g.map_diag(sns.histplot, hue=None, color=\".3\")\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The plot need not be square: separate variables can be used to define the rows and columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x_vars = [\"body_mass_g\", \"bill_length_mm\", \"bill_depth_mm\", \"flipper_length_mm\"]\n", + "y_vars = [\"body_mass_g\"]\n", + "g = sns.PairGrid(penguins, hue=\"species\", x_vars=x_vars, y_vars=y_vars)\n", + "g.map_diag(sns.histplot, color=\".3\")\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It can be useful to explore different approaches to resolving multiple distributions on the diagonal axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"species\")\n", + "g.map_diag(sns.histplot, multiple=\"stack\", element=\"step\")\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/axes_style.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/axes_style.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ba9aa599aea1813cdd40ac64371ff0dbeafef8d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/axes_style.ipynb @@ -0,0 +1,102 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "dated-mother", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns" + ] + }, + { + "cell_type": "markdown", + "id": "prospective-sellers", + "metadata": {}, + "source": [ + "Calling with no arguments will return the current defaults for the style parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "recognized-rehabilitation", + "metadata": { + "tags": [ + "show-output" + ] + }, + "outputs": [], + "source": [ + "sns.axes_style()" + ] + }, + { + "cell_type": "markdown", + "id": "furnished-irrigation", + "metadata": {}, + "source": [ + "Calling with the name of a predefined style will show those parameter values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "coordinate-reward", + "metadata": { + "tags": [ + "show-output" + ] + }, + "outputs": [], + "source": [ + "sns.axes_style(\"darkgrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "mediterranean-picking", + "metadata": {}, + "source": [ + "Use the function as a context manager to temporarily change the style of your plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "missing-essence", + "metadata": {}, + "outputs": [], + "source": [ + "with sns.axes_style(\"whitegrid\"):\n", + " sns.barplot(x=[1, 2, 3], y=[2, 5, 3])" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/barplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/barplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6a7fa92f682ab37691bbfb48e69d03691bf48d78 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/barplot.ipynb @@ -0,0 +1,125 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "6a6d582b-08c2-4fed-be56-afa1b986943a", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "a7ef20b6-3bd8-4992-a270-4c3ecc86a0fa", + "metadata": {}, + "source": [ + "Group by a categorical varaible and plot aggregated values, with confidence intervals:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f5c3ece-6295-4933-8a87-e80cd604c089", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"penguins\")\n", + "sns.barplot(data=df, x=\"island\", y=\"body_mass_g\")" + ] + }, + { + "cell_type": "markdown", + "id": "38f7c39e-485d-4b50-ac21-f1b402f26aa4", + "metadata": {}, + "source": [ + "Add a second layer of grouping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac1a28d1-b3bd-4158-86d0-3defc12f8566", + "metadata": {}, + "outputs": [], + "source": [ + "sns.barplot(data=df, x=\"island\", y=\"body_mass_g\", hue=\"sex\")" + ] + }, + { + "cell_type": "markdown", + "id": "7f8fa070-a8f4-41fb-be74-c489acbdbcbe", + "metadata": {}, + "source": [ + "Use the error bars to show the standard deviation rather than a confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10445b78-a74a-4f14-a28b-a9164e592ae4", + "metadata": {}, + "outputs": [], + "source": [ + "sns.barplot(data=df, x=\"island\", y=\"body_mass_g\", errorbar=\"sd\")" + ] + }, + { + "cell_type": "markdown", + "id": "7f579f70-39a2-4d0c-baa2-9adae11ce2ce", + "metadata": {}, + "source": [ + "Customize the appearance of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6f9ac1c-a77d-4ee3-bc5e-fec2071b33df", + "metadata": {}, + "outputs": [], + "source": [ + "sns.barplot(\n", + " data=df, x=\"body_mass_g\", y=\"island\",\n", + " errorbar=(\"pi\", 50), capsize=.4, errcolor=\".5\",\n", + " linewidth=3, edgecolor=\".5\", facecolor=(0, 0, 0, 0),\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "faedd6f9-a123-4927-9eff-a2046edf5c72", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/blend_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/blend_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..302f93e96bf20e8d9a0d11a16ea2c9de9173c619 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/blend_palette.ipynb @@ -0,0 +1,103 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "8f97280e-cec8-42b2-a968-4fd4364594f8", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "972edede-df1a-4010-9674-00b864d020e2", + "metadata": {}, + "source": [ + "Pass a list of two colors to interpolate between them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e6ae2547-1042-4ac0-84ea-6f37a0229871", + "metadata": {}, + "outputs": [], + "source": [ + "sns.blend_palette([\"b\", \"r\"])" + ] + }, + { + "cell_type": "raw", + "id": "1d983eac-2dd5-4746-b27f-4dfa19b5e091", + "metadata": {}, + "source": [ + "The color list can be arbitrarily long, and any color format can be used:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "846b78fd-30ce-4507-93f4-4274122c1987", + "metadata": {}, + "outputs": [], + "source": [ + "sns.blend_palette([\"#45a872\", \".8\", \"xkcd:golden\"])" + ] + }, + { + "cell_type": "raw", + "id": "318fef32-1f83-44d9-9ff9-21fa0231b7c6", + "metadata": {}, + "source": [ + "Return a continuous colormap instead of a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0a05bc3-c60b-47a1-b276-d2e28a4a8226", + "metadata": {}, + "outputs": [], + "source": [ + "sns.blend_palette([\"#bdc\", \"#7b9\", \"#47a\"], as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0473a402-0ec2-4877-81d2-ed6c57aefc77", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/boxenplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/boxenplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b61e2d5630c6947f79ac5e867f3f32f3301c69cb --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/boxenplot.ipynb @@ -0,0 +1,130 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "882d215b-88d8-4b5e-ae7a-0e3f6bb53bad", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6809326c-14a9-4314-994d-b4e8e7414172", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "markdown", + "id": "9ccbc2d5-5a44-4e80-8b07-e12629729f4a", + "metadata": {}, + "source": [ + "Draw a single horizontal plot, assigning the data directly to the coordinate variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "391e1162-b438-4486-9a08-60686ee8e96a", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxenplot(x=df[\"price\"])" + ] + }, + { + "cell_type": "markdown", + "id": "a3b0e9b8-1673-494c-a27a-aa9c60457ba1", + "metadata": {}, + "source": [ + "Group by a categorical variable, referencing columns in a datafame" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e30fec18-f127-40a3-bfaf-f71324dd60ec", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxenplot(data=df, x=\"price\", y=\"clarity\")" + ] + }, + { + "cell_type": "markdown", + "id": "4f01a821-74d1-452d-a1f7-cf5b806169e8", + "metadata": {}, + "source": [ + "Use a different scaling rule to control the width of each box:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0c1aa43-5e8a-486c-bd6d-3c29d6d23138", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxenplot(data=df, x=\"carat\", y=\"cut\", scale=\"linear\")" + ] + }, + { + "cell_type": "markdown", + "id": "fd5d197c-8cbb-4be3-a14d-76447f06d3f1", + "metadata": {}, + "source": [ + "Use a different method to determine the number of boxes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1aead6a3-6f12-47d3-b472-a39c61867963", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxenplot(data=df, x=\"carat\", y=\"cut\", k_depth=\"trustworthy\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "719fd61f-9795-47d6-96bd-4929d8647038", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/boxplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/boxplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5935f44c157fc4202f64ae6384d418c351631384 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/boxplot.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "7edcf92f-6c11-4dc4-b684-118b3235d067", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "90798548-e999-4127-8191-ce01e252f305", + "metadata": {}, + "source": [ + "Draw a single horizontal boxplot, assigning the data directly to the coordinate variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "80532f2c-0f34-456c-9d5c-673682385461", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"titanic\")\n", + "sns.boxplot(x=df[\"age\"])" + ] + }, + { + "cell_type": "markdown", + "id": "98e6f351-2983-4edc-93e6-03b2d91ed5f1", + "metadata": {}, + "source": [ + "Group by a categorical variable, referencing columns in a dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1e0a6a4-151d-42d7-a098-ec9b91f20906", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(data=df, x=\"age\", y=\"class\")" + ] + }, + { + "cell_type": "markdown", + "id": "a4bebd98-9719-4279-b0b5-700ca0aa087d", + "metadata": {}, + "source": [ + "Draw a vertical boxplot with nested grouping by two variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b8f74dc4-2b59-423a-90a7-dbf900c89251", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(data=df, x=\"age\", y=\"class\", hue=\"alive\")" + ] + }, + { + "cell_type": "markdown", + "id": "8b4a7418-d945-4ec6-90d2-8ec10c552a08", + "metadata": {}, + "source": [ + "Control the order of the boxes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2a496593-7c12-4739-b3db-46b777599c65", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(data=df, x=\"fare\", y=\"alive\", order=[\"yes\", \"no\"])" + ] + }, + { + "cell_type": "markdown", + "id": "4a5b57c0-7835-49c0-b899-012d3b112efc", + "metadata": {}, + "source": [ + "Draw a box for multiple numeric columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a4ca0f44-be47-4014-9ac5-01c9b47c5bdc", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(data=df[[\"age\", \"fare\"]], orient=\"h\")" + ] + }, + { + "cell_type": "markdown", + "id": "d0e68414-2f63-442f-9d2e-24fc9ab1f5e3", + "metadata": {}, + "source": [ + "Use a `hue` variable whithout changing the box width or position:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c242ee2b-22af-47f7-8de6-84e5ff95271f", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(data=df, x=\"fare\", y=\"deck\", hue=\"deck\", dodge=False)" + ] + }, + { + "cell_type": "markdown", + "id": "5dca0faa-96ec-4e64-a187-482a9d10a03b", + "metadata": {}, + "source": [ + "Pass additional keyword arguments to matplotlib:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66c81b6e-e7fb-46c5-aa7b-f001241569b0", + "metadata": {}, + "outputs": [], + "source": [ + "sns.boxplot(\n", + " data=df, x=\"age\", y=\"class\",\n", + " notch=True, showcaps=False,\n", + " flierprops={\"marker\": \"x\"},\n", + " boxprops={\"facecolor\": (.4, .6, .8, .5)},\n", + " medianprops={\"color\": \"coral\"},\n", + ")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/catplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/catplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6e3ee7d06bec36128507c69efdc3204786e1156f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/catplot.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "a8aa6a6a-f6c0-4a6b-9460-2056e58a2e13", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "raw", + "id": "1aef2740-ae6e-4a1b-a588-3ad978e2614d", + "metadata": {}, + "source": [ + "By default, the visual representation will be a jittered strip plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75a49e26-4318-4963-897c-dc0081aebfb3", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"titanic\")\n", + "sns.catplot(data=df, x=\"age\", y=\"class\")" + ] + }, + { + "cell_type": "markdown", + "id": "db1b8f6d-5264-4200-b81a-b0ee64040a1f", + "metadata": {}, + "source": [ + "Use `kind` to select a different representation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75ecd034-8536-4fe4-8852-a3975dba64dc", + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=df, x=\"age\", y=\"class\", kind=\"box\")" + ] + }, + { + "cell_type": "markdown", + "id": "8aee79a9-b8b3-4129-b6d7-e9e32ae1e634", + "metadata": {}, + "source": [ + "One advantage is that the legend will be automatically placed outside the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3798aac6-1ff6-4e36-ad83-4742fcb04159", + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=df, x=\"age\", y=\"class\", hue=\"sex\", kind=\"boxen\")" + ] + }, + { + "cell_type": "markdown", + "id": "8a3777e1-90b6-4f4d-9e14-247b6dfd64fe", + "metadata": {}, + "source": [ + "Additional keyword arguments get passed through to the underlying seaborn function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "afcff2fe-db11-4602-af79-68e4a0380f88", + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=df, x=\"age\", y=\"class\", hue=\"sex\",\n", + " kind=\"violin\", bw=.25, cut=0, split=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "a75bf46f-a3d0-4a5d-abcd-b9e85def65b0", + "metadata": {}, + "source": [ + "Assigning a variable to `col` or `row` will automatically create subplots. Control figure size with the `height` and `aspect` parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "835afcf2-ecc9-4edb-9ec8-24484c5b08fb", + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=df, x=\"class\", y=\"survived\", col=\"sex\",\n", + " kind=\"bar\", height=4, aspect=.6,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "ecf323fe-1e86-47ff-aa50-e8c297cfa125", + "metadata": {}, + "source": [ + "For single-subplot figures, it is easy to layer different representations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dc5b0fc0-359c-4219-b04e-171d8c7c8051", + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=df, x=\"age\", y=\"class\", kind=\"violin\", color=\".9\", inner=None)\n", + "sns.swarmplot(data=df, x=\"age\", y=\"class\", size=3)" + ] + }, + { + "cell_type": "raw", + "id": "26e06ba4-0457-4597-b699-cb0fe8b2be32", + "metadata": {}, + "source": [ + "Use methods on the returned :class:`FacetGrid` to tweak the presentation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a43f1914-d868-4060-82df-b3d25553d595", + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.catplot(\n", + " data=df, x=\"who\", y=\"survived\", col=\"class\",\n", + " kind=\"bar\", height=4, aspect=.6,\n", + ")\n", + "g.set_axis_labels(\"\", \"Survival Rate\")\n", + "g.set_xticklabels([\"Men\", \"Women\", \"Children\"])\n", + "g.set_titles(\"{col_name} {col_var}\")\n", + "g.set(ylim=(0, 1))\n", + "g.despine(left=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a529c18c-45bc-4efb-8ae0-c14518349162", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/clustermap.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/clustermap.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..487cec7646a38797ff03f468531958e66047d5b2 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/clustermap.ipynb @@ -0,0 +1,184 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "ffc1e1d9-fa74-4121-aa87-e1a8665e4c2b", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "id": "41b4f602-32af-44f8-bf1a-0f1695c9abbb", + "metadata": {}, + "source": [ + "Plot a heatmap with row and column clustering:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c715bd8f-cf5d-4caa-9244-336b3d0248a8", + "metadata": {}, + "outputs": [], + "source": [ + "iris = sns.load_dataset(\"iris\")\n", + "species = iris.pop(\"species\")\n", + "sns.clustermap(iris)" + ] + }, + { + "cell_type": "raw", + "id": "1cc3134c-579a-442a-97d8-a878651ce90a", + "metadata": {}, + "source": [ + "Change the size and layout of the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd33cf4b-9589-4b9a-a246-0b95bad28c51", + "metadata": {}, + "outputs": [], + "source": [ + "sns.clustermap(\n", + " iris,\n", + " figsize=(7, 5),\n", + " row_cluster=False,\n", + " dendrogram_ratio=(.1, .2),\n", + " cbar_pos=(0, .2, .03, .4)\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "c5d3408d-f5d6-4045-9d61-15573a981587", + "metadata": {}, + "source": [ + "Add colored labels to identify observations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "79d3fe52-6146-4f33-a39a-1d4a47243ea5", + "metadata": {}, + "outputs": [], + "source": [ + "lut = dict(zip(species.unique(), \"rbg\"))\n", + "row_colors = species.map(lut)\n", + "sns.clustermap(iris, row_colors=row_colors)" + ] + }, + { + "cell_type": "raw", + "id": "f2f944e2-36cd-4653-86b4-6d2affec13d6", + "metadata": {}, + "source": [ + "Use a different colormap and adjust the limits of the color range:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6137c7ad-db92-47b8-9d00-3228c4e1f7df", + "metadata": {}, + "outputs": [], + "source": [ + "sns.clustermap(iris, cmap=\"mako\", vmin=0, vmax=10)" + ] + }, + { + "cell_type": "raw", + "id": "93f96d1c-9d04-464f-93c9-4319caa8504a", + "metadata": {}, + "source": [ + "Use differente clustering parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9e76bde-a222-4eca-971f-54f56ad53281", + "metadata": {}, + "outputs": [], + "source": [ + "sns.clustermap(iris, metric=\"correlation\", method=\"single\")" + ] + }, + { + "cell_type": "raw", + "id": "ea6ed3fd-188d-4244-adac-ec0169c02205", + "metadata": {}, + "source": [ + "Standardize the data within the columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5f744c4-b959-4ed1-b2cf-6046c9214568", + "metadata": {}, + "outputs": [], + "source": [ + "sns.clustermap(iris, standard_scale=1)" + ] + }, + { + "cell_type": "raw", + "id": "7ca72242-4eb0-4f8e-b0c0-d1ef7166b738", + "metadata": {}, + "source": [ + "Normalize the data within rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "33815c4c-9bae-4226-bd11-3dfdb7ecab2b", + "metadata": {}, + "outputs": [], + "source": [ + "sns.clustermap(iris, z_score=0, cmap=\"vlag\", center=0)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f37d57a-b049-4665-9c24-4d5fbbca00ba", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/color_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/color_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b896c7b74380b6b6b49bbaf79636686f79885fca --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/color_palette.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Calling with no arguments returns all colors from the current default\n", + "color cycle:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Other variants on the seaborn categorical color palette can be referenced by name:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"pastel\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a specified number of evenly spaced hues in the \"HUSL\" system:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"husl\", 9)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return all unique colors in a categorical Color Brewer palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Set2\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a diverging Color Brewer palette as a continuous colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Spectral\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return one of the perceptually-uniform palettes included in seaborn as a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"flare\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return one of the perceptually-uniform palettes included in seaborn as a continuous colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"flare\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a customized cubehelix color palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"ch:s=.25,rot=-.25\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a light sequential gradient:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"light:#5A9\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a reversed dark sequential gradient:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"dark:#5A9_r\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Return a blend gradient between two endpoints:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"blend:#7AB,#EDA\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use as a context manager to change the default qualitative color palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "x, y = list(range(10)), [0] * 10\n", + "hue = list(map(str, x))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with sns.color_palette(\"Set3\"):\n", + " sns.relplot(x=x, y=y, hue=hue, s=500, legend=False, height=1.3, aspect=4)\n", + "\n", + "sns.relplot(x=x, y=y, hue=hue, s=500, legend=False, height=1.3, aspect=4)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "See the underlying color values as hex codes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "show-output" + ] + }, + "outputs": [], + "source": [ + "print(sns.color_palette(\"pastel6\").as_hex())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/countplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/countplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..38b122b020d95ea1ba23faea93bed664a004f488 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/countplot.ipynb @@ -0,0 +1,99 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2fdf0f63-d515-4cb8-b3e0-62cac7852b12", + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "5adcc785-6643-4c55-ba38-ac9b65857932", + "metadata": {}, + "source": [ + "Show the number of datapoints with each value of a categorical variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e9d0485-870d-4841-9c84-6e0bacbde7db", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"titanic\")\n", + "sns.countplot(x=df[\"class\"])" + ] + }, + { + "cell_type": "markdown", + "id": "c2e36b42-5453-4478-918b-3699ac1fbc0e", + "metadata": {}, + "source": [ + "Group by a second variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "26f73c00-a2b3-45c3-b3cd-2babe0a81894", + "metadata": {}, + "outputs": [], + "source": [ + "sns.countplot(data=df, x=\"class\", hue=\"alive\")" + ] + }, + { + "cell_type": "markdown", + "id": "eac30be1-c9d8-472c-afa9-16119afab86e", + "metadata": {}, + "source": [ + "Plot horizontally to make more space for category labels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "31758c56-106e-4a9c-bcee-ef1f93f472e8", + "metadata": {}, + "outputs": [], + "source": [ + "sns.countplot(data=df, y=\"deck\", hue=\"alive\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5c049d0c-d91b-4675-a9aa-7deea1421d68", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/cubehelix_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/cubehelix_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a996b05864e40c14a8362a43538daea1b7b324cf --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/cubehelix_palette.ipynb @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "60aebc68-2c7c-4af5-a159-8421e1f94ba6", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "242b3d42-1f10-4da2-9ef9-af06f7fbd724", + "metadata": {}, + "source": [ + "Return a discrete palette with default parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6526accb-9930-4e39-9f58-1ca2941c1c9d", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette()" + ] + }, + { + "cell_type": "raw", + "id": "887a40f0-d949-41fa-9a43-0ee246c9a077", + "metadata": {}, + "source": [ + "Increase the number of colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "02833290-b1ee-46df-a2a0-8268fba94628", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(8)" + ] + }, + { + "cell_type": "raw", + "id": "a9eb86c7-f92e-4422-ae62-a2ef136e7e35", + "metadata": {}, + "source": [ + "Return a continuous colormap rather than a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a460efc2-cf0a-46bf-a12f-12870afce8a5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "id": "5b84aa6c-ad79-45b1-a7d2-44b7ecba5f7d", + "metadata": {}, + "source": [ + "Change the starting point of the helix:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "70ee079a-e760-4d43-8447-648fd236ab15", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(start=2)" + ] + }, + { + "cell_type": "raw", + "id": "5e21fa22-9ac3-4354-8694-967f2447b286", + "metadata": {}, + "source": [ + "Change the amount of rotation in the helix:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ddb1b8c7-8933-4317-827f-4f10d2b4cecc", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(rot=.2)" + ] + }, + { + "cell_type": "raw", + "id": "fa91aff7-54e7-4754-a13c-b629dfc33e8f", + "metadata": {}, + "source": [ + "Rotate in the reverse direction:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "548a3942-48ae-40d2-abb7-acc2ffd71601", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(rot=-.2)" + ] + }, + { + "cell_type": "raw", + "id": "e7188a1b-183f-4b04-93a0-975c27fe408e", + "metadata": {}, + "source": [ + "Apply a nonlinearity to the luminance ramp:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ced54ff-a396-451e-b17f-2366b56f920b", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(gamma=.5)" + ] + }, + { + "cell_type": "raw", + "id": "bc82ce48-2df3-464e-b70e-a1d73d0432c6", + "metadata": {}, + "source": [ + "Increase the saturation of the colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a38b91a8-3fdc-4293-a3ea-71b4006cd2a1", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(hue=1)" + ] + }, + { + "cell_type": "raw", + "id": "f8d23ba1-013a-489f-94c4-f2080bfdae87", + "metadata": {}, + "source": [ + "Change the luminance at the start and end points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a4f05a16-18f0-4c14-99a4-57a0734aad02", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(dark=.25, light=.75)" + ] + }, + { + "cell_type": "raw", + "id": "0bfcc5d9-05ba-4715-94ac-8d430d9416c2", + "metadata": {}, + "source": [ + "Reverse the direction of the luminance ramp:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74563491-5448-42c3-86c5-f5d55ce6924c", + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(reverse=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94a83211-8b8e-4e60-8365-9600e71ddc5d", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/dark_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/dark_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..143ce93f4ebd005f71c678f0045a513c7a2950cf --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/dark_palette.ipynb @@ -0,0 +1,139 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "5cd1cbb8-ba1a-460b-8e3a-bc285867f1d1", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "b157eb25-015f-4dd6-9785-83ba19cf4f94", + "metadata": {}, + "source": [ + "Define a sequential ramp from a dark gray to a specified color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5b655d28-9855-4528-8b8e-a6c50288fd1b", + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette(\"seagreen\")" + ] + }, + { + "cell_type": "raw", + "id": "50053b26-112a-4378-8ef0-9be0fb565ec7", + "metadata": {}, + "source": [ + "Specify the color with a hex code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74ae0d17-f65b-4bcf-ae66-d97d46964d5c", + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette(\"#79C\")" + ] + }, + { + "cell_type": "raw", + "id": "eea376a2-fdf5-40e4-a187-3a28af529072", + "metadata": {}, + "source": [ + "Specify the color from the husl system:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66e451ee-869a-41ea-8dc5-4240b11e7be5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette((20, 60, 50), input=\"husl\")" + ] + }, + { + "cell_type": "raw", + "id": "e4f44dcd-cf49-4920-ac05-b4db67870363", + "metadata": {}, + "source": [ + "Increase the number of colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75985f07-de92-4d8b-89d5-caf445b9375e", + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette(\"xkcd:golden\", 8)" + ] + }, + { + "cell_type": "raw", + "id": "34687ae8-fd6d-427a-a639-208f19e61122", + "metadata": {}, + "source": [ + "Return a continuous colormap rather than a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c342db4-7f97-40f5-934e-9a82201890d1", + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette(\"#b285bc\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e7ebe64b-25fa-4c52-9ebe-fdcbba0ee51e", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/displot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/displot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9a4ae10cae6fba5e0bd6161b4ef09a5540206a80 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/displot.ipynb @@ -0,0 +1,239 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns; sns.set_theme(style=\"ticks\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The default plot kind is a histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.displot(data=penguins, x=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use the ``kind`` parameter to select a different representation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", kind=\"kde\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are three main plot kinds; in addition to histograms and kernel density estimates (KDEs), you can also draw empirical cumulative distribution functions (ECDFs):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", kind=\"ecdf\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "While in histogram mode, it is also possible to add a KDE curve:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", kde=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To draw a bivariate plot, assign both ``x`` and ``y``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Currently, bivariate plots are available only for histograms and KDEs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", kind=\"kde\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For each kind of plot, you can also show individual observations with a marginal \"rug\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.displot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", kind=\"kde\", rug=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Each kind of plot can be drawn separately for subsets of data using ``hue`` mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", kind=\"kde\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Additional keyword arguments are passed to the appropriate underlying plotting function, allowing for further customization:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The figure is constructed using a :class:`FacetGrid`, meaning that you can also show subsets on distinct subplots, or \"facets\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", col=\"sex\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Because the figure is drawn with a :class:`FacetGrid`, you control its size and shape with the ``height`` and ``aspect`` parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(\n", + " data=penguins, y=\"flipper_length_mm\", hue=\"sex\", col=\"species\",\n", + " kind=\"ecdf\", height=4, aspect=.7,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The function returns the :class:`FacetGrid` object with the plot, and you can use the methods on this object to customize it further:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.displot(\n", + " data=penguins, y=\"flipper_length_mm\", hue=\"sex\", col=\"species\",\n", + " kind=\"kde\", height=4, aspect=.7,\n", + ")\n", + "g.set_axis_labels(\"Density (a.u.)\", \"Flipper length (mm)\")\n", + "g.set_titles(\"{col_name} penguins\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/diverging_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/diverging_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ea2ad798bf43e649dd2fdf0813dd0156f912cbfb --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/diverging_palette.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "01295cb6-cc7a-4c6d-94cf-9b0e6cde9fa7", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "84880848-0805-4c41-999a-50808b397275", + "metadata": {}, + "source": [ + "Generate diverging ramps from blue to red through white:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "643b3e07-8365-46e3-b033-af7a2fdcd158", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(240, 20)" + ] + }, + { + "cell_type": "raw", + "id": "5ae53941-d9d9-4b5a-8abc-173911ebee74", + "metadata": {}, + "source": [ + "Change the center color to be dark:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "41f03771-8fb2-46f6-93c5-5a0e28be625c", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(240, 20, center=\"dark\")" + ] + }, + { + "cell_type": "raw", + "id": "0aeb2402-2cbe-4546-a354-f1f501f762ae", + "metadata": {}, + "source": [ + "Return a continuous colormap rather than a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "64d335a5-f8b2-433f-a83f-5aeff7db583a", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(240, 20, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "id": "77223a07-8492-4056-a0f7-14e133e3ce2c", + "metadata": {}, + "source": [ + "Increase the amount of separation around the center value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "82472c1e-4b16-40eb-be1d-480bbd2aa702", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(240, 20, sep=30, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "id": "966e8594-b458-414c-a7b0-3e804ce407bf", + "metadata": {}, + "source": [ + "Use a magenta-to-green palette instead:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a03f8ede-b424-4e06-beb6-cf63c94bcd9e", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(280, 150)" + ] + }, + { + "cell_type": "raw", + "id": "b3b17689-58e2-4065-9d52-1cf5ebcd4e89", + "metadata": {}, + "source": [ + "Decrease the saturation of the endpoints:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "02aaa009-f257-4fc7-a2de-40fbb1464490", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(280, 150, s=50)" + ] + }, + { + "cell_type": "raw", + "id": "db75ca48-ba72-4ca2-8480-bc72c20a70cc", + "metadata": {}, + "source": [ + "Decrease the lightness of the endpoints:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89e3bcb1-a17c-4465-830f-46043cb6c322", + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(280, 150, l=35)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e42452a-a485-43e7-bbc3-338db58e4637", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e19f523f-c2f7-489a-ba00-326810e31a67", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/ecdfplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/ecdfplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ddf95cfc08471f73f8e2b9f092099f8c257543e --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/ecdfplot.ipynb @@ -0,0 +1,142 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a univariate distribution along the x axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns; sns.set_theme()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.ecdfplot(data=penguins, x=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Flip the plot by assigning the data variable to the y axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.ecdfplot(data=penguins, y=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If neither `x` nor `y` is assigned, the dataset is treated as wide-form, and a histogram is drawn for each numeric column:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.ecdfplot(data=penguins.filter(like=\"bill_\", axis=\"columns\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also draw multiple histograms from a long-form dataset with hue mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.ecdfplot(data=penguins, x=\"bill_length_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default distribution statistic is normalized to show a proportion, but you can show absolute counts instead:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.ecdfplot(data=penguins, x=\"bill_length_mm\", hue=\"species\", stat=\"count\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's also possible to plot the empirical complementary CDF (1 - CDF):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.ecdfplot(data=penguins, x=\"bill_length_mm\", hue=\"species\", complementary=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/heatmap.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/heatmap.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ce5c90786ca62d6a465c37804b08b12d495713bf --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/heatmap.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "987b9549-532e-4091-a6cf-007d1b23e825", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "id": "2c78ca60-e232-44f6-956b-b86b472b1c28", + "metadata": {}, + "source": [ + "Pass a :class:`DataFrame` to plot with indices as row/column labels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fad17798-c2e3-4334-abf0-0d46153971fa", + "metadata": {}, + "outputs": [], + "source": [ + "glue = sns.load_dataset(\"glue\").pivot(\"Model\", \"Task\", \"Score\")\n", + "sns.heatmap(glue)" + ] + }, + { + "cell_type": "raw", + "id": "f3255c5f-2477-4d13-b4c2-7e56380e9cc2", + "metadata": {}, + "source": [ + "Use `annot` to represent the cell values with text:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c9f3c73-c8bc-426e-bc67-dec8f807082e", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, annot=True)" + ] + }, + { + "cell_type": "raw", + "id": "bc412da8-866a-49b7-8496-01fbf06dd908", + "metadata": {}, + "source": [ + "Control the annotations with a formatting string:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac952d0d-9187-4dff-a560-88430076851a", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, annot=True, fmt=\".1f\")" + ] + }, + { + "cell_type": "raw", + "id": "5eb12725-e9ee-4df0-9708-243d7e0a77b5", + "metadata": {}, + "source": [ + "Use a separate dataframe for the annotations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1189a37f-9f74-455a-a09a-c22e056d8ba7", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, annot=glue.rank(axis=\"columns\"))" + ] + }, + { + "cell_type": "raw", + "id": "253dfb7f-aa12-4716-adc2-3a38b003b2c3", + "metadata": {}, + "source": [ + "Add lines between cells:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5cac673e-9b86-490b-9e67-ec0cf865bede", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, annot=True, linewidth=.5)" + ] + }, + { + "cell_type": "raw", + "id": "b7d3659c-f996-4af3-a612-430d97799c72", + "metadata": {}, + "source": [ + "Select a different colormap by name:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "86806d72-e784-430e-8320-48f2c91115bb", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, cmap=\"crest\")" + ] + }, + { + "cell_type": "raw", + "id": "8336fd53-3841-458f-b26c-411efff54d45", + "metadata": {}, + "source": [ + "Or pass a colormap object:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9944ff33-991f-4138-a951-e3015c0326f1", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True))" + ] + }, + { + "cell_type": "raw", + "id": "52cc4dba-b86a-4da8-9cbd-3f8aa06b43b4", + "metadata": {}, + "source": [ + "Set the colormap norm (data values corresponding to minimum and maximum points):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b4ddb41e-c075-41a5-8afe-422ad6d105bf", + "metadata": {}, + "outputs": [], + "source": [ + "sns.heatmap(glue, vmin=50, vmax=100)" + ] + }, + { + "cell_type": "raw", + "id": "6e828517-a532-49b1-be11-eda47c50cc37", + "metadata": {}, + "source": [ + "Use methods on the :class:`matplotlib.axes.Axes` object to tweak the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1aab26fc-2de4-4d4f-ad08-487809573deb", + "metadata": {}, + "outputs": [], + "source": [ + "ax = sns.heatmap(glue, annot=True)\n", + "ax.set(xlabel=\"\", ylabel=\"\")\n", + "ax.xaxis.tick_top()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d8e738c-388a-453a-b9c7-4c71a674b69c", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/histplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/histplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..79b66364d4da4bdc91ba83ceb9506fbd292e8f92 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/histplot.ipynb @@ -0,0 +1,483 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"white\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assign a variable to ``x`` to plot a univariate distribution along the x axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.histplot(data=penguins, x=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Flip the plot by assigning the data variable to the y axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, y=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check how well the histogram represents the data by specifying a different bin width:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, x=\"flipper_length_mm\", binwidth=3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also define the total number of bins to use:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, x=\"flipper_length_mm\", bins=30)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add a kernel density estimate to smooth the histogram, providing complementary information about the shape of the distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, x=\"flipper_length_mm\", kde=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If neither `x` nor `y` is assigned, the dataset is treated as wide-form, and a histogram is drawn for each numeric column:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can otherwise draw multiple histograms from a long-form dataset with hue mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, x=\"flipper_length_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default approach to plotting multiple distributions is to \"layer\" them, but you can also \"stack\" them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Overlapping bars can be hard to visually resolve. A different approach would be to draw a step function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(penguins, x=\"flipper_length_mm\", hue=\"species\", element=\"step\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can move even farther away from bars by drawing a polygon with vertices in the center of each bin. This may make it easier to see the shape of the distribution, but use with caution: it will be less obvious to your audience that they are looking at a histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(penguins, x=\"flipper_length_mm\", hue=\"species\", element=\"poly\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To compare the distribution of subsets that differ substantially in size, use independent density normalization:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " penguins, x=\"bill_length_mm\", hue=\"island\", element=\"step\",\n", + " stat=\"density\", common_norm=False,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's also possible to normalize so that each bar's height shows a probability, proportion, or percent, which make more sense for discrete variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.histplot(data=tips, x=\"size\", stat=\"percent\", discrete=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can even draw a histogram over categorical variables (although this is an experimental feature):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=tips, x=\"day\", shrink=.8)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When using a ``hue`` semantic with discrete data, it can make sense to \"dodge\" the levels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=tips, x=\"day\", hue=\"sex\", multiple=\"dodge\", shrink=.8)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Real-world data is often skewed. For heavily skewed distributions, it's better to define the bins in log space. Compare:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "planets = sns.load_dataset(\"planets\")\n", + "sns.histplot(data=planets, x=\"distance\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To the log-scale version:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=planets, x=\"distance\", log_scale=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are also a number of options for how the histogram appears. You can show unfilled bars:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=planets, x=\"distance\", log_scale=True, fill=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Or an unfilled step function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(data=planets, x=\"distance\", log_scale=True, element=\"step\", fill=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Step functions, esepcially when unfilled, make it easy to compare cumulative histograms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " data=planets, x=\"distance\", hue=\"method\",\n", + " hue_order=[\"Radial Velocity\", \"Transit\"],\n", + " log_scale=True, element=\"step\", fill=False,\n", + " cumulative=True, stat=\"density\", common_norm=False,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When both ``x`` and ``y`` are assigned, a bivariate histogram is computed and shown as a heatmap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(penguins, x=\"bill_depth_mm\", y=\"body_mass_g\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's possible to assign a ``hue`` variable too, although this will not work well if data from the different levels have substantial overlap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(penguins, x=\"bill_depth_mm\", y=\"body_mass_g\", hue=\"species\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multiple color maps can make sense when one of the variables is discrete:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " penguins, x=\"bill_depth_mm\", y=\"species\", hue=\"species\", legend=False\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The bivariate histogram accepts all of the same options for computation as its univariate counterpart, using tuples to parametrize ``x`` and ``y`` independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " planets, x=\"year\", y=\"distance\",\n", + " bins=30, discrete=(True, False), log_scale=(False, True),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default behavior makes cells with no observations transparent, although this can be disabled: " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " planets, x=\"year\", y=\"distance\",\n", + " bins=30, discrete=(True, False), log_scale=(False, True),\n", + " thresh=None,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's also possible to set the threshold and colormap saturation point in terms of the proportion of cumulative counts:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " planets, x=\"year\", y=\"distance\",\n", + " bins=30, discrete=(True, False), log_scale=(False, True),\n", + " pthresh=.05, pmax=.9,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To annotate the colormap, add a colorbar:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.histplot(\n", + " planets, x=\"year\", y=\"distance\",\n", + " bins=30, discrete=(True, False), log_scale=(False, True),\n", + " cbar=True, cbar_kws=dict(shrink=.75),\n", + ")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/hls_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/hls_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..49a7db979fc1a9e2c2313600643df93f8190ba13 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/hls_palette.ipynb @@ -0,0 +1,157 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "158cd1cf-6b30-4054-b32f-a166fcb883be", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "c81b86cb-fb4e-418b-8d2f-6cd10601ac5a", + "metadata": {}, + "source": [ + "By default, return 6 colors with identical lightness and saturation and evenly-sampled hues:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6c3eaeaf-88eb-4012-96ea-41b328fa98b9", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette()" + ] + }, + { + "cell_type": "raw", + "id": "f7624b0b-2311-45de-b6a5-fc07132ce455", + "metadata": {}, + "source": [ + "Increase the number of colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "555c29d1-6972-4a19-ad32-957fb7545634", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette(8)" + ] + }, + { + "cell_type": "raw", + "id": "24713fa6-e485-4358-9ffc-d40bd9543caa", + "metadata": {}, + "source": [ + "Decrease the lightness:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b6f80b4c-f7b4-4deb-a119-cdf6cfe1f7b5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette(l=.3)" + ] + }, + { + "cell_type": "raw", + "id": "e521b514-5572-43e8-95ae-a20cc30169b8", + "metadata": {}, + "source": [ + "Decrease the saturation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f88bd038-0c9c-48b1-92b0-d272a9c199f4", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette(s=.3)" + ] + }, + { + "cell_type": "raw", + "id": "92a2212c-2177-4c82-8a5e-9dd788e9f87c", + "metadata": {}, + "source": [ + "Change the start-point for hue sampling:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f8da8fbc-551c-4896-b1b8-04203e740d78", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette(h=.5)" + ] + }, + { + "cell_type": "raw", + "id": "87780608-1f5a-409f-b31f-6a31a599f122", + "metadata": {}, + "source": [ + "Return a continuous colormap. Notice the perceptual discontinuities, especially around yellow, cyan, and magenta: " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c622b3b-70d7-4139-8389-f3d0d4addd66", + "metadata": {}, + "outputs": [], + "source": [ + "sns.hls_palette(as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3a83c1de-88c5-4327-abd2-19e8f3642052", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/husl_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/husl_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8b48b558981124b4d015392056845e0e0b065009 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/husl_palette.ipynb @@ -0,0 +1,157 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "a6794650-f28f-40eb-95a7-3f0e5c4b332d", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "fab2f86e-45d4-4982-ade7-0a5ea6d762d1", + "metadata": {}, + "source": [ + "By default, return 6 colors with identical lightness and saturation and evenly-sampled hues:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b220950e-0ca2-4101-b56a-14eebe8ee8d0", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette()" + ] + }, + { + "cell_type": "raw", + "id": "c5e4a2e3-e6b8-42bf-be19-348ff7ae2798", + "metadata": {}, + "source": [ + "Increase the number of colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7d0af740-cfca-49fb-a472-1daa4ccb3f3a", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette(8)" + ] + }, + { + "cell_type": "raw", + "id": "1a7189f2-2a26-446a-90e7-cf41dcac4f25", + "metadata": {}, + "source": [ + "Decrease the lightness:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43af79c7-f497-41e5-874a-83eed99500f3", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette(l=.4)" + ] + }, + { + "cell_type": "raw", + "id": "6d4099b7-5115-4365-b120-33a345581f5d", + "metadata": {}, + "source": [ + "Decrease the saturation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "52c1afc7-d982-4199-b218-222aa94563c5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette(s=.4)" + ] + }, + { + "cell_type": "raw", + "id": "d26131ac-0d11-48c5-88b1-4e5cf9383000", + "metadata": {}, + "source": [ + "Change the start-point for hue sampling:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d72f06a0-13e0-47f7-bc70-4c5935eaa130", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette(h=.5)" + ] + }, + { + "cell_type": "raw", + "id": "7e6c3c19-41d3-4315-b03e-909d201d0e76", + "metadata": {}, + "source": [ + "Return a continuous colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "49c18838-0589-496f-9a61-635195c07f61", + "metadata": {}, + "outputs": [], + "source": [ + "sns.husl_palette(as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c710a557-8e84-44cb-ab4c-baabcc4fd328", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/jointplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/jointplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b0b9d8f3eddd3ea1fce64d20b837ee24c9670b49 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/jointplot.ipynb @@ -0,0 +1,194 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"white\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In the simplest invocation, assign ``x`` and ``y`` to create a scatterplot (using :func:`scatterplot`) with marginal histograms (using :func:`histplot`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a ``hue`` variable will add conditional colors to the scatterplot and draw separate density curves (using :func:`kdeplot`) on the marginal axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Several different approaches to plotting are available through the ``kind`` parameter. Setting ``kind=\"kde\"`` will draw both bivariate and univariate KDEs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Set ``kind=\"reg\"`` to add a linear regression fit (using :func:`regplot`) and univariate KDE curves:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"reg\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "There are also two options for bin-based visualization of the joint distribution. The first, with ``kind=\"hist\"``, uses :func:`histplot` on all of the axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"hist\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Alternatively, setting ``kind=\"hex\"`` will use :meth:`matplotlib.axes.Axes.hexbin` to compute a bivariate histogram using hexagonal bins:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"hex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Additional keyword arguments can be passed down to the underlying plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " marker=\"+\", s=100, marginal_kws=dict(bins=25, fill=False),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use :class:`JointGrid` parameters to control the size and layout of the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", height=5, ratio=2, marginal_ticks=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To add more layers onto the plot, use the methods on the :class:`JointGrid` object that :func:`jointplot` returns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot_joint(sns.kdeplot, color=\"r\", zorder=0, levels=6)\n", + "g.plot_marginals(sns.rugplot, color=\"r\", height=-.15, clip_on=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/kdeplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/kdeplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f301c56359779d1e5616a8f89ce6bce7f5663140 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/kdeplot.ipynb @@ -0,0 +1,349 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns; sns.set_theme()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a univariate distribution along the x axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.kdeplot(data=tips, x=\"total_bill\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Flip the plot by assigning the data variable to the y axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, y=\"total_bill\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot distributions for each column of a wide-form dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iris = sns.load_dataset(\"iris\")\n", + "sns.kdeplot(data=iris)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use less smoothing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, x=\"total_bill\", bw_adjust=.2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use more smoothing, but don't smooth past the extreme data points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ax= sns.kdeplot(data=tips, x=\"total_bill\", bw_adjust=5, cut=0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot conditional distributions with hue mapping of a second variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, x=\"total_bill\", hue=\"time\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Stack\" the conditional distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, x=\"total_bill\", hue=\"time\", multiple=\"stack\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Normalize the stacked distribution at each value in the grid:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, x=\"total_bill\", hue=\"time\", multiple=\"fill\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Estimate the cumulative distribution function(s), normalizing each subset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(\n", + " data=tips, x=\"total_bill\", hue=\"time\",\n", + " cumulative=True, common_norm=False, common_grid=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Estimate distribution from aggregated data, using weights:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips_agg = (tips\n", + " .groupby(\"size\")\n", + " .agg(total_bill=(\"total_bill\", \"mean\"), n=(\"total_bill\", \"count\"))\n", + ")\n", + "sns.kdeplot(data=tips_agg, x=\"total_bill\", weights=\"n\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Map the data variable with log scaling:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "diamonds = sns.load_dataset(\"diamonds\")\n", + "sns.kdeplot(data=diamonds, x=\"price\", log_scale=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use numeric hue mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=tips, x=\"total_bill\", hue=\"size\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Modify the appearance of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(\n", + " data=tips, x=\"total_bill\", hue=\"size\",\n", + " fill=True, common_norm=False, palette=\"crest\",\n", + " alpha=.5, linewidth=0,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a bivariate distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "geyser = sns.load_dataset(\"geyser\")\n", + "sns.kdeplot(data=geyser, x=\"waiting\", y=\"duration\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Map a third variable with a hue semantic to show conditional distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=geyser, x=\"waiting\", y=\"duration\", hue=\"kind\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Show filled contours:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(\n", + " data=geyser, x=\"waiting\", y=\"duration\", hue=\"kind\", fill=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Show fewer contour levels, covering less of the distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(\n", + " data=geyser, x=\"waiting\", y=\"duration\", hue=\"kind\",\n", + " levels=5, thresh=.2,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill the axes extent with a smooth distribution, using a different colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(\n", + " data=geyser, x=\"waiting\", y=\"duration\",\n", + " fill=True, thresh=0, levels=100, cmap=\"mako\",\n", + ")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/light_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/light_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..15564b63e3192b0195149c90325d2b128e77de1b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/light_palette.ipynb @@ -0,0 +1,139 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "5cd1cbb8-ba1a-460b-8e3a-bc285867f1d1", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "raw", + "id": "b157eb25-015f-4dd6-9785-83ba19cf4f94", + "metadata": {}, + "source": [ + "Define a sequential ramp from a light gray to a specified color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "851a4742-6276-4383-b17e-480beb896877", + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette(\"seagreen\")" + ] + }, + { + "cell_type": "raw", + "id": "50053b26-112a-4378-8ef0-9be0fb565ec7", + "metadata": {}, + "source": [ + "Specify the color with a hex code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74ae0d17-f65b-4bcf-ae66-d97d46964d5c", + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette(\"#79C\")" + ] + }, + { + "cell_type": "raw", + "id": "eea376a2-fdf5-40e4-a187-3a28af529072", + "metadata": {}, + "source": [ + "Specify the color from the husl system:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66e451ee-869a-41ea-8dc5-4240b11e7be5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette((20, 60, 50), input=\"husl\")" + ] + }, + { + "cell_type": "raw", + "id": "e4f44dcd-cf49-4920-ac05-b4db67870363", + "metadata": {}, + "source": [ + "Increase the number of colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75985f07-de92-4d8b-89d5-caf445b9375e", + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette(\"xkcd:copper\", 8)" + ] + }, + { + "cell_type": "raw", + "id": "34687ae8-fd6d-427a-a639-208f19e61122", + "metadata": {}, + "source": [ + "Return a continuous colormap rather than a discrete palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c342db4-7f97-40f5-934e-9a82201890d1", + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette(\"#a275ac\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e7ebe64b-25fa-4c52-9ebe-fdcbba0ee51e", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/lineplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/lineplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..985440eac5b3e593279c7507667694e666abf99f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/lineplot.ipynb @@ -0,0 +1,453 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import matplotlib as mpl\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``flights`` dataset has 10 years of monthly airline passenger data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights = sns.load_dataset(\"flights\")\n", + "flights.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To draw a line plot using long-form data, assign the ``x`` and ``y`` variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "may_flights = flights.query(\"month == 'May'\")\n", + "sns.lineplot(data=may_flights, x=\"year\", y=\"passengers\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Pivot the dataframe to a wide-form representation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_wide = flights.pivot(\"year\", \"month\", \"passengers\")\n", + "flights_wide.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To plot a single vector, pass it to ``data``. If the vector is a :class:`pandas.Series`, it will be plotted against its index:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights_wide[\"May\"])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Passing the entire wide-form dataset to ``data`` plots a separate line for each column:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights_wide)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Passing the entire dataset in long-form mode will aggregate over repeated values (each year) to show the mean and 95% confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights, x=\"year\", y=\"passengers\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assign a grouping semantic (``hue``, ``size``, or ``style``) to plot separate lines" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights, x=\"year\", y=\"passengers\", hue=\"month\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The same column can be assigned to multiple semantic variables, which can increase the accessibility of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights, x=\"year\", y=\"passengers\", hue=\"month\", style=\"month\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use the `orient` parameter to aggregate and sort along the vertical dimension of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=flights, x=\"passengers\", y=\"year\", orient=\"y\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Each semantic variable can also represent a different column. For that, we'll need a more complex dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fmri = sns.load_dataset(\"fmri\")\n", + "fmri.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Repeated observations are aggregated even when semantic grouping is used:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=fmri, x=\"timepoint\", y=\"signal\", hue=\"event\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assign both ``hue`` and ``style`` to represent two different grouping variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(data=fmri, x=\"timepoint\", y=\"signal\", hue=\"region\", style=\"event\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When assigning a ``style`` variable, markers can be used instead of (or along with) dashes to distinguish the groups:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=fmri,\n", + " x=\"timepoint\", y=\"signal\", hue=\"event\", style=\"event\",\n", + " markers=True, dashes=False\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Show error bars instead of error bands and extend them to two standard error widths:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=fmri, x=\"timepoint\", y=\"signal\", hue=\"event\", err_style=\"bars\", errorbar=(\"se\", 2),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning the ``units`` variable will plot multiple lines without applying a semantic mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=fmri.query(\"region == 'frontal'\"),\n", + " x=\"timepoint\", y=\"signal\", hue=\"event\", units=\"subject\",\n", + " estimator=None, lw=1,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Load another dataset with a numeric grouping variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dots = sns.load_dataset(\"dots\").query(\"align == 'dots'\")\n", + "dots.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a numeric variable to ``hue`` maps it differently, using a different default palette and a quantitative color mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=dots, x=\"time\", y=\"firing_rate\", hue=\"coherence\", style=\"choice\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Control the color mapping by setting the ``palette`` and passing a :class:`matplotlib.colors.Normalize` object:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=dots.query(\"coherence > 0\"),\n", + " x=\"time\", y=\"firing_rate\", hue=\"coherence\", style=\"choice\",\n", + " palette=\"flare\", hue_norm=mpl.colors.LogNorm(),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or pass specific colors, either as a Python list or dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "palette = sns.color_palette(\"mako_r\", 6)\n", + "sns.lineplot(\n", + " data=dots, x=\"time\", y=\"firing_rate\",\n", + " hue=\"coherence\", style=\"choice\",\n", + " palette=palette\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assign the ``size`` semantic to map the width of the lines with a numeric variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=dots, x=\"time\", y=\"firing_rate\",\n", + " size=\"coherence\", hue=\"choice\",\n", + " legend=\"full\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Pass a a tuple, ``sizes=(smallest, largest)``, to control the range of linewidths used to map the ``size`` semantic:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lineplot(\n", + " data=dots, x=\"time\", y=\"firing_rate\",\n", + " size=\"coherence\", hue=\"choice\",\n", + " sizes=(.25, 2.5)\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the observations are sorted by ``x``. Disable this to plot a line with the order that observations appear in the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x, y = np.random.normal(size=(2, 5000)).cumsum(axis=1)\n", + "sns.lineplot(x=x, y=y, sort=False, lw=1)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use :func:`relplot` to combine :func:`lineplot` and :class:`FacetGrid`. This allows grouping within additional categorical variables. Using :func:`relplot` is safer than using :class:`FacetGrid` directly, as it ensures synchronization of the semantic mappings across facets:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, x=\"timepoint\", y=\"signal\",\n", + " col=\"region\", hue=\"event\", style=\"event\",\n", + " kind=\"line\"\n", + ")" + ] + } + ], + "metadata": { + "interpreter": { + "hash": "8bdfc9d9da1e36addfcfc8a3409187c45d33387af0f87d0d91e99e8d6403f1c3" + }, + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/lmplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/lmplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4a5b4119b871295f901dadcd2d267e9e1988313f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/lmplot.ipynb @@ -0,0 +1,157 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "034a9a5b-91ff-4ccc-932d-0f314e2cd6d2", + "metadata": {}, + "source": [ + "See the :func:`regplot` docs for demonstrations of various options for specifying the regression model, which are also accepted here." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76c91243-3bd8-49a1-b8c8-b7272f09a3f1", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"ticks\")\n", + "penguins = sns.load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "0ba9f55d-17ea-4084-a74f-852d51771380", + "metadata": {}, + "source": [ + "Plot a regression fit over a scatter plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f789265-93c0-4867-b666-798713e4e7e5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "id": "7e4b0ad4-446c-4109-9393-961f76132e34", + "metadata": {}, + "source": [ + "Condition the regression fit on another variable and represent it using color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "61347189-34e5-42ea-b77b-4acdef843326", + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "id": "c9b6d059-49dc-46a7-869b-86baa3a7ed65", + "metadata": {}, + "source": [ + "Condition the regression fit on another variable and split across subplots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d8ec2955-ccc9-493c-b9ec-c78648ce9f53", + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " hue=\"species\", col=\"sex\", height=4,\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "de01dee1-b2ce-445c-8d0d-d054ca0dfedb", + "metadata": {}, + "source": [ + "Condition across two variables using both columns and rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f1264aa-829c-416a-805a-b989e5f11a17", + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " col=\"species\", row=\"sex\", height=3,\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "b3888f04-b22f-4205-8acc-24ce5b59568e", + "metadata": {}, + "source": [ + "Allow axis limits to vary across subplots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "67ed5af1-d228-4b81-b4f8-21937c513a10", + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " col=\"species\", row=\"sex\", height=3,\n", + " facet_kws=dict(sharex=False, sharey=False),\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "46e9cf18-c847-4c40-8e38-6c20cdde2be5", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/move_legend.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/move_legend.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f16fcf502b66f446327b359a86aab84194250bf8 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/move_legend.ipynb @@ -0,0 +1,156 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "8ec46ad8-bc4c-4ee0-9626-271088c702f9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "penguins = sns.load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "008bdd98-88cb-4a81-9f50-9b0e5a357305", + "metadata": {}, + "source": [ + "For axes-level functions, pass the :class:`matplotlib.axes.Axes` object and provide a new location." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b82e58f9-b15d-4554-bee5-de6a689344a6", + "metadata": {}, + "outputs": [], + "source": [ + "ax = sns.histplot(penguins, x=\"bill_length_mm\", hue=\"species\")\n", + "sns.move_legend(ax, \"center right\")" + ] + }, + { + "cell_type": "raw", + "id": "4f2a7f5d-ab39-46c7-87f4-532e607adf0b", + "metadata": {}, + "source": [ + "Use the `bbox_to_anchor` parameter for more fine-grained control, including moving the legend outside of the axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed610a98-447a-4459-8342-48abc80330f0", + "metadata": {}, + "outputs": [], + "source": [ + "ax = sns.histplot(penguins, x=\"bill_length_mm\", hue=\"species\")\n", + "sns.move_legend(ax, \"upper left\", bbox_to_anchor=(1, 1))" + ] + }, + { + "cell_type": "raw", + "id": "9d2fd766-a806-45d9-949d-1572991cf512", + "metadata": {}, + "source": [ + "Pass additional :meth:`matplotlib.axes.Axes.legend` parameters to update other properties:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ad4342c-c46e-49e9-98a2-6c88c6fb4c54", + "metadata": {}, + "outputs": [], + "source": [ + "ax = sns.histplot(penguins, x=\"bill_length_mm\", hue=\"species\")\n", + "sns.move_legend(\n", + " ax, \"lower center\",\n", + " bbox_to_anchor=(.5, 1), ncol=3, title=None, frameon=False,\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0d573092-46fd-4a95-b7ed-7e6833823adc", + "metadata": {}, + "source": [ + "It's also possible to move the legend created by a figure-level function. But when fine-tuning the position, you must bear in mind that the figure will have extra blank space on the right:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b258a9b8-69e5-4d4a-94cb-5b6baddc402b", + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.displot(\n", + " penguins,\n", + " x=\"bill_length_mm\", hue=\"species\",\n", + " col=\"island\", col_wrap=2, height=3,\n", + ")\n", + "sns.move_legend(g, \"upper left\", bbox_to_anchor=(.55, .45))" + ] + }, + { + "cell_type": "raw", + "id": "c9dc54e2-2c66-412f-ab2a-4f2bc2cb5782", + "metadata": {}, + "source": [ + "One way to avoid this would be to set `legend_out=False` on the :class:`FacetGrid`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "06cff408-4cdf-47af-8def-176f3e70ec5a", + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.displot(\n", + " penguins,\n", + " x=\"bill_length_mm\", hue=\"species\",\n", + " col=\"island\", col_wrap=2, height=3,\n", + " facet_kws=dict(legend_out=False),\n", + ")\n", + "sns.move_legend(g, \"upper left\", bbox_to_anchor=(.55, .45), frameon=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b170f20d-22a9-4f7d-917a-d09e10b1f08c", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/mpl_palette.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/mpl_palette.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c65d4292f8b7c6150ffc7f0a552bea0a19c705c3 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/mpl_palette.ipynb @@ -0,0 +1,139 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "1d0d41d3-463c-4c6f-aa65-38131bdf3ddb", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "sns.palettes._patch_colormap_display()" + ] + }, + { + "cell_type": "markdown", + "id": "d2a0ae1e-a01e-49b3-a677-2b05a195990a", + "metadata": {}, + "source": [ + "Return discrete samples from a continuous matplotlib colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b6a4ce9-6e4e-4b59-ada8-14ef8aef21d7", + "metadata": {}, + "outputs": [], + "source": [ + "sns.mpl_palette(\"viridis\")" + ] + }, + { + "cell_type": "raw", + "id": "0ccc47b1-c969-46e2-93bb-b9eb5a2e2141", + "metadata": {}, + "source": [ + "Return the continuous colormap instead; note how the extreme values are more intense:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a8a1bc5d-1d62-45c6-a53b-9fadb58f11c0", + "metadata": {}, + "outputs": [], + "source": [ + "sns.mpl_palette(\"viridis\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "id": "ff0d1a3b-8641-40c0-bb4b-c22b83ec9432", + "metadata": {}, + "source": [ + "Return more colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8faef1d8-a1eb-4060-be10-377342c9bd1d", + "metadata": {}, + "outputs": [], + "source": [ + "sns.mpl_palette(\"viridis\", 8)" + ] + }, + { + "cell_type": "raw", + "id": "612bf052-e888-411d-a2ea-6a742a78bc63", + "metadata": {}, + "source": [ + "Return values from a qualitative colormap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74db95a8-4898-4f6c-a57d-c751af1dc7bf", + "metadata": {}, + "outputs": [], + "source": [ + "sns.mpl_palette(\"Set2\")" + ] + }, + { + "cell_type": "raw", + "id": "918494bf-1b8e-4b00-8950-1bd73032dee1", + "metadata": {}, + "source": [ + "Notice how the palette will only contain distinct colors and can be shorter than requested:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d97efa25-9050-4e28-b758-da6f43c9f963", + "metadata": {}, + "outputs": [], + "source": [ + "sns.mpl_palette(\"Set2\", 10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f64ad118-e213-43cc-a714-98ed13cc3824", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Agg.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Agg.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5e640f324a975668998b487f8789f4ffaae90c3e --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Agg.ipynb @@ -0,0 +1,140 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "0d053943-66c9-410d-ad65-ce91f1c1ff48", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "51b029af-b83b-4ae0-a6ff-f48bf9692518", + "metadata": {}, + "source": [ + "The default behavior is to aggregate by taking a mean over each group:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28451b4e-9f4e-4604-b2b9-6138c4f51436", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(diamonds, \"clarity\", \"carat\")\n", + "p.add(so.Bar(), so.Agg())" + ] + }, + { + "cell_type": "raw", + "id": "53859a3b-051c-423d-97ef-b03f647268b7", + "metadata": {}, + "source": [ + "Other aggregation functions can be selected by name if they are pandas methods:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5beaac3a-b9f7-4acc-81c7-480599e3675e", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bar(), so.Agg(\"median\"))" + ] + }, + { + "cell_type": "raw", + "id": "2d318ee3-56c1-4fd4-99a5-fa87db770f67", + "metadata": {}, + "source": [ + "It's also possible to pass an arbitrary aggregation function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bd11e289-7274-464a-b781-06fb756cf8de", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bar(), so.Agg(lambda x: x.quantile(.75) - x.quantile(.25)))" + ] + }, + { + "cell_type": "raw", + "id": "555394c1-25f8-4932-94d1-f67a8a9fa1c6", + "metadata": {}, + "source": [ + "When other mapping variables are assigned, they'll be used to define aggregation groups. With some marks, it may be helpful to use additional transforms, such as :class:`Dodge`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5755cdeb-1d1a-4434-9cc5-91024735eb4e", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bar(), so.Agg(), so.Dodge(), color=\"cut\")" + ] + }, + { + "cell_type": "raw", + "id": "07eb1150-db57-4a58-b830-8a7aba9f46ec", + "metadata": {}, + "source": [ + "The variable that gets aggregated depends on the orientation of the layer, which is usually inferred from the coordinate variable types (but may also be specified with the `orient` parameter in :meth:`Plot.add`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1bdcc970-1b6c-4a3d-b0bc-6c7a625163ff", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(diamonds, \"carat\", \"clarity\").add(so.Bar(), so.Agg())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ad8006ff-5472-4345-9537-a5680c519f4f", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Area.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Area.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9ee18b6e7b08a6f1a8718d098d7f1d95ed51af46 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Area.ipynb @@ -0,0 +1,161 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "healthexp = (\n", + " load_dataset(\"healthexp\")\n", + " .pivot(\"Year\", \"Country\", \"Spending_USD\")\n", + " .interpolate()\n", + " .stack()\n", + " .rename(\"Spending_USD\")\n", + " .reset_index()\n", + " .sort_values(\"Country\")\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6d3bc7fe-0b0b-49eb-8f8b-ddd8c7441044", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(healthexp, \"Year\", \"Spending_USD\").facet(\"Country\", wrap=3)\n", + "p.add(so.Area())" + ] + }, + { + "cell_type": "raw", + "id": "3a47b7f1-31ef-4218-a1ea-c289f3c64ab5", + "metadata": {}, + "source": [ + "The `color` property sets both the edge and fill color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1697359a-bf26-49d0-891b-49c207cab82d", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), color=\"Country\")" + ] + }, + { + "cell_type": "raw", + "id": "9bfaed37-7153-45d9-89e5-b348c7c14401", + "metadata": {}, + "source": [ + "It's also possible to map only the `edgecolor`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "39e5c9e5-793e-450c-a5d2-e09d5ad1f854", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(color=\".5\", edgewidth=2), edgecolor=\"Country\")" + ] + }, + { + "cell_type": "raw", + "id": "0b1a5297-9e96-472d-b284-919048e41358", + "metadata": {}, + "source": [ + "The mark is drawn as a polygon, but it can be combined with :class:`Line` to draw a shaded region by setting `edgewidth=0`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42b65535-acf6-4634-84bd-6e35305e3018", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(edgewidth=0)).add(so.Line())" + ] + }, + { + "cell_type": "raw", + "id": "59761f97-eadb-4047-9e6b-09339545fe57", + "metadata": {}, + "source": [ + "The layer's orientation defines the axis that the mark fills from:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a1c30f88-6287-486d-ae4b-fc272bc8e6ab", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), x=\"Spending_USD\", y=\"Year\", orient=\"y\")" + ] + }, + { + "cell_type": "raw", + "id": "f1b893c5-6847-4e5b-9fc2-4190ddd75099", + "metadata": {}, + "source": [ + "This mark can be stacked to show part-whole relationships:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66a79e6e-3e7f-4f54-9394-f8b003a0e228", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, \"Year\", \"Spending_USD\", color=\"Country\")\n", + " .add(so.Area(alpha=.7), so.Stack())\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69f4e423-94f4-4003-b337-12162d1040c2", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Band.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Band.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..896f96a1995221e7b0019fa0ecf5a03da161217f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Band.ipynb @@ -0,0 +1,143 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "fmri = load_dataset(\"fmri\").query(\"region == 'parietal'\")\n", + "seaice = (\n", + " load_dataset(\"seaice\")\n", + " .assign(\n", + " Day=lambda x: x[\"Date\"].dt.day_of_year,\n", + " Year=lambda x: x[\"Date\"].dt.year,\n", + " )\n", + " .query(\"Year >= 1980\")\n", + " .astype({\"Year\": str})\n", + " .pivot(index=\"Day\", columns=\"Year\", values=\"Extent\")\n", + " .filter([\"1980\", \"2019\"])\n", + " .dropna()\n", + " .reset_index()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e840e876-fbd6-4bfd-868c-a9d7af7913fa", + "metadata": {}, + "source": [ + "The mark fills between pairs of data points to show an interval on the value axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "518cf20d-bb0b-433a-9b25-f1ed8d432149", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(seaice, x=\"Day\", ymin=\"1980\", ymax=\"2019\")\n", + "p.add(so.Band())" + ] + }, + { + "cell_type": "raw", + "id": "fa50b778-13f9-4368-a967-68365fd51117", + "metadata": {}, + "source": [ + "By default it draws a faint ribbon with no edges, but edges can be added:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a05176c4-0615-49ca-a2df-48ced8b5a8a8", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Band(alpha=.5, edgewidth=2))" + ] + }, + { + "cell_type": "raw", + "id": "776d192a-f35f-4253-be7f-01e4b2466dad", + "metadata": {}, + "source": [ + "The defaults are optimized for the main expected usecase, where the mark is combined with a line to show an errorbar interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69f4e423-94f4-4003-b337-12162d1040c2", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(fmri, x=\"timepoint\", y=\"signal\", color=\"event\")\n", + " .add(so.Band(), so.Est())\n", + " .add(so.Line(), so.Agg())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "9f0c82bf-3457-4ac5-ba48-8930bac03d75", + "metadata": {}, + "source": [ + "When min/max values are not explicitly assigned or added in a transform, the band will cover the full extent of the data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "309f578e-da3d-4dc5-b6ac-a354321334c8", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(fmri, x=\"timepoint\", y=\"signal\", color=\"event\")\n", + " .add(so.Line(linewidth=.5), group=\"subject\")\n", + " .add(so.Band())\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4330a3cd-63fe-470a-8e83-09e9606643b5", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bar.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bar.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8d746252aadb5a31f131b32fbec979f6058471e6 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bar.ipynb @@ -0,0 +1,186 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")\n", + "flights = load_dataset(\"flights\").query(\"year == 1960\")" + ] + }, + { + "cell_type": "raw", + "id": "4e817cdd-09a3-4cf6-8602-e9665607bfe1", + "metadata": {}, + "source": [ + "The mark draws discrete bars from a baseline to provided values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5a4e5ba1-50ce-4060-8eb7-f17fee9080c0", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(flights[\"month\"], flights[\"passengers\"]).add(so.Bar())" + ] + }, + { + "cell_type": "raw", + "id": "252cf7b2-7fc8-4085-8174-0126743d8a08", + "metadata": {}, + "source": [ + "The bars are oriented depending on the x/y variable types and the `orient` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "81dbbc81-178a-46dd-9acf-2c57d2a7e315", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(flights[\"passengers\"], flights[\"month\"]).add(so.Bar())" + ] + }, + { + "cell_type": "markdown", + "id": "6fddeceb-25b9-4fc1-bae0-4cc4cb612674", + "metadata": {}, + "source": [ + "A common usecase will be drawing histograms on a variable with a nominal scale:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "08604543-c681-4cd3-943e-b57c0f863b2e", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(penguins, x=\"species\").add(so.Bar(), so.Hist())" + ] + }, + { + "cell_type": "markdown", + "id": "8b9af978-fdb0-46aa-9cf9-d3e49e38b344", + "metadata": {}, + "source": [ + "When mapping additional variables, the bars will overlap by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "297f7fef-7c31-40dd-ac68-e0ce7f131528", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(penguins, x=\"species\", color=\"sex\").add(so.Bar(), so.Hist())" + ] + }, + { + "cell_type": "raw", + "id": "cd9b7b4a-3150-42b5-b1a8-1c5950ca8703", + "metadata": {}, + "source": [ + "Apply a move transform, such as a :class:`Dodge` or :class:`Stack` to resolve them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a13c7594-737c-4215-b2a2-e59fc2d033c3", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(penguins, x=\"species\", color=\"sex\").add(so.Bar(), so.Hist(), so.Dodge())" + ] + }, + { + "cell_type": "raw", + "id": "f5f44a6b-610a-4523-a7c2-39c804a60520", + "metadata": {}, + "source": [ + "A number of properties can be mapped or set:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5cbf5a9-effb-4550-bdaf-c266dc69d3f0", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " penguins, x=\"species\",\n", + " color=\"sex\", alpha=\"sex\", edgestyle=\"sex\",\n", + " )\n", + " .add(so.Bar(edgewidth=2), so.Hist(), so.Dodge(\"fill\"))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "539144d9-75bc-4eb0-8fed-ca57b516b6d3", + "metadata": {}, + "source": [ + "Combine with :class:`Range` to plot an estimate with errorbars:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89233c4a-38e7-4807-b3b4-3b4540ffcf56", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, \"body_mass_g\", \"species\", color=\"sex\")\n", + " .add(so.Bar(alpha=.5), so.Agg(), so.Dodge())\n", + " .add(so.Range(), so.Est(errorbar=\"sd\"), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f6a97a0-2d92-4fd5-ad98-b4299bda1b6b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bars.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bars.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b6609731e2b0f73b5cd6c466f63e9c201f26c7fd --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Bars.ipynb @@ -0,0 +1,165 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "5cf83822-ceb1-4ce5-8364-069466f7aa40", + "metadata": {}, + "source": [ + "This mark draws bars between a baseline and a value. In contrast to :class:`Bar`, the bars have a full width and thin edges by default; this makes this mark a better choice for a continuous histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9b99eaf-695f-41ae-9bd1-bfe406dedb63", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(diamonds, \"price\").scale(x=\"log\")\n", + "p.add(so.Bars(), so.Hist())" + ] + }, + { + "cell_type": "raw", + "id": "bc4c0f25-3f7a-4a2c-a032-151da47f5ea3", + "metadata": {}, + "source": [ + "When mapping the color or other properties, bars will overlap by default; this is usually confusing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7989211b-7a29-4763-bb97-4ea19cdef081", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(), color=\"cut\")" + ] + }, + { + "cell_type": "raw", + "id": "f16a3b5d-1ac1-4d9d-9bc6-d4cea7f83a17", + "metadata": {}, + "source": [ + "Using a move transform, such as :class:`Stack` or :class:`Dodge`, will resolve the overlap (although faceting might often be a better approach):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8933f5f7-1423-4741-b7be-6239ea8b2fee", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(), so.Stack(), color=\"cut\")" + ] + }, + { + "cell_type": "raw", + "id": "74075e80-0361-4388-a459-cbfa6418df6c", + "metadata": {}, + "source": [ + "A number of different properties can be set or mapped:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "04fada68-a61b-451c-b3bd-9aaab16b5f29", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(edgewidth=0), so.Hist(), so.Stack(), alpha=\"clarity\")" + ] + }, + { + "cell_type": "raw", + "id": "a14d7d36-9d8b-4024-8653-002e9da946d7", + "metadata": {}, + "source": [ + "It is possible to draw unfilled bars, but you must override the default edge color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "21642f8c-99c7-4f61-b3f5-bc1dacc638c3", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(fill=False, edgecolor=\"C0\", edgewidth=1.5), so.Hist())" + ] + }, + { + "cell_type": "raw", + "id": "dce5b6cc-0808-48ec-b4d6-0c0c2e5178d2", + "metadata": {}, + "source": [ + "It is also possible to narrow the bars, which may be useful for dealing with overlap in some cases:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "166693bf-420c-4ec3-8da2-abc22724952b", + "metadata": {}, + "outputs": [], + "source": [ + "hist = so.Hist(binwidth=.075, binrange=(2, 5))\n", + "(\n", + " p.add(so.Bars(), hist)\n", + " .add(\n", + " so.Bars(color=\".9\", width=.5), hist,\n", + " data=diamonds.query(\"cut == 'Ideal'\")\n", + " )\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b40b02c4-fb2c-4300-93e4-24ea28bc6ef8", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Count.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Count.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ee7af016e98117e1922d40a9e6a9356c678b8c3a --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Count.ipynb @@ -0,0 +1,121 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "89113d6b-70b9-4ebe-9910-10a80eab246e", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "tips = load_dataset(\"tips\")" + ] + }, + { + "cell_type": "raw", + "id": "daf6ff78-df24-4541-ba72-73fb9eddb50d", + "metadata": {}, + "source": [ + "The transform counts distinct observations of the orientation variable defines a new variable on the opposite axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "390f2fd3-0596-40e3-b262-163b3a90d055", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(tips, x=\"day\").add(so.Bar(), so.Count())" + ] + }, + { + "cell_type": "raw", + "id": "813fb4a5-db68-4b51-b236-5b5628ebba47", + "metadata": {}, + "source": [ + "When additional mapping variables are defined, they are also used to define groups:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76a4ae70-e914-4f54-b979-ce1b79374fc3", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(tips, x=\"day\", color=\"sex\").add(so.Bar(), so.Count(), so.Dodge())" + ] + }, + { + "cell_type": "raw", + "id": "2973dee1-5aee-4768-846d-22d220faf170", + "metadata": {}, + "source": [ + "Unlike :class:`Hist`, numeric data are not binned before counting:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f94c5f0-680e-4d8a-a1c9-70876980dd1c", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(tips, x=\"size\").add(so.Bar(), so.Count())" + ] + }, + { + "cell_type": "raw", + "id": "11acd5e6-f477-4eb1-b1d7-72f4582bca45", + "metadata": {}, + "source": [ + "When the `y` variable is defined, the counts are assigned to the `x` variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "924e0e35-210f-4f65-83b4-4aebe41ad264", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(tips, y=\"size\").add(so.Bar(), so.Count())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0229fa39-b6dc-48da-9a25-31e25ed34ebc", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dash.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dash.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..845fbc5216bdc45e3a91a844cbedbb1204028e45 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dash.ipynb @@ -0,0 +1,168 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "3227e585-7166-44e7-b0c2-8570e098102d", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "1b424322-eaa4-45c7-8007-a671ef2afbde", + "metadata": {}, + "source": [ + "A line segment is drawn for each datapoint, centered on the value along the orientation axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fc835356-2dc2-4583-a9f9-c1fe0a6cc9ea", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(penguins, \"species\", \"body_mass_g\", color=\"sex\")\n", + "p.add(so.Dash())" + ] + }, + { + "cell_type": "raw", + "id": "ad9b94de-f19f-4e60-8275-686e749da39c", + "metadata": {}, + "source": [ + "A number of properties can be mapped or set directly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6070a665-ab19-43a6-9eba-e206193d9422", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dash(alpha=.5), linewidth=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "raw", + "id": "2c4a8291-0a84-4e70-a992-756850933791", + "metadata": {}, + "source": [ + "The mark has a `width` property, which is relative to the spacing between orientation values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "315327da-421e-46c8-8a1b-8b87355d0439", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dash(width=.5))" + ] + }, + { + "cell_type": "raw", + "id": "224bf51a-b8d8-4d8e-b0ab-b63ec6788584", + "metadata": {}, + "source": [ + "When dodged, the width will automatically adapt:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "227e889c-7ce7-49fc-b985-f7746393930e", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dash(), so.Dodge())" + ] + }, + { + "cell_type": "raw", + "id": "aa807f57-5d37-4faa-8fd2-1e5378115f9f", + "metadata": {}, + "source": [ + "This mark works well to show aggregate values when paired with a strip plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5141e0b8-ea1a-4178-adde-21b4bc2e705f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p\n", + " .add(so.Dash(), so.Agg(), so.Dodge())\n", + " .add(so.Dots(), so.Dodge(), so.Jitter())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "f2abd4b7-5afb-4661-95f3-b51bfa101273", + "metadata": {}, + "source": [ + "When both coordinate variables are numeric, you can control the orientation explicitly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f6d7e236-327f-460f-b12e-46d7444ac348", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " penguins[\"body_mass_g\"],\n", + " penguins[\"flipper_length_mm\"].round(-1),\n", + " )\n", + " .add(so.Dash(), orient=\"y\")\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6811d776-93e5-49ce-88a6-14786a67841d", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dodge.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dodge.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1b3c0e1d07167baa43c16102604c690e19594464 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dodge.ipynb @@ -0,0 +1,198 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "4d44a940-db84-4e16-bc83-e67d08d6d56a", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "tips = load_dataset(\"tips\").astype({\"time\": str})" + ] + }, + { + "cell_type": "raw", + "id": "ce99e1a1-c213-478f-a5bc-d19e2c4d70db", + "metadata": {}, + "source": [ + "This transform modifies both the width and position (along the orientation axis) of marks that would otherwise overlap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f6a84062-2c2b-4a45-91cb-77f29462104d", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"day\", color=\"time\")\n", + " .add(so.Bar(), so.Count(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "55d3a9a8-c973-4e91-9f3a-bc137df15f48", + "metadata": {}, + "source": [ + "By default, empty space may appear when variables are not fully crossed:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "08ae1c65-5ad9-47a3-a8f3-d901bd4821f2", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(tips, \"day\", color=\"time\")\n", + "p.add(so.Bar(), so.Count(), so.Dodge())" + ] + }, + { + "cell_type": "raw", + "id": "2125f07d-4210-4d49-8761-bcfa3f9c67f5", + "metadata": {}, + "source": [ + "The `empty` parameter handles this case; use it to fill out the space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c2314343-de73-45d7-9595-acf5f7d62e93", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bar(), so.Count(), so.Dodge(empty=\"fill\"))" + ] + }, + { + "cell_type": "raw", + "id": "08f4382c-842e-4777-a452-1d88251da6e7", + "metadata": {}, + "source": [ + "Or center the marks while using a consistent width:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1e0745e4-be11-4703-bf9c-4b13cbb76e91", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bar(), so.Count(), so.Dodge(empty=\"drop\"))" + ] + }, + { + "cell_type": "raw", + "id": "7d29ec53-caef-4cff-9828-dc242adb5c49", + "metadata": {}, + "source": [ + "Use `gap` to add a bit of spacing between dodged marks:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "342aca16-c67b-4bc4-9101-fec6c398aa0f", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(tips, \"day\", \"total_bill\", color=\"sex\")\n", + "p.add(so.Bar(), so.Agg(\"sum\"), so.Dodge(gap=.1))" + ] + }, + { + "cell_type": "raw", + "id": "68b52dcb-c5e7-4186-b61f-e96fac5f4d40", + "metadata": {}, + "source": [ + "When multiple semantic variables are used, each distinct group will be dodged:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "497f3e3b-39bc-4381-85bb-be5bb5c60b1f", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dot(), so.Dodge(), fill=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "id": "795835d2-904f-4343-89c2-b91be9c1c504", + "metadata": {}, + "source": [ + "Use `by` to dodge only a subset of variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "da01f6c0-c425-409c-a010-5cb52a794dc9", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dot(), so.Dodge(by=[\"color\"]), fill=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "id": "77de77da-2fad-4374-9d14-90520e448c90", + "metadata": {}, + "source": [ + "When combining with other transforms (such as :class:`Jitter` or :class:`Stack`), be mindful of the order that they are applied in:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "29ccabd6-6bd5-4563-a337-f8f8d25f7dad", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dot(), so.Dodge(), so.Jitter())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a73fe9a5-c717-41fd-874e-be72334ea6d4", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a60745320b5390a0e2a6eaf84d907643fbdb0bc --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dot.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "tips = load_dataset(\"tips\")\n", + "glue = load_dataset(\"glue\")" + ] + }, + { + "cell_type": "raw", + "id": "f8e7b343-0301-49b3-8d42-862266d322bb", + "metadata": {}, + "source": [ + "This mark draws relatively large, filled dots by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f92e97d0-b6a5-41ec-8507-dc64e60cb6e0", + "metadata": {}, + "outputs": [], + "source": [ + "p1 = so.Plot(tips, \"total_bill\", \"tip\")\n", + "p1.add(so.Dot())" + ] + }, + { + "cell_type": "raw", + "id": "625abe2a-7b0b-42a7-bfbc-dc2bfaf14897", + "metadata": {}, + "source": [ + "While :class:`Dots` is a better choice for dense scatter plots, adding a thin edge can help to resolve individual points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3c7c22d-c7ce-40a9-941b-a8bc30db1e54", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dot(edgecolor=\"w\"))" + ] + }, + { + "cell_type": "markdown", + "id": "398a43e1-4d45-42ea-bc87-41a8602540a4", + "metadata": {}, + "source": [ + "Dodging and jittering can also help to reduce overplotting, when appropriate:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1b15e393-35cf-457f-8180-d92d05e2675a", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"total_bill\", \"day\", color=\"sex\")\n", + " .add(so.Dot(), so.Dodge(), so.Jitter(.2))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "12453ada-40e6-4aad-9f32-ba41fd7b27ca", + "metadata": {}, + "source": [ + "The larger dot size makes this mark well suited to representing values along a nominal scale:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bd2edac0-ee6b-4cc9-8201-641b589630b8", + "metadata": {}, + "outputs": [], + "source": [ + "p2 = so.Plot(glue, \"Score\", \"Model\").facet(\"Task\", wrap=4).limit(x=(-5, 105))\n", + "p2.add(so.Dot())" + ] + }, + { + "cell_type": "raw", + "id": "ddd86209-d5cd-4f7a-9274-c578bc6a9f07", + "metadata": {}, + "source": [ + "A number of properties can be set or mapped:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d00cdc35-4b9c-4f32-a047-8e036e565c4f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p2\n", + " .add(so.Dot(pointsize=6), color=\"Year\", marker=\"Encoder\")\n", + " .scale(marker=[\"o\", \"s\"], color=\"flare\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "061e22f4-8505-425d-8c80-8ac82c6a3125", + "metadata": {}, + "source": [ + "Note that the edge properties are parameterized differently for filled and unfilled markers; use `stroke` and `color` rather than `edgewidth` and `edgecolor` if the marker is unfilled:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "964b00be-1c29-4664-838d-0daeead9154a", + "metadata": {}, + "outputs": [], + "source": [ + "p2.add(so.Dot(stroke=1.5), fill=\"Encoder\", color=\"Encoder\")" + ] + }, + { + "cell_type": "raw", + "id": "fb5e1383-1460-4389-a67b-09ec7965af90", + "metadata": {}, + "source": [ + "Combine with :class:`Range` to show error bars:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2618c22-bc7f-4ddd-9824-346e8d9b2b51", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"day\")\n", + " .add(so.Dot(pointsize=3), so.Shift(y=.2), so.Jitter(.2))\n", + " .add(so.Dot(), so.Agg())\n", + " .add(so.Range(), so.Est(errorbar=(\"se\", 2)))\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5dc04fd-dba4-4b86-99a1-31ba00c7650d", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dots.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dots.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2576b899b2b15bc80377bd11c30bca519c4a2207 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Dots.ipynb @@ -0,0 +1,146 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "mpg = load_dataset(\"mpg\")" + ] + }, + { + "cell_type": "raw", + "id": "f8e7b343-0301-49b3-8d42-862266d322bb", + "metadata": {}, + "source": [ + "This mark draws relatively small, partially-transparent dots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d668d7f6-555b-4b5d-876e-35e259076d2a", + "metadata": {}, + "outputs": [], + "source": [ + "p1 = so.Plot(mpg, \"horsepower\", \"mpg\")\n", + "p1.add(so.Dots())" + ] + }, + { + "cell_type": "raw", + "id": "a2cf4669-9c91-4adc-9e3a-3b0660e7898e", + "metadata": {}, + "source": [ + "Fixing or mapping the `color` property changes both the stroke (edge) and fill:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bba2b1c5-22fd-4f44-af8d-defb31dfbe9d", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dots(), color=\"origin\")" + ] + }, + { + "cell_type": "raw", + "id": "bf967d57-22cf-4bce-b718-aae6936719e6", + "metadata": {}, + "source": [ + "These properties can be independently parametrized (although the resulting plot may not always be clear):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c45261a9-fb88-4eb5-b633-060debda261b", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p1.add(so.Dots(fillalpha=.5), color=\"origin\", fillcolor=\"weight\")\n", + " .scale(fillcolor=\"binary\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "b20dcaee-8e09-4a76-8eff-5289ef43ea8c", + "metadata": {}, + "source": [ + "Filled and unfilled markers will happily mix:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a1a9bdda-abb7-4850-a936-ceed518b9b17", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dots(stroke=1), marker=\"origin\").scale(marker=[\"o\", \"x\", (6, 2, 1)])" + ] + }, + { + "cell_type": "raw", + "id": "1d932f10-e8f8-4114-9362-3da82c7b5ac0", + "metadata": {}, + "source": [ + "The partial opacity also helps to see local density when using jitter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "692e1611-4804-4979-b616-041e9fa9cdd9", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg, \"horsepower\", \"origin\")\n", + " .add(so.Dots(), so.Jitter(.25))\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "acd5788f-e62b-497c-a109-f0bc02b8cae9", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Est.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Est.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3dcac462e55f33ff2b92725d29721839e3f8c033 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Est.ipynb @@ -0,0 +1,142 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "57ececfa-0ae0-4acb-b85d-7c6a6ca8d3db", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "03c64256-8daf-4b32-87bd-b425e27a7823", + "metadata": {}, + "source": [ + "The default behavior is to compute the mean and 95% confidence interval (using bootstrapping):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "46017dc7-7c3c-4dcf-9232-2e3ac490d980", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "p = so.Plot(diamonds, \"clarity\", \"carat\")\n", + "p.add(so.Range(), so.Est())" + ] + }, + { + "cell_type": "raw", + "id": "1bf04e8d-998e-4a47-9375-ddcde76e3914", + "metadata": {}, + "source": [ + "Other estimators may be selected by name if they are pandas methods:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea394c55-8fa6-4fb0-8665-42c03ef3576e", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Range(), so.Est(\"median\"))" + ] + }, + { + "cell_type": "raw", + "id": "9c5f3c91-fecb-4e75-b045-b30870154083", + "metadata": {}, + "source": [ + "There are several options for computing the error bar interval, such as (scaled) standard errors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9c350af5-d549-4cce-b3f2-e9bef33aef36", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Range(), so.Est(errorbar=\"se\"))" + ] + }, + { + "cell_type": "raw", + "id": "8c8d321b-5e73-418c-8c71-4b91cf187e57", + "metadata": {}, + "source": [ + "The error bars can also represent the spread of the distribution around the estimate using (scaled) standard deviations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd2cd9dc-e4c9-4ba1-ac79-38806cf1e009", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Range(), so.Est(errorbar=\"sd\"))" + ] + }, + { + "cell_type": "raw", + "id": "6dba074b-881c-40df-b42e-458e4a26e23d", + "metadata": {}, + "source": [ + "Because confidence intervals are computed using bootstrapping, there will be small amounts of randomness. Reduce the random variability by increasing the nubmer of bootstrap iterations (although this will be slower), or eliminate it by seeding the random number generator:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6b450e1-8b1f-411f-aa01-bbb46ab3b6ec", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Range(), so.Est(seed=0))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5e4a0594-e1ee-4f72-971e-3763dd626e8b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Hist.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Hist.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..93ed02ea217dc30a4e4d28ed21ac123f2a4266f2 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Hist.ipynb @@ -0,0 +1,231 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "59690096-a0ad-4ff3-b82c-0258d724035a", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "c345a35c-bac8-4163-ba40-e7c208df1033", + "metadata": {}, + "source": [ + "For discrete or categorical variables, this stat is commonly combined with a :class:`Bar` mark:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6a96ac9b-1240-496d-9385-840205945208", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(penguins, \"island\").add(so.Bar(), so.Hist())" + ] + }, + { + "cell_type": "raw", + "id": "1e5ff9d5-c6a9-4adc-a9be-0f155b1575be", + "metadata": {}, + "source": [ + "When used to estimate a univariate distribution, it is better to use the :class:`Bars` mark:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7f3e3144-752a-4d71-9528-85eb1ed0a9a4", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(penguins, \"flipper_length_mm\")\n", + "p.add(so.Bars(), so.Hist())" + ] + }, + { + "cell_type": "raw", + "id": "008b9ffe-da74-4406-9756-4f70e333f33b", + "metadata": {}, + "source": [ + "The granularity of the bins will influence whether the underlying distribution is accurately represented. Adjust it by setting the total number:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "27d221d5-add5-40a8-85d2-05102384dad1", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(bins=20))" + ] + }, + { + "cell_type": "raw", + "id": "fffebb54-0299-45c5-b7fb-6fcad6427239", + "metadata": {}, + "source": [ + "Alternatively, specify the *width* of the bins:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d036ca65-7dcf-45ac-a2d1-caafb9f922a7", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(binwidth=5))" + ] + }, + { + "cell_type": "raw", + "id": "bc1e4bd3-2a16-42bd-9c13-a660dd381f66", + "metadata": {}, + "source": [ + "By default, the transform returns the count of observations in each bin. The counts can be normalized, e.g. to show a proportion:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dbf23712-2231-4226-8265-0e2a5299c4bb", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(stat=\"proportion\"))" + ] + }, + { + "cell_type": "raw", + "id": "6c6fb23e-78c5-4630-a958-62cb4dee4ec8", + "metadata": {}, + "source": [ + "When additional variables define groups, the default behavior is to normalize across all groups:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac3fe4ef-56e3-4ec7-b580-596d2a3d924b", + "metadata": {}, + "outputs": [], + "source": [ + "p = p.facet(\"island\")\n", + "p.add(so.Bars(), so.Hist(stat=\"proportion\"))" + ] + }, + { + "cell_type": "raw", + "id": "f7afc403-26cc-4325-a28a-913c2291aa35", + "metadata": {}, + "source": [ + "Pass `common_norm=False` to normalize each distribution independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2029324-069f-4261-a178-1efad2fd0e88", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(stat=\"proportion\", common_norm=False))" + ] + }, + { + "cell_type": "raw", + "id": "0f83401a-e456-4a14-af69-f1483c6c03c4", + "metadata": {}, + "source": [ + "Or, with more than one grouping varible, specify a subset to normalize within:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5c092262-8a8f-4a3e-8cae-9e0f23dd94ba", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(stat=\"proportion\", common_norm=[\"col\"]), color=\"sex\")" + ] + }, + { + "cell_type": "raw", + "id": "86532133-bf33-4674-9614-86ae3408aa51", + "metadata": {}, + "source": [ + "When distributions overlap it may be easier to discern their shapes with an :class:`Area` mark:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "00b18ad8-52d4-460a-a012-d87c66b3e71e", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.Hist(), color=\"sex\")" + ] + }, + { + "cell_type": "raw", + "id": "2b34d435-abbf-41aa-b219-91883d7d29f3", + "metadata": {}, + "source": [ + "Or add :class:`Stack` move to represent a part-whole relationship:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3a7a0c05-d774-4f99-950f-5dc9865027c4", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Bars(), so.Hist(), so.Stack(), color=\"sex\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e247e74b-2c09-40f0-8f45-9fa5f8264d78", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Jitter.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Jitter.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ede8ce43c564bc941a8638d2b1496564d8aa32c0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Jitter.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "f2e5a85d-c710-492b-a4fc-09b45ae26471", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "14b5927c-42f1-4934-adee-3d380b8b3228", + "metadata": {}, + "source": [ + "When used without any arguments, a small amount of jitter will be applied along the orientation axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bc1b4941-bbe6-4afc-b51a-0ac67cbe417d", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, \"species\", \"body_mass_g\")\n", + " .add(so.Dots(), so.Jitter())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "1101690e-6c19-4219-aa4e-180798454df1", + "metadata": {}, + "source": [ + "The `width` parameter controls the amount of jitter relative to the spacing between the marks:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c4251b9d-8b11-4c2c-905c-2f3b523dee70", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, \"species\", \"body_mass_g\")\n", + " .add(so.Dots(), so.Jitter(.5))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "38aa639a-356e-4674-970b-53d55379b2b7", + "metadata": {}, + "source": [ + "The `width` parameter always applies to the orientation axis, so the direction of jitter will adapt along with the orientation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1cfe1c07-7e81-45a0-a989-240503046133", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, \"body_mass_g\", \"species\")\n", + " .add(so.Dots(), so.Jitter(.5))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0f5de4cc-3383-4503-8b59-9c48230a12a5", + "metadata": {}, + "source": [ + "Because the `width` jitter is relative, it can be used when the orientation axis is numeric without further tweaking:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c94c41e8-29c4-4439-a5d1-0b8ffb244890", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins[\"body_mass_g\"].round(-3), penguins[\"flipper_length_mm\"])\n", + " .add(so.Dots(), so.Jitter())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "dd982dfa-fd9f-4edc-8190-18f0e101ae1a", + "metadata": {}, + "source": [ + "In contrast to `width`, the `x` and `y` parameters always refer to specific axes and control the jitter in data units:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b0f2e5ca-68ad-4439-a4ee-f32f65682e95", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins[\"body_mass_g\"].round(-3), penguins[\"flipper_length_mm\"])\n", + " .add(so.Dots(), so.Jitter(x=100))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a90ba526-8043-42ed-8f57-36445c163c0d", + "metadata": {}, + "source": [ + "Both `x` and `y` can be used in a single transform:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6c07ed1d-ac77-4b30-90a8-e1b8760f9fad", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " penguins[\"body_mass_g\"].round(-3),\n", + " penguins[\"flipper_length_mm\"].round(-1),\n", + " )\n", + " .add(so.Dots(), so.Jitter(x=200, y=5))\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb04c7a2-93f0-44cf-aacf-0eb436d0f14b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.KDE.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.KDE.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..863a5a16ad77c66f8c2a7e80f3c2ed67bade42d5 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.KDE.ipynb @@ -0,0 +1,270 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "dcc1ae12-bba4-4de9-af8d-543b3d65b42b", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "1042b991-1471-43bd-934c-43caae3cb2fa", + "metadata": {}, + "source": [ + "This stat estimates transforms observations into a smooth function representing the estimated density:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2406e2aa-7f0f-4a51-af59-4cef827d28d8", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(penguins, x=\"flipper_length_mm\")\n", + "p.add(so.Area(), so.KDE())" + ] + }, + { + "cell_type": "raw", + "id": "44515f21-683b-420f-967b-4c7568c907d7", + "metadata": {}, + "source": [ + "Adjust the smoothing bandwidth to see more or fewer details:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4e6ba5b-4dd2-4210-8cf0-de057dc71e2a", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.KDE(bw_adjust=0.25))" + ] + }, + { + "cell_type": "raw", + "id": "fd665fe1-a5e4-4742-adc9-e40615d57d08", + "metadata": {}, + "source": [ + "The curve will extend beyond observed values in the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4cda1cb8-f663-4f94-aa24-6f1727a41031", + "metadata": {}, + "outputs": [], + "source": [ + "p2 = p.add(so.Bars(alpha=.3), so.Hist(\"density\"))\n", + "p2.add(so.Line(), so.KDE())" + ] + }, + { + "cell_type": "raw", + "id": "75235825-d522-4562-aacc-9b7413eabf5d", + "metadata": {}, + "source": [ + "Control the range of the density curve relative to the observations using `cut`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a7a9275e-9889-437d-bdc5-18653d2c92ef", + "metadata": {}, + "outputs": [], + "source": [ + "p2.add(so.Line(), so.KDE(cut=0))" + ] + }, + { + "cell_type": "raw", + "id": "6a885eeb-81ba-47c6-8402-1bef40544fd1", + "metadata": {}, + "source": [ + "When observations are assigned to the `y` variable, the density will be shown for `x`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "38b3a0fb-54ff-493a-bd64-f83a12365723", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(penguins, y=\"flipper_length_mm\").add(so.Area(), so.KDE())" + ] + }, + { + "cell_type": "raw", + "id": "59996340-168e-479f-a0c6-c7e1fcab0fb0", + "metadata": {}, + "source": [ + "Use `gridsize` to increase or decrease the resolution of the grid where the density is evaluated:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "23715820-7df9-40ba-9e74-f11564704dd0", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dots(), so.KDE(gridsize=100))" + ] + }, + { + "cell_type": "raw", + "id": "4c9b6492-98c8-45ab-9f53-681cde2f767a", + "metadata": {}, + "source": [ + "Or pass `None` to evaluate the density at the original datapoints:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e1b6810-5c28-43aa-aa61-652521299b51", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dots(), so.KDE(gridsize=None))" + ] + }, + { + "cell_type": "raw", + "id": "0970a56b-0cba-4c40-bb1b-b8e71739df5c", + "metadata": {}, + "source": [ + "Other variables will define groups for the estimation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f0ce0b6-5742-4bc0-9ac3-abedde923684", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.KDE(), color=\"species\")" + ] + }, + { + "cell_type": "raw", + "id": "22204fcd-4b25-46e5-a170-02b1419c23d5", + "metadata": {}, + "source": [ + "By default, the density is normalized across all groups (i.e., the joint density is shown); pass `common_norm=False` to show conditional densities:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6ad56958-dc45-4632-94d1-23039ad3ec58", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.KDE(common_norm=False), color=\"species\")" + ] + }, + { + "cell_type": "raw", + "id": "b1627197-85d1-4476-b4ae-3e93044ee988", + "metadata": {}, + "source": [ + "Or pass a list of variables to condition on:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "58f63734-5afd-4d90-bbfb-fc39c8d1981f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p.facet(\"sex\")\n", + " .add(so.Area(), so.KDE(common_norm=[\"col\"]), color=\"species\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "2b7e018e-1374-4939-909c-e95f5ffd086e", + "metadata": {}, + "source": [ + "This stat can be combined with other transforms, such as :class:`Stack` (when `common_grid=True`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96e5b2d0-c7e2-47df-91f1-7f9ec0bb08a9", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.KDE(), so.Stack(), color=\"sex\")" + ] + }, + { + "cell_type": "raw", + "id": "8500ff86-0b1f-4831-954b-08b6df690387", + "metadata": {}, + "source": [ + "Set `cumulative=True` to integrate the density:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "26bb736e-7cfd-421e-b80d-42fa450e88c0", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Line(), so.KDE(cumulative=True))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8bfd9d2-ad60-4971-aa7f-71a285f44a20", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Line.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Line.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c0e5587f51456fd22c152200e60ea43caa4aad4b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Line.ipynb @@ -0,0 +1,168 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "dowjones = load_dataset(\"dowjones\")\n", + "fmri = load_dataset(\"fmri\")" + ] + }, + { + "cell_type": "markdown", + "id": "05468ecf-d2f5-46f0-ba43-ea13aba0ebd2", + "metadata": {}, + "source": [ + "The mark draws a connecting line between sorted observations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "acd5788f-e62b-497c-a109-f0bc02b8cae9", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(dowjones, \"Date\", \"Price\").add(so.Line())" + ] + }, + { + "cell_type": "markdown", + "id": "94efb077-49a5-4214-891a-c68f89c79926", + "metadata": {}, + "source": [ + "Change the orientation to connect observations along the opposite axis (`orient=\"y\"` is redundant here; the plot would detect that the date variable has a lower orientation priority than the price variable):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c5db48f-1c88-4905-a5f5-2ae96ceb0f95", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(dowjones, x=\"Price\", y=\"Date\").add(so.Line(), orient=\"y\")" + ] + }, + { + "cell_type": "raw", + "id": "77bd0b1e-d9d1-4741-9821-83cec708e877", + "metadata": {}, + "source": [ + "To replicate the same line multiple times, assign a `group` variable (but consider using :class:`Lines` here instead):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c1b699c-4e42-4461-a7fb-0d664ef8fe1b", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " fmri\n", + " .query(\"region == 'parietal' and event == 'stim'\")\n", + " .pipe(so.Plot, \"timepoint\", \"signal\")\n", + " .add(so.Line(color=\".2\", linewidth=1), group=\"subject\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "c09cc6a1-a86b-48b7-b276-e0e9125d279e", + "metadata": {}, + "source": [ + "When mapping variables to properties like `color` or `linestyle`, stat transforms are computed within each grouping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83b8c68d-a1ae-4bfb-b3dc-4a11bbe85cbc", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(fmri, \"timepoint\", \"signal\", color=\"region\", linestyle=\"event\")\n", + "p.add(so.Line(), so.Agg())" + ] + }, + { + "cell_type": "raw", + "id": "c9390f58-0fb1-47ba-8b86-bde4c41e6d1d", + "metadata": {}, + "source": [ + "Combine with :class:`Band` to show an error bar:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b6ab0006-0f28-4992-b687-41889a424684", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p\n", + " .add(so.Line(), so.Agg())\n", + " .add(so.Band(), so.Est(), group=\"event\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e567df5c-6675-423f-bcd8-94cb3a400251", + "metadata": {}, + "source": [ + "Add markers to indicate values where the data were sampled:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2541701c-1a2c-44dd-b300-6551861c8b98", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Line(marker=\"o\", edgecolor=\"w\"), so.Agg(), linestyle=None)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a25d0379-b374-4539-82a4-00ce37245e1b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Lines.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Lines.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..012a5c4eb446c6e0a611c18380ee992fdc7cb495 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Lines.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "seaice = load_dataset(\"seaice\")" + ] + }, + { + "cell_type": "raw", + "id": "09694cb8-4867-49fc-80a6-a4551e50b77e", + "metadata": {}, + "source": [ + "Like :class:`Line`, the mark draws a connecting line between sorted observations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "acd5788f-e62b-497c-a109-f0bc02b8cae9", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(seaice, \"Date\", \"Extent\").add(so.Lines())" + ] + }, + { + "cell_type": "raw", + "id": "8f982f2d-1119-4842-9860-80b415fd24fe", + "metadata": {}, + "source": [ + "Compared to :class:`Line`, this mark offers fewer settable properties, but it can have better performance when drawing a large number of lines:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4411136-1787-47ca-91f4-4ecba541e575", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " x=seaice[\"Date\"].dt.day_of_year,\n", + " y=seaice[\"Extent\"],\n", + " color=seaice[\"Date\"].dt.year\n", + " )\n", + " .facet(seaice[\"Date\"].dt.year.round(-1))\n", + " .add(so.Lines(linewidth=.5, color=\"#bbca\"), col=None)\n", + " .add(so.Lines(linewidth=1))\n", + " .scale(color=\"ch:rot=-.2,light=.7\")\n", + " .layout(size=(8, 4))\n", + " .label(title=\"{}s\".format)\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aaab3914-77d7-4d09-bdbe-f057a2fe28cf", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Norm.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Norm.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dee130640c2e45be854ae10800b03c16595cc1c9 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Norm.ipynb @@ -0,0 +1,93 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "0bfee8b6-1e3e-499d-96ae-735a5c230b32", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "healthexp = load_dataset(\"healthexp\")" + ] + }, + { + "cell_type": "raw", + "id": "43adf565-2843-48fe-a12a-1a65bc9fce9f", + "metadata": {}, + "source": [ + "By default, this transform scales each group relative to its maximum value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6262c89d-56cd-41b4-8276-0bf737b02f29", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Spending_USD\", color=\"Country\")\n", + " .add(so.Lines(), so.Norm())\n", + " .label(y=\"Spending relative to maximum amount\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "5941b47a-7f2f-4540-9944-c6a16e7eec75", + "metadata": {}, + "source": [ + "Use `where` to constrain the values used to define a baseline, and `percent` to scale the output:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8142d0b4-1b91-4ba9-bc60-3df148130ff9", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Spending_USD\", color=\"Country\")\n", + " .add(so.Lines(), so.Norm(where=\"x == x.min()\", percent=True))\n", + " .label(y=\"Percent change in spending from 1970 baseline\")\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f2d2d33-8a92-44fb-b37a-24dee23a7d75", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Path.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Path.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6ec364ff9411a739d86855c2ec4ef2fb45688c8b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Path.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "healthexp = load_dataset(\"healthexp\").sort_values([\"Country\", \"Year\"])" + ] + }, + { + "cell_type": "raw", + "id": "8c2781ed-190d-4155-99ac-0170b94de030", + "metadata": {}, + "source": [ + "Unlike :class:`Line`, this mark does not sort observations before plotting, making it suitable for plotting trajectories through a variable space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "199c0b22-1cbd-4b5a-bebe-f59afa79b9c6", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(healthexp, \"Spending_USD\", \"Life_Expectancy\", color=\"Country\")\n", + "p.add(so.Path())" + ] + }, + { + "cell_type": "raw", + "id": "fb87bd85-024b-42f5-b458-3550271d7124", + "metadata": {}, + "source": [ + "It otherwise offers the same set of options, including a number of properties that can be set or mapped:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "280de309-1c0d-4cdc-8f4c-a4f15da461cf", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Path(marker=\"o\", pointsize=2, linewidth=.75, fillcolor=\"w\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e795770-4481-4e23-a49b-e828a1f5cbbd", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Paths.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Paths.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5f326bf07aabb7b07d05672b20ae15277855e519 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Paths.ipynb @@ -0,0 +1,103 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "networks = (\n", + " load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n", + " .rename_axis(\"timepoint\")\n", + " .stack([0, 1, 2])\n", + " .groupby([\"timepoint\", \"network\", \"hemi\"])\n", + " .mean()\n", + " .unstack(\"network\")\n", + " .reset_index()\n", + " .query(\"timepoint < 100\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "50646936-5236-413f-b79b-6c3b640ade04", + "metadata": {}, + "source": [ + "Unlike :class:`Lines`, this mark does not sort observations before plotting, making it suitable for plotting trajectories through a variable space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4a3ed115-cc47-4ea8-be46-2c99f7453941", + "metadata": {}, + "outputs": [], + "source": [ + "p = (\n", + " so.Plot(networks)\n", + " .pair(\n", + " x=[\"5\", \"8\", \"12\", \"15\"],\n", + " y=[\"6\", \"13\", \"16\"],\n", + " )\n", + " .layout(size=(8, 5))\n", + " .share(x=True, y=True)\n", + ")\n", + "p.add(so.Paths())" + ] + }, + { + "cell_type": "raw", + "id": "5bf502eb-feb3-4b2e-882b-3e915bf5d041", + "metadata": {}, + "source": [ + "The mark has the same set of properties as :class:`Lines`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "326a765b-59f0-46ef-91c2-6705c6893740", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Paths(linewidth=1, alpha=.8), color=\"hemi\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "175b836d-d328-4b6c-ad36-dde18c19e3bf", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Perc.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Perc.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d1c8094aea5b7cc7040fe114075a573f66dca4a7 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Perc.ipynb @@ -0,0 +1,130 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2d44a326-029b-47ff-b560-5f4b6a4bb73f", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "65e975a2-2559-4bf1-8851-8bbbf52bf22d", + "metadata": {}, + "source": [ + "The default behavior computes the quartiles and min/max of the input data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "36f927f5-3b64-4871-a355-adadc4da769b", + "metadata": {}, + "outputs": [], + "source": [ + "p = (\n", + " so.Plot(diamonds, \"cut\", \"price\")\n", + " .scale(y=\"log\")\n", + ")\n", + "p.add(so.Dot(), so.Perc())" + ] + }, + { + "cell_type": "raw", + "id": "feba1b99-0f71-4b18-8e7e-bd5470cc2d0c", + "metadata": {}, + "source": [ + "Passing an integer will compute that many evenly-spaced percentiles:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f030dd39-1223-475a-93e1-1759a8971a6c", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dot(), so.Perc(20))" + ] + }, + { + "cell_type": "raw", + "id": "85bd754b-122e-4475-8727-2d584a90a38e", + "metadata": {}, + "source": [ + "Passing a list will compute exactly those percentiles:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2fde7549-45b5-411a-afba-eb0da754d9e9", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Dot(), so.Perc([10, 25, 50, 75, 90]))" + ] + }, + { + "cell_type": "raw", + "id": "7be16a13-dfc8-4595-a904-42f9be10f4f6", + "metadata": {}, + "source": [ + "Combine with a range mark to show a percentile interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "05c561c6-0449-4a61-96d1-390611a1b694", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, \"price\", \"cut\")\n", + " .add(so.Dots(pointsize=1, alpha=.2), so.Jitter(.3))\n", + " .add(so.Range(color=\"k\"), so.Perc([25, 75]), so.Shift(y=.2))\n", + " .scale(x=\"log\")\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d464157c-3187-49c1-9cd8-71f284ce4c50", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.add.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.add.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..365f189143972c67c73fbd69d732cca4d2b41226 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.add.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "tips = load_dataset(\"tips\")" + ] + }, + { + "cell_type": "raw", + "id": "33cd5d3c-d3ad-4e3b-bdac-350f8e104594", + "metadata": {}, + "source": [ + "Every layer must be defined with a :class:`Mark`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43d0401a-d7d5-4746-a02f-a48f8b5fd1f2", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(tips, \"total_bill\", \"tip\").add(so.Dot())\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "34b4f581-6126-4d57-ac76-8821c5daa97b", + "metadata": {}, + "source": [ + "Call :class:`Plot.add` multiple times to add multiple layers. In addition to the :class:`Mark`, layers can also be defined with :class:`Stat` or :class:`Move` transforms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "693c461e-1dc2-4b44-a9e5-c07b1bf0108b", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Line(), so.PolyFit())" + ] + }, + { + "cell_type": "raw", + "id": "96a61426-0de2-4f4b-a373-0006da6fcceb", + "metadata": {}, + "source": [ + "Multiple transforms can be stacked into a pipeline. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b22623a7-bfde-493c-8593-76b145fa1e84", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, y=\"day\", color=\"sex\")\n", + " .add(so.Bar(), so.Hist(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "aa8e6bde-c86c-4bd8-abbe-e0fc64103114", + "metadata": {}, + "source": [ + "Layers have an \"orientation\", which affects the transforms and some marks. The orientation is typically inferred from the variable types assigned to `x` and `y`, but it can be specified when it would otherwise be ambiguous:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42be495b-e41b-4883-b061-0973c0e8b496", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"size\", color=\"time\")\n", + " .add(so.Dot(alpha=.5), so.Dodge(), so.Jitter(.4), orient=\"y\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0d2a77f2-6a21-4fe6-a8b1-66978f4f072b", + "metadata": {}, + "source": [ + "Variables can be assigned to a specific layer. Note the distinction between how `pointsize` is passed to :class:`Plot.add` — so it is *mapped* by a scale — while `color` and `linewidth` are passed directly to :class:`Line`, so they directly set the line's color and width:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e42c3699-c468-4c21-b417-3952311735eb", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"total_bill\", \"tip\")\n", + " .add(so.Dots(), pointsize=\"size\")\n", + " .add(so.Line(color=\".3\", linewidth=3), so.PolyFit())\n", + " .scale(pointsize=(2, 10))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "d61908e5-9074-443d-9160-2c3101a39bcd", + "metadata": {}, + "source": [ + "Variables that would otherwise apply to the entire plot can also be *excluded* from a specific layer by setting their value to `None`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a095ecca-b428-4bad-a9ab-4d4f05cf61e0", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"total_bill\", \"tip\", color=\"day\")\n", + " .facet(col=\"day\")\n", + " .add(so.Dot(color=\"#aabc\"), col=None, color=None)\n", + " .add(so.Dot())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "60f94773-668e-441e-9634-41473c26d3bd", + "metadata": {}, + "source": [ + "Variables used only by the transforms *must* be passed at the layer level:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d1ac7e8-5bbd-4a1a-a207-197a4251c2d3", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"day\")\n", + " .add(so.Bar(), so.Hist(), weight=\"size\")\n", + " .label(y=\"Total patrons\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "8a7a5ff7-c0f5-4787-8908-3cb13ea7a047", + "metadata": {}, + "source": [ + "Each layer can be provided with its own data source. If a data source was provided in the constructor, the layer data will be joined using its index:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45690aaa-1abf-40ae-be3b-1ab648f8be62", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, \"total_bill\", \"tip\")\n", + " .add(so.Dot(color=\"#aabc\"))\n", + " .add(so.Dot(), data=tips.query(\"size == 2\"), color=\"time\")\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a403012a-e895-4e5b-b690-dc27efbeccad", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.config.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.config.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b0ba2dcef87aa2ebabb09995496674c7ec0914f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.config.ipynb @@ -0,0 +1,124 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "a38a6fed-51de-4dbc-8d5b-4971d06acf2e", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so" + ] + }, + { + "cell_type": "raw", + "id": "38081259-9382-4623-8d67-09aa114e0949", + "metadata": {}, + "source": [ + "Theme configuration\n", + "^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The theme is a dictionary of matplotlib `rc parameters `_. You can set individual parameters directly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "34ca0ce9-5284-47b6-8281-180709dbec89", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot.config.theme[\"axes.facecolor\"] = \"white\"" + ] + }, + { + "cell_type": "raw", + "id": "b3f93646-8370-4c16-ace4-7bb811688758", + "metadata": {}, + "source": [ + "To change the overall style of the plot, update the theme with a dictionary of parameters, perhaps from one of seaborn's theming functions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8e5eb7d3-cc7a-4231-b887-db37045f3db4", + "metadata": {}, + "outputs": [], + "source": [ + "from seaborn import axes_style\n", + "so.Plot.config.theme.update(axes_style(\"whitegrid\"))" + ] + }, + { + "cell_type": "raw", + "id": "f7c7bd9c-722d-45db-902a-c2dcdef571ee", + "metadata": {}, + "source": [ + "To sync :class:`Plot` with matplotlib's global state, pass the `rcParams` dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd1cd96e-1a2c-474a-809f-20b8c4794578", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib as mpl\n", + "so.Plot.config.theme.update(mpl.rcParams)" + ] + }, + { + "cell_type": "raw", + "id": "7e305ec1-4a83-411f-91df-aee2ec4d1806", + "metadata": {}, + "source": [ + "The theme can also be reset back to seaborn defaults:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3146b1d-1b5e-464f-a631-e6d6caf161b3", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot.config.theme.reset()" + ] + }, + { + "cell_type": "raw", + "id": "eae5da42-cf7f-41c9-b13d-8fa25e5cf0be", + "metadata": {}, + "source": [ + "Changes made through this interface will apply to all subsequent :class:`Plot` instances. Use the :meth:`Plot.theme` method to modify the theme on a plot-by-plot basis." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.facet.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.facet.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8a7d1d7696919fcee735f9fdd29eb936d59f196 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.facet.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "fb8e120d-5dcf-483b-a0d1-74857d09ce7d", + "metadata": {}, + "source": [ + ".. currentmodule:: seaborn.objects" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "markdown", + "id": "ae85e302-354c-46ca-a17f-aaec7ed1cbd6", + "metadata": {}, + "source": [ + "Assigning a faceting variable will create multiple subplots and plot subsets of the data on each of them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d65405fd-cf28-4248-8e51-1aa1999354a2", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(penguins, \"bill_length_mm\", \"bill_depth_mm\").add(so.Dots())\n", + "p.facet(\"species\")" + ] + }, + { + "cell_type": "markdown", + "id": "2b9630aa-3b46-4e72-82ef-5717c2d8c686", + "metadata": {}, + "source": [ + "Multiple faceting variables can be defined to create a two-dimensional grid:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1857144f-1373-4704-9332-d3fc649ceb9d", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"species\", \"sex\")" + ] + }, + { + "cell_type": "markdown", + "id": "7664e2d2-c254-44b4-9973-88e1d013fb3d", + "metadata": {}, + "source": [ + "Facet variables can be provided as references to the global plot data or as vectors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6569616d-480b-4b8c-a761-f5bd2bde60e3", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(penguins[\"island\"])" + ] + }, + { + "cell_type": "markdown", + "id": "198f63a0-bb0f-40c4-b790-bd15f8656acb", + "metadata": {}, + "source": [ + "With a single faceting variable, arrange the facets or limit to a subset by passing a list of levels to `order`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b1344f7f-50d0-4592-b4fb-ab81d97a4798", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"species\", order=[\"Gentoo\", \"Adelie\"])" + ] + }, + { + "cell_type": "markdown", + "id": "2090297c-414f-4448-a930-5b6f0de18deb", + "metadata": {}, + "source": [ + "With multiple variables, pass `order` as a dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "58ed1b13-71a7-462a-af99-78be566268a6", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"species\", \"sex\", order={\"col\": [\"Gentoo\", \"Adelie\"], \"row\": [\"Female\", \"Male\"]})" + ] + }, + { + "cell_type": "markdown", + "id": "e440f14d-24b2-4f83-a247-0bb917f9f4c3", + "metadata": {}, + "source": [ + "When the faceting variable has multiple levels, you can `wrap` it to distribute subplots across both dimensions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92baf66c-6dd9-4f50-adf2-386c4daab094", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(diamonds, x=\"carat\", y=\"price\").add(so.Dots())\n", + "p.facet(\"color\", wrap=4)" + ] + }, + { + "cell_type": "markdown", + "id": "8d0872cb-e261-4796-b81e-a416fea85201", + "metadata": {}, + "source": [ + "Wrapping works only when there is a single variable, but you can wrap in either direction:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c5a66a64-bfba-437c-80be-1311e85cf5a5", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(row=\"color\", wrap=2)" + ] + }, + { + "cell_type": "raw", + "id": "e1bdaad7-5883-45ad-af39-c10183569bdc", + "metadata": {}, + "source": [ + "Use :meth:`Plot.share` to specify whether facets should be scaled the same way:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14c1f977-79d4-4f9c-a846-1fd70ad3569e", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"clarity\", wrap=3).share(x=False)" + ] + }, + { + "cell_type": "raw", + "id": "a4fc64d9-b7ba-4061-8160-63d8fd89e47a", + "metadata": {}, + "source": [ + "Use :meth:`Plot.label` to tweak the titles:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4206b12c-d7a3-419f-b278-6edfe487c5de", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"color\").label(title=\"{} grade\".format)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28b4fb9d-2bb0-40ff-a541-5f300aca6200", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.label.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.label.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1497c565048a730b2dc5895484b8be7206f01e12 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.label.ipynb @@ -0,0 +1,161 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "fb32137a-e882-4222-9463-b8cf0ee1c8bd", + "metadata": {}, + "source": [ + "Use strings to override default labels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "65b4320e-6fb9-48ed-9132-53b0d21b85e6", + "metadata": {}, + "outputs": [], + "source": [ + "p = (\n", + " so.Plot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + " .add(so.Dot(), color=\"species\")\n", + ")\n", + "p.label(x=\"Length\", y=\"Depth\", color=\"\")" + ] + }, + { + "cell_type": "raw", + "id": "a39626d2-76f5-40a9-a3fd-6f44dd69bd30", + "metadata": {}, + "source": [ + "Pass a function to *modify* the default label:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c3540c54-1c91-4d55-8f58-cd758abbe2fd", + "metadata": {}, + "outputs": [], + "source": [ + "p.label(color=str.capitalize)" + ] + }, + { + "cell_type": "markdown", + "id": "68f3b321-0755-4ef1-a9e6-bcff61a9178d", + "metadata": {}, + "source": [ + "Use this method to set the title for a single-axes plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "12d23c6e-781f-4b5c-a6b0-3ea0317ab7fb", + "metadata": {}, + "outputs": [], + "source": [ + "p.label(title=\"Penguin species exhibit distinct bill shapes\")" + ] + }, + { + "cell_type": "markdown", + "id": "8e0bcb80-0929-4ab9-b5c0-13bb3d8e4484", + "metadata": {}, + "source": [ + "When faceting, the `title` parameter will modify default titles:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "da1516b7-b823-41c0-b251-01bdecb6a4e6", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"sex\").label(title=str.upper)" + ] + }, + { + "cell_type": "markdown", + "id": "bb439eae-6cc3-4a6c-bef2-b4b7746edbd1", + "metadata": {}, + "source": [ + "And the `col`/`row` parameters will add labels to the title for each facet:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e0d49ba9-0507-4358-b477-2e0253f0df8f", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"sex\").label(col=\"Sex:\")" + ] + }, + { + "cell_type": "markdown", + "id": "99471c06-1b1a-4ef5-844c-5f4aa8f322f5", + "metadata": {}, + "source": [ + "If more customization is needed, a format string can work well:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "848be3a3-5a2c-4b98-918f-825257be85ae", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet(\"sex\").label(title=\"{} penguins\".format)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94012def-dd7c-48f4-8830-f77a3bf7299b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.layout.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.layout.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..755d6d3a28e6b780dcc305392a57771cac9f65fd --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.layout.ipynb @@ -0,0 +1,102 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so" + ] + }, + { + "cell_type": "markdown", + "id": "406f8f8d-b590-46f4-a230-626e32e52c71", + "metadata": {}, + "source": [ + "Control the overall dimensions of the figure with `size`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fefc2b45-3510-4cd7-9de9-4806d71fc4c1", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot().layout(size=(4, 4))\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "909a47bb-82f5-455a-99c3-7049d548561b", + "metadata": {}, + "source": [ + "Subplots created by using :meth:`Plot.facet` or :meth:`Plot.pair` will shrink to fit in the available space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3163687c-8d48-4e88-8dc2-35e16341e30e", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet([\"A\", \"B\"], [\"X\", \"Y\"])" + ] + }, + { + "cell_type": "markdown", + "id": "feda7c3a-3862-48d4-bb18-419cd03fc081", + "metadata": {}, + "source": [ + "You may find that different automatic layout engines give better or worse results with specific plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c2107939-c6a9-414c-b3a2-6f5d0dd60daf", + "metadata": {}, + "outputs": [], + "source": [ + "p.facet([\"A\", \"B\"], [\"X\", \"Y\"]).layout(engine=\"constrained\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "781ff58c-b805-4e93-8cae-be0442e273ea", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.limit.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.limit.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6d1ec6084d37218238d565b27fdce67c9d0148e0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.limit.ipynb @@ -0,0 +1,120 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so" + ] + }, + { + "cell_type": "raw", + "id": "1888667e-8761-4c32-9510-68e08e64f21d", + "metadata": {}, + "source": [ + "By default, plot limits are automatically set to provide a small margin around the data (controlled by :meth:`Plot.theme` parameters `axes.xmargin` and `axes.ymargin`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "25ec46d9-3c60-4962-b182-a2b2c8310305", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(x=[1, 2, 3], y=[1, 3, 2]).add(so.Line(marker=\"o\"))\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "5f5c19d8-4104-4df0-ae45-9a8ac96d024e", + "metadata": {}, + "source": [ + "Pass a `min`/`max` tuple to pin the limits at specific values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "804388c5-5efa-4cfb-92d8-97fdf838ae5e", + "metadata": {}, + "outputs": [], + "source": [ + "p.limit(x=(0, 4), y=(-1, 6))" + ] + }, + { + "cell_type": "markdown", + "id": "49634203-4c77-42ae-abc1-b182671f305e", + "metadata": {}, + "source": [ + "Reversing the `min`/`max` values will invert the axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6ea1c82c-a9bc-43cc-ba75-5ee28923b8f2", + "metadata": {}, + "outputs": [], + "source": [ + "p.limit(y=(4, 0))" + ] + }, + { + "cell_type": "raw", + "id": "9bb25c70-3960-4a81-891c-2bd299e7b24f", + "metadata": {}, + "source": [ + "Use `None` for either side to maintain the default value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0566ba8-707c-4808-9a76-525ccaef7a42", + "metadata": {}, + "outputs": [], + "source": [ + "p.limit(y=(0, None))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fefc2b45-3510-4cd7-9de9-4806d71fc4c1", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.on.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.on.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f297bf631fea259e8716996bffa80db6e4da66b3 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.on.ipynb @@ -0,0 +1,182 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "fb8e120d-5dcf-483b-a0d1-74857d09ce7d", + "metadata": {}, + "source": [ + ".. currentmodule:: seaborn.objects" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%config InlineBackend.figure_format = \"retina\"\n", + "import seaborn as sns\n", + "import seaborn.objects as so\n", + "import matplotlib as mpl\n", + "import matplotlib.pyplot as plt\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "3445ed22-7a6a-4f91-8914-49bb1af023cb", + "metadata": {}, + "source": [ + "Passing a :class:`matplotlib.axes.Axes` object provides functionality closest to seaborn's axes-level plotting functions. Notice how the resulting image looks different from others created with :class:`Plot`. This is because the plot theme uses the global rcParams at the time the axes were created, rather than :class:`Plot` defaults:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b816b0b1-b861-404e-bec6-9b2b0844ea5a", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(diamonds, \"carat\", \"price\").add(so.Dots())\n", + "f, ax = plt.subplots()\n", + "p.on(ax).show()" + ] + }, + { + "cell_type": "raw", + "id": "ce3aa102-50fe-44ce-9e06-e25d14b410f1", + "metadata": {}, + "source": [ + "Alternatively, calling :func:`matplotlib.pyplot.figure` will defer axes creation to :class:`Plot`, which will apply the default theme (and any customizations specified with :meth:`Plot.theme`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "52eefae9-d08e-48fb-a15b-27920609d53b", + "metadata": {}, + "outputs": [], + "source": [ + "f = plt.figure()\n", + "p.on(f).show()" + ] + }, + { + "cell_type": "raw", + "id": "171fa466-1f7a-4c5e-8a12-61edb3f11e4a", + "metadata": {}, + "source": [ + "Creating a :class:`matplotlib.figure.Figure` object will bypass `pyplot` altogether. This may be useful for embedding :class:`Plot` figures in a GUI application:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bba83103-ab74-4e3c-b16e-77644f4c0431", + "metadata": {}, + "outputs": [], + "source": [ + "f = mpl.figure.Figure()\n", + "p.on(f).plot()" + ] + }, + { + "cell_type": "raw", + "id": "4cce3d40-acea-4f5c-87c4-56666480d2fe", + "metadata": {}, + "source": [ + "Using :class:`Plot.on` also provides access to the underlying matplotlib objects, which may be useful for deep customization. But it requires a careful attention to the order of operations by which the :class:`Plot` is specified, compiled, customized, and displayed:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "91823d24-8269-4b72-abeb-38201eb2db3f", + "metadata": {}, + "outputs": [], + "source": [ + "f = mpl.figure.Figure()\n", + "res = p.on(f).plot()\n", + "\n", + "ax = f.axes[0]\n", + "rect = mpl.patches.Rectangle(\n", + " xy=(0, 1), width=.4, height=.1,\n", + " color=\"C1\", alpha=.2,\n", + " transform=ax.transAxes, clip_on=False,\n", + ")\n", + "ax.add_artist(rect)\n", + "ax.text(\n", + " x=rect.get_width() / 2, y=1 + rect.get_height() / 2,\n", + " s=\"Diamonds: very sparkly!\", size=12,\n", + " ha=\"center\", va=\"center\", transform=ax.transAxes,\n", + ")\n", + "\n", + "res" + ] + }, + { + "cell_type": "raw", + "id": "61286891-25b3-4db5-8ebe-af080d5c5f31", + "metadata": {}, + "source": [ + "Matplotlib 3.4 introduced the concept of :meth:`matplotlib.figure.Figure.subfigures`, which make it easier to composite multiple arrangements of subplots. These can also be passed to :meth:`Plot.on`, " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca19a28e-7a49-46b3-a727-a26f4a1099c3", + "metadata": {}, + "outputs": [], + "source": [ + "f = mpl.figure.Figure(figsize=(7, 4), dpi=100, layout=\"constrained\")\n", + "sf1, sf2 = f.subfigures(1, 2)\n", + "\n", + "p.on(sf1).plot()\n", + "(\n", + " so.Plot(diamonds, x=\"price\")\n", + " .add(so.Bars(), so.Hist())\n", + " .facet(row=\"cut\")\n", + " .scale(x=\"log\")\n", + " .share(y=False)\n", + " .on(sf2)\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6ecd4166-939d-4925-92be-bf886a16ae94", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.pair.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.pair.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c31240f57f57c897031d83bc1b6c3b77c639036b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.pair.ipynb @@ -0,0 +1,217 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "ac7814b6-1e2c-4f0e-991b-7fe78fca4346", + "metadata": {}, + "source": [ + ".. currentmodule:: seaborn.objects" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "mpg = load_dataset(\"mpg\")" + ] + }, + { + "cell_type": "markdown", + "id": "a6ee48da-ff1e-41eb-95ec-9f2dd12bdb63", + "metadata": {}, + "source": [ + "Plot one dependent variable against multiple independent variables by assigning `y` and pairing on `x`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56ab58b6-ccdf-4938-a8e0-cbe2de8d6749", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg, y=\"acceleration\")\n", + " .pair(x=[\"displacement\", \"weight\"])\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "c37e0543-d022-4079-b58a-8f8af90b29c8", + "metadata": {}, + "source": [ + "Show multiple pairwise relationships by passing lists to both `x` and `y`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "39b5298d-d578-4284-8fab-415d2c03022d", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg)\n", + " .pair(x=[\"displacement\", \"weight\"], y=[\"horsepower\", \"acceleration\"])\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "09bf54ad-bf55-4e26-8566-5af62bf29c51", + "metadata": {}, + "source": [ + "When providing lists for both `x` and `y`, pass `cross=False` to pair each position in the list rather than showing all pairwise relationships:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c70ca7d8-79ee-4c7a-ae91-2088e965b1f4", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg)\n", + " .pair(\n", + " x=[\"weight\", \"acceleration\"],\n", + " y=[\"displacement\", \"horsepower\"],\n", + " cross=False,\n", + " )\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "79beadec-038d-40f0-8783-749474d48eac", + "metadata": {}, + "source": [ + "When plotting against several `x` or `y` variables, it is possible to `wrap` the subplots to produce a two-dimensional grid:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2bf2d87f-a940-426c-bdff-8bf80696b7a1", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg, y=\"mpg\")\n", + " .pair(x=[\"displacement\", \"weight\", \"horsepower\", \"cylinders\"], wrap=2)\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "6304faed-2466-49eb-a8c2-d9d635938b78", + "metadata": {}, + "source": [ + "Pairing can be combined with faceting, either pairing on `y` and faceting on `col` or pairing on `x` and faceting on `row`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bea235cd-e9c1-4119-a683-871e60b149ec", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg, x=\"weight\")\n", + " .pair(y=[\"horsepower\", \"acceleration\"])\n", + " .facet(col=\"origin\")\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "ded931d2-95f1-4e09-8e24-f8b687f8f052", + "metadata": {}, + "source": [ + "While typically convenient to assign pairing variables as references to the common `data`, it's also possible to pass a list of vectors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66e0cb77-094b-4144-b086-15bab106ca9f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg[\"weight\"])\n", + " .pair(y=[mpg[\"horsepower\"], mpg[\"acceleration\"]])\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "7bef3310-87f6-44f6-be6a-e30effaa7a70", + "metadata": {}, + "source": [ + "When customizing the plot through methods like :meth:`Plot.label`, :meth:`Plot.limit`, or :meth:`Plot.scale`, you can refer to the individual coordinate variables as `x0`, `x1`, etc.:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6ce8868-55c0-4c44-8fed-937771b762ee", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(mpg, y=\"mpg\")\n", + " .pair(x=[\"weight\", \"displacement\"])\n", + " .label(x0=\"Weight (lb)\", x1=\"Displacement (cu in)\", y=\"MPG\")\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "358d409f-8b7c-4901-8eec-b2cf51731483", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.scale.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.scale.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b4c11680ec380dae708ec3c95f1fcf5d83d66296 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.scale.ipynb @@ -0,0 +1,316 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "diamonds = load_dataset(\"diamonds\")\n", + "mpg = load_dataset(\"mpg\").query(\"cylinders in [4, 6, 8]\")" + ] + }, + { + "cell_type": "raw", + "id": "bd43bcc6-b060-49c2-a429-8ea0ab046e2c", + "metadata": {}, + "source": [ + "Passing the name of a function, such as `\"log\"` or `\"symlog\"` will set the scale's transform:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84b84cc1-ef1c-461e-b4af-4ce6e99886d1", + "metadata": {}, + "outputs": [], + "source": [ + "p1 = so.Plot(diamonds, x=\"carat\", y=\"price\")\n", + "p1.add(so.Dots()).scale(y=\"log\")" + ] + }, + { + "cell_type": "raw", + "id": "b5ea9f7f-c776-48af-a4be-0053c3c12036", + "metadata": {}, + "source": [ + "String arguments can also specify the the name of a palette that defines the output values (or \"range\") of the scale:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e1f64d2f-6abd-48aa-9bab-c3e4614d0302", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dots(), color=\"clarity\").scale(color=\"crest\")" + ] + }, + { + "cell_type": "raw", + "id": "37df8672-33b1-49a8-b702-a87c8b95db99", + "metadata": {}, + "source": [ + "The scale's range can alternatively be specified as a tuple of min/max values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "371b8abd-ddfb-42f9-b730-f75b0e7b5fd6", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dots(), pointsize=\"carat\").scale(pointsize=(2, 10))" + ] + }, + { + "cell_type": "raw", + "id": "f0c4ead3-e950-48e4-9c81-c8734a8458d0", + "metadata": {}, + "source": [ + "The tuple format can also be used for a color scale:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "678fd8b2-b031-4ec6-a567-a6711f722cbd", + "metadata": {}, + "outputs": [], + "source": [ + "p1.add(so.Dots(), color=\"carat\").scale(color=(\".4\", \"#68d\"))" + ] + }, + { + "cell_type": "raw", + "id": "b6445ab7-2ec1-40be-95bc-9df0a5750bf5", + "metadata": {}, + "source": [ + "For more control pass a scale object, such as :class:`Continuous`, which allows you to specify the input domain (`norm`), output range (`values`), and nonlinear transform (`trans`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6a219ef-b50e-442e-82e9-8ae9e2cdb825", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "(\n", + " p1.add(so.Dots(), color=\"carat\")\n", + " .scale(color=so.Continuous((\".4\", \"#68d\"), norm=(1, 3), trans=\"sqrt\"))\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "737e73a9-a0d5-4311-8c5c-4ca42f9194bf", + "metadata": { + "tags": [] + }, + "source": [ + "The scale objects also offer an interface for configuring the location of the scale ticks (including in the legend) and the formatting of the tick labels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cfaa426a-1a97-4b6f-91b6-ee378eabf194", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p1.add(so.Dots(), color=\"price\")\n", + " .scale(\n", + " x=so.Continuous(trans=\"sqrt\").tick(every=.5),\n", + " y=so.Continuous().label(like=\"${x:g}\"),\n", + " color=so.Continuous(\"ch:.2\").tick(upto=4).label(unit=\"\"),\n", + " )\n", + " .label(y=\"\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "d4013795-fd5d-4a53-b145-e87f876a0684", + "metadata": {}, + "source": [ + "If the scale includes a nonlinear transform, it will be applied *before* any statistical transforms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9bf321f-c482-4d25-bb3b-7c499930b0d1", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " p1.add(so.Dots(color=\".7\"))\n", + " .add(so.Line(), so.PolyFit(order=2))\n", + " .scale(y=\"log\")\n", + " .limit(y=(250, 25000))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "00ac5844-efb1-4683-a8ff-e864d0c68dff", + "metadata": {}, + "source": [ + "The scale is also relevant for when numerical data should be treated as categories. Consider the following histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "04d5e6ae-30b2-495b-be1a-d99d6ffd4f44", + "metadata": {}, + "outputs": [], + "source": [ + "p2 = so.Plot(mpg, \"cylinders\").add(so.Bar(), so.Hist())\n", + "p2" + ] + }, + { + "cell_type": "raw", + "id": "9b3dafad-aae0-4862-b1b2-bb76b75a9cec", + "metadata": {}, + "source": [ + "By default, the plot gives `cylinders` a continuous scale, since it is a vector of floats. But assigning a :class:`Nominal` scale causes the histogram to bin observations properly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f89331a-69fc-4714-adfb-0568690c1b66", + "metadata": {}, + "outputs": [], + "source": [ + "p2.scale(x=so.Nominal())" + ] + }, + { + "cell_type": "raw", + "id": "78880057-f4a7-40a1-a619-20d4b3be34dc", + "metadata": {}, + "source": [ + "The default behavior for semantic mappings also depends on input data types and can be modified by the scale. Consider the sequential mapping applied to the colors in this plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "653abbc6-8227-48eb-9e1d-31587e6ef46d", + "metadata": {}, + "outputs": [], + "source": [ + "p3 = (\n", + " so.Plot(mpg, \"weight\", \"acceleration\", color=\"cylinders\")\n", + " .add(so.Dot(), marker=\"origin\")\n", + ")\n", + "p3" + ] + }, + { + "cell_type": "raw", + "id": "6ce5c9a8-5051-43b1-973c-fb9fb35ba399", + "metadata": {}, + "source": [ + "Passing the name of a qualitative palette will select a :class:`Nominal` scale:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "218d6619-1fe3-4412-a2fc-efed4f542db7", + "metadata": {}, + "outputs": [], + "source": [ + "p3.scale(color=\"deep\")" + ] + }, + { + "cell_type": "raw", + "id": "d2362247-6e0e-48fb-bbe4-2149f96785ae", + "metadata": {}, + "source": [ + "A :class:`Nominal` scale is also implied when the output values are given as a list or dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8bdf57da-cb05-4347-87ec-fac2c3763f12", + "metadata": {}, + "outputs": [], + "source": [ + "p3.scale(\n", + " color=[\"#49b\", \"#a6a\", \"#5b8\"],\n", + " marker={\"japan\": \".\", \"europe\": \"+\", \"usa\": \"*\"},\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a7d92be7-9e96-4850-a26a-090c5ae9857b", + "metadata": {}, + "source": [ + "Pass a :class:`Nominal` object directly to control the order of the category mappings:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3c7eeb9-351f-484d-b0af-e18341569de3", + "metadata": {}, + "outputs": [], + "source": [ + "p3.scale(\n", + " color=so.Nominal([\"#008fd5\", \"#fc4f30\", \"#e5ae38\"]),\n", + " marker=so.Nominal(order=[\"japan\", \"europe\", \"usa\"])\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d8885056-fd98-4964-a4a1-8c0344960409", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.share.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.share.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..097cf01bd027a4529e34bfe02bedaea0389efd5d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.share.ipynb @@ -0,0 +1,131 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "3a874676-6b0d-45b1-a227-857a536c5ed2", + "metadata": {}, + "source": [ + "By default, faceted plots will share all axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "615d0765-98c7-4694-8115-a6d1b3557fe7", + "metadata": {}, + "outputs": [], + "source": [ + "p = (\n", + " so.Plot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + " .facet(col=\"species\", row=\"sex\")\n", + " .add(so.Dots())\n", + ")\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "8b75feb1-491e-4031-9fcb-619037bd1bfb", + "metadata": {}, + "source": [ + "Set a coordinate variable to `False` to let each subplot adapt independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c23c570-ca9b-49cc-9aab-7d167218454b", + "metadata": {}, + "outputs": [], + "source": [ + "p.share(x=False, y=False)" + ] + }, + { + "cell_type": "markdown", + "id": "cc46d8d0-7ab9-44c2-8a28-c656fe86c085", + "metadata": {}, + "source": [ + "It's also possible to share only across rows or columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7cb8136b-9aa3-4c48-bd41-fc0e19fa997c", + "metadata": {}, + "outputs": [], + "source": [ + "p.share(x=\"col\", y=\"row\")" + ] + }, + { + "cell_type": "raw", + "id": "91533aba-45ae-4011-b72c-10f5f79e01d0", + "metadata": {}, + "source": [ + "This method is also relevant for paired plots, which have different defaults. In this case, you would need to opt *in* to full sharing (although it may not always make sense):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e2b71770-e520-45b9-b41c-a66431f21e1f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, y=\"flipper_length_mm\")\n", + " .pair(x=[\"bill_length_mm\", \"bill_depth_mm\"])\n", + " .add(so.Dots())\n", + " .share(x=True)\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92c29080-8561-4c90-8581-4d435a5f96b9", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.theme.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.theme.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df98bc456be296829ca769504927bc311607bafc --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Plot.theme.ipynb @@ -0,0 +1,185 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "9252d5a5-8af1-4f99-b799-ee044329fb23", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "anscombe = load_dataset(\"anscombe\")" + ] + }, + { + "cell_type": "raw", + "id": "406f6608-daf2-4d3e-9f2c-1a9e93ecb840", + "metadata": {}, + "source": [ + "The default theme uses the same parameters as :func:`seaborn.set_theme` with no additional arguments:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5e3d639c-1167-48d2-b9b5-c26b7fa12c66", + "metadata": {}, + "outputs": [], + "source": [ + "p = (\n", + " so.Plot(anscombe, \"x\", \"y\", color=\"dataset\")\n", + " .facet(\"dataset\", wrap=2)\n", + " .add(so.Line(), so.PolyFit(order=1))\n", + " .add(so.Dot())\n", + ")\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "e2823a91-47f1-40a8-a150-32f00bcb59ea", + "metadata": {}, + "source": [ + "Pass a dictionary of rc parameters to change the appearance of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "368c8cdb-2e6f-4520-8412-cd1864a6c09b", + "metadata": {}, + "outputs": [], + "source": [ + "p.theme({\"axes.facecolor\": \"w\", \"axes.edgecolor\": \"slategray\"})" + ] + }, + { + "cell_type": "raw", + "id": "637cf0ba-e9b7-4f0f-a628-854e300c4122", + "metadata": {}, + "source": [ + "Many (though not all) mark properties will reflect theme parameters by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9eb330b3-f424-405b-9653-5df9948792d9", + "metadata": {}, + "outputs": [], + "source": [ + "p.theme({\"lines.linewidth\": 4})" + ] + }, + { + "cell_type": "raw", + "id": "0186e852-9c47-4da1-999a-f61f41687dfb", + "metadata": {}, + "source": [ + "Apply seaborn styles by passing in the output of the style functions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48cafbb1-37da-42c7-a20e-b63c0fef4d41", + "metadata": {}, + "outputs": [], + "source": [ + "from seaborn import axes_style\n", + "p.theme(axes_style(\"ticks\"))" + ] + }, + { + "cell_type": "raw", + "id": "bbdecb4b-382a-49f3-8928-16f5f72c39b5", + "metadata": {}, + "source": [ + "Or apply styles that ship with matplotlib:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84a7ac28-798d-4560-bbc8-d214fd6fcada", + "metadata": {}, + "outputs": [], + "source": [ + "from matplotlib import style\n", + "p.theme(style.library[\"fivethirtyeight\"])" + ] + }, + { + "cell_type": "raw", + "id": "e1870ad0-48a0-4fd1-a557-d337979bc845", + "metadata": {}, + "source": [ + "Multiple parameter dictionaries should be passed to the same function call. On Python 3.9+, you can use dictionary union syntax for this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dec4db5b-1b2b-4b9d-97e1-9cf0f20d6b83", + "metadata": {}, + "outputs": [], + "source": [ + "from seaborn import plotting_context\n", + "p.theme(axes_style(\"whitegrid\") | plotting_context(\"talk\"))" + ] + }, + { + "cell_type": "raw", + "id": "7cc09720-887d-463e-a162-1e3ef8a46ad9", + "metadata": {}, + "source": [ + "The default theme for all :class:`Plot` instances can be changed using the :attr:`Plot.config` attribute:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e535ddf-d394-4ce1-8d09-4dc95ca314b4", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot.config.theme.update(axes_style(\"white\"))\n", + "p" + ] + }, + { + "cell_type": "raw", + "id": "2f19f645-3f8d-4044-82e9-4a87165a0078", + "metadata": {}, + "source": [ + "See :ref:`Plot Configuration ` for more details." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Range.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Range.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3e462255fb5887b7d2b0a8dee91194f630e65339 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Range.ipynb @@ -0,0 +1,140 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2923956c-f141-4ecb-ab08-e819099f0fa9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")" + ] + }, + { + "cell_type": "raw", + "id": "576cbc86-f869-47b5-a98f-6ee727287a8b", + "metadata": {}, + "source": [ + "This mark will often be used in the context of a stat transform that adds an errorbar interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f6217b85-7479-49fd-aeda-9f435aa0473a", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"body_mass_g\", y=\"species\", color=\"sex\")\n", + " .add(so.Dot(), so.Agg(), so.Dodge())\n", + " .add(so.Range(), so.Est(errorbar=\"sd\"), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e156ea24-d8b4-4d67-acb5-750034be4dde", + "metadata": {}, + "source": [ + "One feature (or potential gotcha) is that the mark will pick up properties like `linestyle` and `linewidth`; exclude those properties from the relevant layer if this behavior is undesired:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4bb63ebb-7733-4313-844c-cb7613298da3", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"sex\", y=\"body_mass_g\", linestyle=\"species\")\n", + " .facet(\"species\")\n", + " .add(so.Line(marker=\"o\"), so.Agg())\n", + " .add(so.Range(), so.Est(errorbar=\"sd\"))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "5387e049-b343-49ea-a943-7dd9c090f184", + "metadata": {}, + "source": [ + "It's also possible to directly assign the minimum and maximum values for the range:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e795770-4481-4e23-a49b-e828a1f5cbbd", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " penguins\n", + " .rename_axis(index=\"penguin\")\n", + " .pipe(so.Plot, x=\"penguin\", ymin=\"bill_depth_mm\", ymax=\"bill_length_mm\")\n", + " .add(so.Range(), color=\"island\")\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "2191bec6-a02e-48e0-b92c-69c38826049d", + "metadata": {}, + "source": [ + "When `min`/`max` variables are neither computed as part of a transform or explicitly assigned, the range will cover the full extent of the data at each unique observation on the orient axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63c6352e-4ef5-4cff-940e-35fa5804b2c7", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"sex\", y=\"body_mass_g\")\n", + " .facet(\"species\")\n", + " .add(so.Dots(pointsize=6))\n", + " .add(so.Range(linewidth=2))\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c215deb1-e510-4631-b999-737f5f41cae2", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Shift.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Shift.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e33c90c9595b88ec73a489dce07e3b6a9743af1b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Shift.ipynb @@ -0,0 +1,94 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "2605c8d0-5872-4dff-9172-db81fac1cee1", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "penguins = load_dataset(\"penguins\")\n", + "diamonds = load_dataset(\"diamonds\")" + ] + }, + { + "cell_type": "raw", + "id": "e70d701a-cd7c-4b38-aaa0-4729e2be56d9", + "metadata": {}, + "source": [ + "Use this transform to layer multiple marks that would otherwise overlap and be hard to interpret:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ea7a2c4-cb69-4ad0-8ea8-73067b756371", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, \"species\", \"body_mass_g\")\n", + " .add(so.Dots(), so.Jitter())\n", + " .add(so.Range(), so.Perc([25, 75]), so.Shift(x=.2))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "940b87b2-04fb-40ba-a62f-52f461039ab9", + "metadata": {}, + "source": [ + "For y variables with a nominal scale, bear in mind that the axis will be inverted and a positive shift will move downwards:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "54b5f728-4fbc-474a-8865-0f58d0ad9b0b", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, \"carat\", \"clarity\")\n", + " .add(so.Dots(), so.Jitter())\n", + " .add(so.Range(), so.Perc([25, 75]), so.Shift(y=.25))\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "78d9bb6a-ea3d-491e-b43e-25efd386bd59", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Stack.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Stack.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7878db9a6a1516aef8f6dd8fd953c7e9aadbb103 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Stack.ipynb @@ -0,0 +1,89 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "87244f49-8cf2-4668-a556-a8c7828b31bf", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "titanic = load_dataset(\"titanic\").sort_values(\"alive\", ascending=False)" + ] + }, + { + "cell_type": "raw", + "id": "c9a1a7db-f365-4c5f-85ae-1f00e15b0af9", + "metadata": {}, + "source": [ + "This transform applies a vertical shift to eliminate overlap between marks with a baseline, such as :class:`Bar` or :class:`Area`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "07579f71-842d-4dc1-98ab-38652409238d", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot(titanic, x=\"class\", color=\"sex\").add(so.Bar(), so.Count(), so.Stack())" + ] + }, + { + "cell_type": "raw", + "id": "2488a821-3bf1-4bb9-9963-bf726d11925c", + "metadata": {}, + "source": [ + "Stacking can make it much harder to compare values between groups that get shifted, but it can work well when depicting a part-whole relationship:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dcb8ea58-3cf2-455b-b6b7-98b434f2f152", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(titanic, x=\"age\", alpha=\"alive\")\n", + " .facet(\"sex\")\n", + " .add(so.Bars(), so.Hist(binwidth=10), so.Stack())\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b649198f-898e-4103-84bc-d74de71de5a7", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/objects.Text.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Text.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d8f3204af79ea942ba2b13a7022f754ad78497d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/objects.Text.ipynb @@ -0,0 +1,188 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "cd1cdefe-b8c1-40b9-be31-006d52ec9f18", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn.objects as so\n", + "from seaborn import load_dataset\n", + "glue = (\n", + " load_dataset(\"glue\")\n", + " .pivot(index=[\"Model\", \"Encoder\"], columns=\"Task\", values=\"Score\")\n", + " .assign(Average=lambda x: x.mean(axis=1).round(1))\n", + " .sort_values(\"Average\", ascending=False)\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "3e49ffb1-8778-4cd5-80d6-9d7e1438bc9c", + "metadata": {}, + "source": [ + "Add text at x/y locations on the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3bf21068-d39e-436c-8deb-aa1b15aeb2b3", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"SST-2\", y=\"MRPC\", text=\"Model\")\n", + " .add(so.Text())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a4b9a8b2-6603-46db-9ede-3b3fb45e0e64", + "metadata": {}, + "source": [ + "Add bar annotations, horizontally-aligned with `halign`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f68501f0-c868-439e-9485-d71cca86ea47", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"Average\", y=\"Model\", text=\"Average\")\n", + " .add(so.Bar())\n", + " .add(so.Text(color=\"w\", halign=\"right\"))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a9d39479-0afa-477b-8403-fe92a54643c9", + "metadata": {}, + "source": [ + "Fine-tune the alignment using `offset`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5da4a9d-79f3-4c11-bab3-f89da8512ce4", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"Average\", y=\"Model\", text=\"Average\")\n", + " .add(so.Bar())\n", + " .add(so.Text(color=\"w\", halign=\"right\", offset=6))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e9c43798-70d5-42b5-bd91-b85684d1b671", + "metadata": {}, + "source": [ + "Add text above dots, mapping the text color with a third variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2d26ebc-24ac-4531-9ba2-fa03720c58bc", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"SST-2\", y=\"MRPC\", color=\"Encoder\", text=\"Model\")\n", + " .add(so.Dot())\n", + " .add(so.Text(valign=\"bottom\"))\n", + "\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "f31aaa38-6728-4299-8422-8762c52c9857", + "metadata": {}, + "source": [ + "Map the text alignment for better use of space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf4bbf0c-0c5f-4c31-b971-720ea8910918", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"RTE\", y=\"MRPC\", color=\"Encoder\", text=\"Model\")\n", + " .add(so.Dot())\n", + " .add(so.Text(), halign=\"Encoder\")\n", + " .scale(halign={\"LSTM\": \"left\", \"Transformer\": \"right\"})\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a5de35a6-1ccf-4958-8013-edd9ed1cd4b0", + "metadata": {}, + "source": [ + "Use additional matplotlib parameters to control the appearance of the text:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9c4be188-1614-4c19-9bd7-b07e986f6a23", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"RTE\", y=\"MRPC\", color=\"Encoder\", text=\"Model\")\n", + " .add(so.Dot())\n", + " .add(so.Text({\"fontweight\": \"bold\"}), halign=\"Encoder\")\n", + " .scale(halign={\"LSTM\": \"left\", \"Transformer\": \"right\"})\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95fb7aee-090a-4415-917c-b5258d2b298b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/pairplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/pairplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7aa8d45b866a2b278e39705892ae0766986018b9 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/pairplot.ipynb @@ -0,0 +1,225 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"ticks\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The simplest invocation uses :func:`scatterplot` for each pairing of the variables and :func:`histplot` for the marginal plots along the diagonal:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.pairplot(penguins)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a ``hue`` variable adds a semantic mapping and changes the default marginal plot to a layered kernel density estimate (KDE):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's possible to force marginal histograms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, hue=\"species\", diag_kind=\"hist\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``kind`` parameter determines both the diagonal and off-diagonal plotting style. Several options are available, including using :func:`kdeplot` to draw KDEs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or :func:`histplot` to draw both bivariate and univariate histograms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, kind=\"hist\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``markers`` parameter applies a style mapping on the off-diagonal axes. Currently, it will be redundant with the ``hue`` variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, hue=\"species\", markers=[\"o\", \"s\", \"D\"])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As with other figure-level functions, the size of the figure is controlled by setting the ``height`` of each individual subplot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, height=1.5)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use ``vars`` or ``x_vars`` and ``y_vars`` to select the variables to plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(\n", + " penguins,\n", + " x_vars=[\"bill_length_mm\", \"bill_depth_mm\", \"flipper_length_mm\"],\n", + " y_vars=[\"bill_length_mm\", \"bill_depth_mm\"],\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Set ``corner=True`` to plot only the lower triangle:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins, corner=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``plot_kws`` and ``diag_kws`` parameters accept dicts of keyword arguments to customize the off-diagonal and diagonal plots, respectively:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(\n", + " penguins,\n", + " plot_kws=dict(marker=\"+\", linewidth=1),\n", + " diag_kws=dict(fill=False),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The return object is the underlying :class:`PairGrid`, which can be used to further customize the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.pairplot(penguins, diag_kind=\"kde\")\n", + "g.map_lower(sns.kdeplot, levels=4, color=\".2\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/plotting_context.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/plotting_context.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..43009c2aa76f06672caef9e3ff1c5815a981b59b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/plotting_context.ipynb @@ -0,0 +1,110 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "perceived-worry", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns" + ] + }, + { + "cell_type": "markdown", + "id": "seventh-volleyball", + "metadata": {}, + "source": [ + "Calling with no arguments will return the current defaults for the parameters that get scaled:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "roman-villa", + "metadata": { + "tags": [ + "show-output" + ] + }, + "outputs": [], + "source": [ + "sns.plotting_context()" + ] + }, + { + "cell_type": "markdown", + "id": "handled-texas", + "metadata": {}, + "source": [ + "Calling with the name of a predefined style will show those values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "distant-caribbean", + "metadata": { + "tags": [ + "show-output" + ] + }, + "outputs": [], + "source": [ + "sns.plotting_context(\"talk\")" + ] + }, + { + "cell_type": "markdown", + "id": "lightweight-anime", + "metadata": {}, + "source": [ + "Use the function as a context manager to temporarily change the parameter values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "contemporary-hampshire", + "metadata": {}, + "outputs": [], + "source": [ + "with sns.plotting_context(\"talk\"):\n", + " sns.lineplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "accompanied-brisbane", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/pointplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/pointplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9c227fcc373be935cbb8fae079f94d99814f47c1 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/pointplot.ipynb @@ -0,0 +1,142 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "43f842ee-44c9-476b-ab08-112d23e2effb", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "9aa5bc8a-03cd-4792-906d-7e7318c2cecc", + "metadata": {}, + "source": [ + "Group by a categorical varaible and plot aggregated values, with confidence intervals:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9a865fec-c034-4000-938d-b7cd89157495", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"penguins\")\n", + "sns.pointplot(data=df, x=\"island\", y=\"body_mass_g\")" + ] + }, + { + "cell_type": "markdown", + "id": "a0002e29-0ad6-41c7-b66d-c80bb1844924", + "metadata": {}, + "source": [ + "Add a second layer of grouping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f27011f1-0e3c-4dc4-818e-4a77930977b9", + "metadata": {}, + "outputs": [], + "source": [ + "sns.pointplot(data=df, x=\"island\", y=\"body_mass_g\", hue=\"sex\")" + ] + }, + { + "cell_type": "markdown", + "id": "a63681f6-e692-400f-b9fe-0d9fd0521398", + "metadata": {}, + "source": [ + "Adjust the artists along the categorical axis to reduce overplotting:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8f94d069-c5f4-4579-a4bf-6d755962d48d", + "metadata": {}, + "outputs": [], + "source": [ + "sns.pointplot(data=df, x=\"sex\", y=\"bill_depth_mm\", hue=\"island\", dodge=True)" + ] + }, + { + "cell_type": "markdown", + "id": "51523904-3b42-4818-9de6-52dc30090e56", + "metadata": {}, + "source": [ + "Use the error bars to show the standard deviation rather than a confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "386b25eb-7ab7-4a1d-9498-cef3e4fd3e6b", + "metadata": {}, + "outputs": [], + "source": [ + "sns.pointplot(data=df, x=\"island\", y=\"body_mass_g\", errorbar=\"sd\")" + ] + }, + { + "cell_type": "markdown", + "id": "41253d65-b3be-4aab-87a2-be34e66a2d7c", + "metadata": {}, + "source": [ + "Customize the appearance of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "50b14810-2299-479c-b6c5-0fd10c4ed3de", + "metadata": {}, + "outputs": [], + "source": [ + "sns.pointplot(\n", + " data=df, x=\"body_mass_g\", y=\"island\",\n", + " errorbar=(\"pi\", 100), capsize=.4, join=False, color=\".5\",\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94d6718d-2cfe-44f4-88e5-f47461d7d51f", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/regplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/regplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2b1ef937a6e51b201f3148dff569cd38b9511ede --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/regplot.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "611aed40-d120-4fbf-b1e6-9712ed8167fc", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import seaborn as sns\n", + "sns.set_theme()\n", + "mpg = sns.load_dataset(\"mpg\")" + ] + }, + { + "cell_type": "raw", + "id": "61bebade-0c45-4e99-9567-dfe0bc2dc6e1", + "metadata": {}, + "source": [ + "Plot the relationship between two variables in a DataFrame:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f4107db-d89b-46ad-a4c6-9ba1181b2122", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"weight\", y=\"acceleration\")" + ] + }, + { + "cell_type": "raw", + "id": "146225d0-2e38-4b92-8e64-6d7f78311f40", + "metadata": {}, + "source": [ + "Fit a higher-order polynomial regression to capture nonlinear trends:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ba29488c-8a45-4387-bfb1-71a584fa1b3d", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"weight\", y=\"mpg\", order=2)" + ] + }, + { + "cell_type": "raw", + "id": "0ad71f54-b362-465e-8780-1d8b99ff2d51", + "metadata": {}, + "source": [ + "Alternatively, fit a log-linear regression:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aae2acaa-ed07-4568-97d2-8665603eb7eb", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"displacement\", y=\"mpg\", logx=True)" + ] + }, + { + "cell_type": "raw", + "id": "eef37c8a-7190-465c-b963-076ec17e1b3a", + "metadata": {}, + "source": [ + "Or use a locally-weighted (LOWESS) smoother:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9276c469-72ea-4c36-9b7c-19ecba564376", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"horsepower\", y=\"mpg\", lowess=True)" + ] + }, + { + "cell_type": "raw", + "id": "d18f1534-598e-4f08-91dd-0c4020f30b00", + "metadata": {}, + "source": [ + "Fit a logistic regression when the response variable is binary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "79ec9180-10c9-4910-9713-dcd1fdd266be", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(x=mpg[\"weight\"], y=mpg[\"origin\"].eq(\"usa\").rename(\"from_usa\"), logistic=True)" + ] + }, + { + "cell_type": "raw", + "id": "2e165783-d505-4acb-a20a-d22a49965c2b", + "metadata": {}, + "source": [ + "Fit a robust regression to downweight the influence of outliers:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd5cf940-de8f-4230-8b04-5c650418f3c4", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"horsepower\", y=\"weight\", robust=True)" + ] + }, + { + "cell_type": "raw", + "id": "e7d43c4e-e819-4634-8269-cbf5de4a2f24", + "metadata": {}, + "source": [ + "Disable the confidence interval for faster plotting:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b21384ff-6395-4fa9-b7da-63e8a951d8a5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"weight\", y=\"horsepower\", ci=None)" + ] + }, + { + "cell_type": "raw", + "id": "06e979ac-f418-4ead-bde1-ec684d0545ff", + "metadata": {}, + "source": [ + "Jitter the scatterplot when the `x` variable is discrete:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "543a8ace-a89e-4af9-bf6d-a8722ebdfac5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"cylinders\", y=\"weight\", x_jitter=.15)" + ] + }, + { + "cell_type": "raw", + "id": "c3042eb2-0933-4886-9bff-88c276371516", + "metadata": {}, + "source": [ + "Or aggregate over the distinct `x` values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "158c6e36-8858-415b-b78c-7d8d79879ee5", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"cylinders\", y=\"acceleration\", x_estimator=np.mean, order=2)" + ] + }, + { + "cell_type": "raw", + "id": "d9cefe7a-7f86-4353-95da-d7e72e65d4fc", + "metadata": {}, + "source": [ + "With a continuous `x` variable, bin and then aggregate:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c48829b-2e3b-4e6b-9b1d-5ba69f713617", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(data=mpg, x=\"weight\", y=\"mpg\", x_bins=np.arange(2000, 5500, 250), order=2)" + ] + }, + { + "cell_type": "raw", + "id": "dfe5a36a-20b0-4e69-b986-fede8e1506cc", + "metadata": {}, + "source": [ + "Customize the appearance of various elements:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df689a39-c5e1-4f7b-a8f9-8ffb09b95238", + "metadata": {}, + "outputs": [], + "source": [ + "sns.regplot(\n", + " data=mpg, x=\"weight\", y=\"horsepower\",\n", + " ci=99, marker=\"x\", color=\".3\", line_kws=dict(color=\"r\"),\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d625745b-3706-447b-9224-88e6cb1eb7f9", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/relplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/relplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..42ef09a324b4f8b64c957cf53a2e078bf33c9122 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/relplot.ipynb @@ -0,0 +1,262 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "These examples will illustrate only some of the functionality that :func:`relplot` is capable of. For more information, consult the examples for :func:`scatterplot` and :func:`lineplot`, which are used when ``kind=\"scatter\"`` or ``kind=\"line\"``, respectively." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme(style=\"ticks\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To illustrate ``kind=\"scatter\"`` (the default style of plot), we will use the \"tips\" dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "tips.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning ``x`` and ``y`` and any semantic mapping variables will draw a single plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"day\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a ``col`` variable creates a faceted figure with multiple subplots arranged across the columns of the grid:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"day\", col=\"time\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Different variables can be assigned to facet on both the columns and rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"day\", col=\"time\", row=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When the variable assigned to ``col`` has many levels, it can be \"wrapped\" across multiple rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\", col=\"day\", col_wrap=2)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning multiple semantic variables can show multi-dimensional relationships, but be mindful to avoid making an overly-complicated plot." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\", col=\"time\",\n", + " hue=\"time\", size=\"size\", style=\"sex\",\n", + " palette=[\"b\", \"r\"], sizes=(10, 100)\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When there is a natural continuity to one of the variables, it makes more sense to show lines instead of points. To draw the figure using :func:`lineplot`, set ``kind=\"line\"``. We will illustrate this effect with the \"fmri dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fmri = sns.load_dataset(\"fmri\")\n", + "fmri.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Using ``kind=\"line\"`` offers the same flexibility for semantic mappings as ``kind=\"scatter\"``, but :func:`lineplot` transforms the data more before plotting. Observations are sorted by their ``x`` value, and repeated observations are aggregated. By default, the resulting plot shows the mean and 95% CI for each unit" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, x=\"timepoint\", y=\"signal\", col=\"region\",\n", + " hue=\"event\", style=\"event\", kind=\"line\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The size and shape of the figure is parametrized by the ``height`` and ``aspect`` ratio of each individual facet:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri,\n", + " x=\"timepoint\", y=\"signal\",\n", + " hue=\"event\", style=\"event\", col=\"region\",\n", + " height=4, aspect=.7, kind=\"line\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The object returned by :func:`relplot` is always a :class:`FacetGrid`, which has several methods that allow you to quickly tweak the title, labels, and other aspects of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.relplot(\n", + " data=fmri,\n", + " x=\"timepoint\", y=\"signal\",\n", + " hue=\"event\", style=\"event\", col=\"region\",\n", + " height=4, aspect=.7, kind=\"line\"\n", + ")\n", + "(g.map(plt.axhline, y=0, color=\".7\", dashes=(2, 1), zorder=0)\n", + " .set_axis_labels(\"Timepoint\", \"Percent signal change\")\n", + " .set_titles(\"Region: {col_name} cortex\")\n", + " .tight_layout(w_pad=0))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It is also possible to use wide-form data with :func:`relplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_wide = sns.load_dataset(\"flights\").pivot(\"year\", \"month\", \"passengers\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Faceting is not an option in this case, but the plot will still take advantage of the external legend offered by :class:`FacetGrid`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=flights_wide, kind=\"line\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/residplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/residplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..287462f2e0e361ce6eddbe03d3d41454325ab9e0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/residplot.ipynb @@ -0,0 +1,113 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "776f8271-21ed-4707-a1ad-09d8c63ae95a", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme()\n", + "mpg = sns.load_dataset(\"mpg\")" + ] + }, + { + "cell_type": "raw", + "id": "85717971-adc9-45b0-9c4b-3f022d96179c", + "metadata": {}, + "source": [ + "Pass `x` and `y` to see a scatter plot of the residuals after fitting a simple regression model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5aea4655-fb51-4b51-b41d-4769de50e956", + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(data=mpg, x=\"weight\", y=\"displacement\")" + ] + }, + { + "cell_type": "raw", + "id": "175b6287-9240-493f-94bc-9d18258e952b", + "metadata": {}, + "source": [ + "Structure in the residual plot can reveal a violation of linear regression assumptions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "39aa84c2-d623-44be-9b0b-746f52b55fd4", + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\")" + ] + }, + { + "cell_type": "raw", + "id": "bd9641e4-8df5-4751-b261-6443888fbbfe", + "metadata": {}, + "source": [ + "Remove higher-order trends to test whether that stabilizes the residuals:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03a68199-1272-464b-8b85-7a309c22a4a6", + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\", order=2)" + ] + }, + { + "cell_type": "raw", + "id": "b17750af-0393-4c53-8057-bf95d0de821a", + "metadata": {}, + "source": [ + "Adding a LOWESS curve can help reveal or emphasize structure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "494359bd-47b2-426e-9c35-14b5351eec93", + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\", lowess=True, line_kws=dict(color=\"r\"))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/rugplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/rugplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ce5da483c24b253bff75bf7e2255b30cc6527612 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/rugplot.ipynb @@ -0,0 +1,137 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add a rug along one of the axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns; sns.set_theme()\n", + "tips = sns.load_dataset(\"tips\")\n", + "sns.kdeplot(data=tips, x=\"total_bill\")\n", + "sns.rugplot(data=tips, x=\"total_bill\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add a rug along both axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\")\n", + "sns.rugplot(data=tips, x=\"total_bill\", y=\"tip\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Represent a third variable with hue mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\")\n", + "sns.rugplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Draw a taller rug:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\")\n", + "sns.rugplot(data=tips, x=\"total_bill\", y=\"tip\", height=.1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Put the rug outside the axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\")\n", + "sns.rugplot(data=tips, x=\"total_bill\", y=\"tip\", height=-.02, clip_on=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Show the density of a larger dataset using thinner lines and alpha blending:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "diamonds = sns.load_dataset(\"diamonds\")\n", + "sns.scatterplot(data=diamonds, x=\"carat\", y=\"price\", s=5)\n", + "sns.rugplot(data=diamonds, x=\"carat\", y=\"price\", lw=1, alpha=.005)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/scatterplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/scatterplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..973a67d690c7487ef4f290ea5338a41edb1d9e6f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/scatterplot.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "These examples will use the \"tips\" dataset, which has a mixture of numeric and categorical variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "tips.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Passing long-form data and assigning ``x`` and ``y`` will draw a scatter plot between two variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a variable to ``hue`` will map its levels to the color of the points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning the same variable to ``style`` will also vary the markers and create a more accessible plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\", style=\"time\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning ``hue`` and ``style`` to different variables will vary colors and markers independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"day\", style=\"time\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If the variable assigned to ``hue`` is numeric, the semantic mapping will be quantitative and use a different default palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Pass the name of a categorical palette or explicit colors (as a Python list of dictionary) to force categorical mapping of the ``hue`` variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\", palette=\"deep\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If there are a large number of unique numeric values, the legend will show a representative, evenly-spaced set:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tip_rate = tips.eval(\"tip / total_bill\").rename(\"tip_rate\")\n", + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=tip_rate)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A numeric variable can also be assigned to ``size`` to apply a semantic mapping to the areas of the points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\", size=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Control the range of marker areas with ``sizes``, and set ``lengend=\"full\"`` to force every unique value to appear in the legend:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\", size=\"size\",\n", + " sizes=(20, 200), legend=\"full\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Pass a tuple of values or a :class:`matplotlib.colors.Normalize` object to ``hue_norm`` to control the quantitative hue mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\", size=\"size\",\n", + " sizes=(20, 200), hue_norm=(0, 7), legend=\"full\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Control the specific markers used to map the ``style`` variable by passing a Python list or dictionary of marker codes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "markers = {\"Lunch\": \"s\", \"Dinner\": \"X\"}\n", + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", style=\"time\", markers=markers)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Additional keyword arguments are passed to :meth:`matplotlib.axes.Axes.scatter`, allowing you to directly set the attributes of the plot that are not semantically mapped:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", s=100, color=\".2\", marker=\"+\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The previous examples used a long-form dataset. When working with wide-form data, each column will be plotted against its index using both ``hue`` and ``style`` mapping:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "index = pd.date_range(\"1 1 2000\", periods=100, freq=\"m\", name=\"date\")\n", + "data = np.random.randn(100, 4).cumsum(axis=0)\n", + "wide_df = pd.DataFrame(data, index, [\"a\", \"b\", \"c\", \"d\"])\n", + "sns.scatterplot(data=wide_df)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use :func:`relplot` to combine :func:`scatterplot` and :class:`FacetGrid`. This allows grouping within additional categorical variables, and plotting them across multiple subplots.\n", + "\n", + "Using :func:`relplot` is safer than using :class:`FacetGrid` directly, as it ensures synchronization of the semantic mappings across facets." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\",\n", + " col=\"time\", hue=\"day\", style=\"day\",\n", + " kind=\"scatter\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/set_context.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/set_context.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..97c8679cb79858a493d30863607c2ea1587acfce --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/set_context.ipynb @@ -0,0 +1,104 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "thorough-equipment", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns" + ] + }, + { + "cell_type": "markdown", + "id": "canadian-protection", + "metadata": {}, + "source": [ + "Call the function with the name of a context to set the default for all plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "freelance-leonard", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"notebook\")\n", + "sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "studied-adventure", + "metadata": {}, + "source": [ + "You can independently scale the font elements relative to the current context:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "irish-digest", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"notebook\", font_scale=1.25)\n", + "sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "fourth-technical", + "metadata": {}, + "source": [ + "It is also possible to override some of the parameters with specific values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "advance-request", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"notebook\", rc={\"lines.linewidth\": 3})\n", + "sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "compatible-string", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/set_style.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/set_style.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7780bcf95a616c6aac4e7102fdc4486d1956b389 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/set_style.ipynb @@ -0,0 +1,85 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "practical-announcement", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns" + ] + }, + { + "cell_type": "markdown", + "id": "suffering-emerald", + "metadata": {}, + "source": [ + "Call the function with the name of a seaborn style to set the default for all plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "collaborative-struggle", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"whitegrid\")\n", + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "defensive-surgery", + "metadata": {}, + "source": [ + "You can also selectively override seaborn's default parameter values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "coastal-sydney", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"darkgrid\", {\"grid.color\": \".6\", \"grid.linestyle\": \":\"})\n", + "sns.lineplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bright-october", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/set_theme.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/set_theme.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c2820ab9cd0cebe8bc8de93eeaef342ca5256ac6 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/set_theme.ipynb @@ -0,0 +1,161 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "flush-block", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "id": "remarkable-confirmation", + "metadata": {}, + "source": [ + "By default, seaborn plots will be made with the current values of the matplotlib rcParams:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "viral-highway", + "metadata": {}, + "outputs": [], + "source": [ + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "hungarian-poster", + "metadata": {}, + "source": [ + "Calling this function with no arguments will activate seaborn's \"default\" theme:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "front-february", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme()\n", + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "daily-mills", + "metadata": {}, + "source": [ + "Note that this will take effect for *all* matplotlib plots, including those not made using seaborn:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "essential-replica", + "metadata": {}, + "outputs": [], + "source": [ + "plt.bar([\"A\", \"B\", \"C\"], [1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "naughty-edgar", + "metadata": {}, + "source": [ + "The seaborn theme is decomposed into several distinct sets of parameters that you can control independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "latin-conversion", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme(style=\"whitegrid\", palette=\"pastel\")\n", + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "durable-cycling", + "metadata": {}, + "source": [ + "Pass `None` to preserve the current values for a given set of parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "blessed-chuck", + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme(style=\"white\", palette=None)\n", + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "markdown", + "id": "present-writing", + "metadata": {}, + "source": [ + "You can also override any seaborn parameters or define additional parameters that are part of the matplotlib rc system but not included in the seaborn themes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "floppy-effectiveness", + "metadata": {}, + "outputs": [], + "source": [ + "custom_params = {\"axes.spines.right\": False, \"axes.spines.top\": False}\n", + "sns.set_theme(style=\"ticks\", rc=custom_params)\n", + "sns.barplot(x=[\"A\", \"B\", \"C\"], y=[1, 3, 2])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "large-transfer", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/stripplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/stripplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..386ad117fd9f092e7112cbda0a0e83f7a349d07c --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/stripplot.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a single numeric variable shows its univariate distribution with points randomly \"jittered\" on the other axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.stripplot(data=tips, x=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a second variable splits the strips of points to compare categorical levels of that variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Show vertically-oriented strips by swapping the assignment of the categorical and numerical variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"day\", y=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Prior to version 0.12, the levels of the categorical variable had different colors by default. To get the same effect, assign the `hue` variable explicitly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"day\", legend=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or you can assign a distinct variable to `hue` to show a multidimensional relationship:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If the `hue` variable is numeric, it will be mapped with a quantitative palette by default (note that this was not the case prior to version 0.12):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use `palette` to control the color mapping, including forcing a categorical mapping by passing the name of a qualitative palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"size\", palette=\"deep\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the different levels of the `hue` variable are intermingled in each strip, but setting `dodge=True` will split them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\", dodge=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The random jitter can be disabled by setting `jitter=False`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\", dodge=True, jitter=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If plotting in wide-form mode, each numeric column of the dataframe will be mapped to both `x` and `hue`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To change the orientation while in wide-form mode, pass `orient` explicitly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, orient=\"h\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The `orient` parameter is also useful when both axis variables are numeric, as it will resolve ambiguity about which dimension to group (and jitter) along:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(data=tips, x=\"total_bill\", y=\"size\", orient=\"h\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the categorical variable will be mapped to discrete indices with a fixed scale (0, 1, ...), even when it is numeric:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(\n", + " data=tips.query(\"size in [2, 3, 5]\"),\n", + " x=\"total_bill\", y=\"size\", orient=\"h\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To disable this behavior and use the original scale of the variable, set `native_scale=True`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(\n", + " data=tips.query(\"size in [2, 3, 5]\"),\n", + " x=\"total_bill\", y=\"size\", orient=\"h\",\n", + " native_scale=True,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Further visual customization can be achieved by passing keyword arguments for :func:`matplotlib.axes.Axes.scatter`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.stripplot(\n", + " data=tips, x=\"total_bill\", y=\"day\", hue=\"time\",\n", + " jitter=False, s=20, marker=\"D\", linewidth=1, alpha=.1,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To make a plot with multiple facets, it is safer to use :func:`catplot` than to work with :class:`FacetGrid` directly, because :func:`catplot` will ensure that the categorical and hue variables are properly synchronized in each facet:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"time\", y=\"total_bill\", hue=\"sex\", col=\"day\", aspect=.5)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/swarmplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/swarmplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c3341c5172978adfbd865cd64c19c9756b6b7073 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/swarmplot.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a single numeric variable shows its univariate distribution with points adjusted along on the other axis such that they don't overlap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.swarmplot(data=tips, x=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a second variable splits the groups of points to compare categorical levels of that variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Show vertically-oriented swarms by swapping the assignment of the categorical and numerical variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"day\", y=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Prior to version 0.12, the levels of the categorical variable had different colors by default. To get the same effect, assign the `hue` variable explicitly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"day\", legend=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or you can assign a distinct variable to `hue` to show a multidimensional relationship:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If the `hue` variable is numeric, it will be mapped with a quantitative palette by default (note that this was not the case prior to version 0.12):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Use `palette` to control the color mapping, including forcing a categorical mapping by passing the name of a qualitative palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"size\", palette=\"deep\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the different levels of the `hue` variable are intermingled in each swarm, but setting `dodge=True` will split them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\", dodge=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The \"orientation\" of the plot (defined as the direction along which quantitative relationships are preserved) is usually inferred automatically. But in ambiguous cases, such as when both axis variables are numeric, it can be specified:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"size\", orient=\"h\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When the local density of points is too high, they will be forced to overlap in the \"gutters\" of each swarm and a warning will be issued. Decreasing the size of the points can help to avoid this problem:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(data=tips, x=\"total_bill\", y=\"size\", orient=\"h\", size=3)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the categorical variable will be mapped to discrete indices with a fixed scale (0, 1, ...), even when it is numeric:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(\n", + " data=tips.query(\"size in [2, 3, 5]\"),\n", + " x=\"total_bill\", y=\"size\", orient=\"h\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To disable this behavior and use the original scale of the variable, set `native_scale=True` (notice how this also changes the order of the variables on the y axis):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(\n", + " data=tips.query(\"size in [2, 3, 5]\"),\n", + " x=\"total_bill\", y=\"size\", orient=\"h\",\n", + " native_scale=True,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Further visual customization can be achieved by passing keyword arguments for :func:`matplotlib.axes.Axes.scatter`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.swarmplot(\n", + " data=tips, x=\"total_bill\", y=\"day\",\n", + " marker=\"x\", linewidth=1, \n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To make a plot with multiple facets, it is safer to use :func:`catplot` with `kind=\"swarm\"` than to work with :class:`FacetGrid` directly, because :func:`catplot` will ensure that the categorical and hue variables are properly synchronized in each facet:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, kind=\"swarm\",\n", + " x=\"time\", y=\"total_bill\", hue=\"sex\", col=\"day\",\n", + " aspect=.5\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_docstrings/violinplot.ipynb b/testbed/mwaskom__seaborn/doc/_docstrings/violinplot.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..35e1246672dbec03cbfbd0cf70bdc06c7051211d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_docstrings/violinplot.ipynb @@ -0,0 +1,193 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "cc19031c-bc2f-4294-95ce-3a2d9b86f44d", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "sns.set_theme(style=\"whitegrid\")" + ] + }, + { + "cell_type": "markdown", + "id": "863c03b1-63e2-4d60-a3a4-4693afab4b5b", + "metadata": {}, + "source": [ + "Draw a single horizontal boxplot, assigning the data directly to the coordinate variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "27d578fb-1c20-4d31-b93d-b1b4a053992b", + "metadata": {}, + "outputs": [], + "source": [ + "df = sns.load_dataset(\"titanic\")\n", + "sns.violinplot(x=df[\"age\"])" + ] + }, + { + "cell_type": "markdown", + "id": "aeea380b-405e-4762-8ede-db57f5549ca5", + "metadata": {}, + "source": [ + "Group by a categorical variable, referencing columns in a dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b851b2c-0011-4cff-8719-11f6138c44e7", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"age\", y=\"class\")" + ] + }, + { + "cell_type": "markdown", + "id": "c9a99aa4-2da0-42fa-879a-0c3b264803f4", + "metadata": {}, + "source": [ + "Draw vertical violins, grouped by two variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4810c8e7-0864-496f-8e86-a6527369b9e1", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"class\", y=\"age\", hue=\"alive\")" + ] + }, + { + "cell_type": "markdown", + "id": "973e6617-5720-428d-a0ac-447e76aa9fde", + "metadata": {}, + "source": [ + "Draw split violins to take up less space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2ae35376-5272-496c-afec-c60a3426f1bf", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"deck\", y=\"age\", hue=\"alive\", split=True)" + ] + }, + { + "cell_type": "markdown", + "id": "f291d4a2-41bc-4eb0-813d-7a1ceacc0cb0", + "metadata": {}, + "source": [ + "Prevent the density from smoothing beyond the limits of the data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "82556de0-3756-426c-a591-9af6ed6c45d4", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"age\", y=\"alive\", cut=0)" + ] + }, + { + "cell_type": "markdown", + "id": "6f351f71-1db3-4c5a-948c-9e1dbc550234", + "metadata": {}, + "source": [ + "Use a narrower bandwidth to reduce the amount of smoothing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d17e1e3-e0f4-4d2c-ac6e-aec42ed75390", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"age\", y=\"alive\", bw=.15)" + ] + }, + { + "cell_type": "markdown", + "id": "c4aaeb60-6c1b-4337-91ce-d6b744a3dd90", + "metadata": {}, + "source": [ + "Represent every observation inside the distribution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "00b5f00e-a515-4e53-9d73-d13b045cd4c8", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"age\", y=\"embark_town\", inner=\"stick\")" + ] + }, + { + "cell_type": "markdown", + "id": "01622556-9df8-4af1-b36c-9bc5f6b6099e", + "metadata": {}, + "source": [ + "Use a different scaling rule for normalizing the density:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "be59f17e-824e-4a8c-a0e1-a27874a05df6", + "metadata": {}, + "outputs": [], + "source": [ + "sns.violinplot(data=df, x=\"age\", y=\"embark_town\", scale=\"count\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fdda9a33-37f3-43fd-b02d-1ff414657a37", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_static/copybutton.js b/testbed/mwaskom__seaborn/doc/_static/copybutton.js new file mode 100644 index 0000000000000000000000000000000000000000..0a7db6d6dcde9b549c33f1e35684bba2b851262d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/copybutton.js @@ -0,0 +1,59 @@ +// originally taken from scikit-learn's Sphinx theme +$(document).ready(function() { + /* Add a [>>>] button on the top-right corner of code samples to hide + * the >>> and ... prompts and the output and thus make the code + * copyable. + * Note: This JS snippet was taken from the official python.org + * documentation site.*/ + var div = $('.highlight-python .highlight,' + + '.highlight-python3 .highlight,' + + '.highlight-pycon .highlight') + var pre = div.find('pre'); + + // get the styles from the current theme + pre.parent().parent().css('position', 'relative'); + var hide_text = 'Hide the prompts and output'; + var show_text = 'Show the prompts and output'; + var border_width = pre.css('border-top-width'); + var border_style = pre.css('border-top-style'); + var border_color = pre.css('border-top-color'); + var button_styles = { + 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0', + 'border-color': border_color, 'border-style': border_style, + 'border-width': border_width, 'color': border_color, 'text-size': '75%', + 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em' + } + + // create and add the button to all the code blocks that contain >>> + div.each(function(index) { + var jthis = $(this); + if (jthis.find('.gp').length > 0) { + var button = $('>>>'); + button.css(button_styles) + button.attr('title', hide_text); + jthis.prepend(button); + } + // tracebacks (.gt) contain bare text elements that need to be + // wrapped in a span to work with .nextUntil() (see later) + jthis.find('pre:has(.gt)').contents().filter(function() { + return ((this.nodeType == 3) && (this.data.trim().length > 0)); + }).wrap(''); + }); + + // define the behavior of the button when it's clicked + $('.copybutton').toggle( + function() { + var button = $(this); + button.parent().find('.go, .gp, .gt').hide(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden'); + button.css('text-decoration', 'line-through'); + button.attr('title', show_text); + }, + function() { + var button = $(this); + button.parent().find('.go, .gp, .gt').show(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible'); + button.css('text-decoration', 'none'); + button.attr('title', hide_text); + }); +}); diff --git a/testbed/mwaskom__seaborn/doc/_static/css/custom.css b/testbed/mwaskom__seaborn/doc/_static/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..3ecccfdb1d058df02534919f7c9d4c7b1c8f6e5e --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/css/custom.css @@ -0,0 +1,113 @@ +/**** Overriding theme defaults ****/ + +html[data-theme=light]{ + --pst-color-primary: rgb(52, 54, 99); + --pst-color-secondary: rgb(107, 161, 174); + --pst-color-link: rgb(74, 105, 145); + --pst-color-inline-code: rgb(96, 141, 130); +} + +:root { + --pst-font-size-h1: 38px; + --pst-font-size-h2: 32px; + --pst-font-size-h3: 27px; + --pst-font-size-h4: 22px; + --pst-font-size-h5: 18px; + --pst-font-size-h6: 15px; + +} + +/* Syntax highlighting */ + +/* string literals */ +html[data-theme=light] .highlight .s2 { + color: rgb(74, 105, 145); + font-weight: normal; +} +/* number literals */ +html[data-theme=light] .highlight .mi { + color: rgb(136, 97, 153); + font-weight: normal; +} +html[data-theme=light] .highlight .mf { + color: rgb(136, 97, 153); + font-weight: normal; +} +/* operators */ +html[data-theme=light] .highlight .o { + color: rgb(219, 164, 117); + font-weight: bold; +} +/* builtins */ +html[data-theme=light] .highlight .kc { + color: rgb(107, 161, 174); + font-weight: bold; +} + +/* Use full page width without sidebars */ +.bd-content { + max-width: 100%; + flex-grow: 1; +} + +/* Function signature customization */ +dt { + font-weight: 500; + color: rgb(52, 54, 99); +} + +span.default_value { + color: rgb(124, 141, 138); +} + +/* highlight over function signature after link */ +dt:target, span.highlighted { + background-color: #fdebba; +} + +/* *********************************************************************** */ + +/* --- Badges for categorizing release notes --- */ + +.label, +.badge { + display: inline-block; + padding: 2px 4px; + font-size: 11.844px; + /* font-weight: bold; */ + line-height: 13px; + color: #ffffff; + vertical-align: baseline; + white-space: nowrap; + /* text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); */ + background-color: #999999; +} +.badge { + padding-left: 9px; + padding-right: 9px; + -webkit-border-radius: 9px; + -moz-border-radius: 9px; + border-radius: 9px; + opacity: 70%; +} +.badge-api { + background-color: #c44e52; +} +.badge-defaults { + background-color: #dd8452; +} +.badge-docs { + background-color: #8172b3; +} +.badge-feature { + background-color: #55a868; +} +.badge-enhancement { + background-color: #4c72b0; +} +.badge-fix { + background-color: #ccb974; +} +.badge-build { + background-color: #937860; +} diff --git a/testbed/mwaskom__seaborn/doc/_static/favicon.ico b/testbed/mwaskom__seaborn/doc/_static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..fac1e28c2cfa95cc0afc82b9b334c7c0ad94a9d4 Binary files /dev/null and b/testbed/mwaskom__seaborn/doc/_static/favicon.ico differ diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-mark-darkbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-mark-darkbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..4b06364224efe302a6a5a40cf582a85f6ae9ef27 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-mark-darkbg.svg @@ -0,0 +1,4946 @@ + + + + + + + + + 2020-09-07T14:13:59.975140 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-mark-lightbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-mark-lightbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..1405269edcdf349c2abf925de7a5dc97c72b66d1 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-mark-lightbg.svg @@ -0,0 +1,4946 @@ + + + + + + + + + 2020-09-07T14:13:57.855925 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-tall-darkbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-tall-darkbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..3d7d91020621fe9632c5c9efdc4acffb0338ff08 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-tall-darkbg.svg @@ -0,0 +1,5206 @@ + + + + + + + + + 2020-09-07T14:14:01.511527 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-tall-lightbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-tall-lightbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..eb52f345c084c9185856bd5075de3563145106fd --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-tall-lightbg.svg @@ -0,0 +1,5206 @@ + + + + + + + + + 2020-09-07T14:13:59.334522 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-wide-darkbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-wide-darkbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..83b0ef8289bf2b80d74180bfa6973912b57437d0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-wide-darkbg.svg @@ -0,0 +1,5216 @@ + + + + + + + + + 2020-09-07T14:14:00.795540 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_static/logo-wide-lightbg.svg b/testbed/mwaskom__seaborn/doc/_static/logo-wide-lightbg.svg new file mode 100644 index 0000000000000000000000000000000000000000..57f1f71345ae273c98fdc9fb615ce0df82a5a68d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_static/logo-wide-lightbg.svg @@ -0,0 +1,5216 @@ + + + + + + + + + 2020-09-07T14:13:58.676334 + image/svg+xml + + + Matplotlib v3.3.1, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/mwaskom__seaborn/doc/_templates/autosummary/base.rst b/testbed/mwaskom__seaborn/doc/_templates/autosummary/base.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7556ebf7b06631c6d12c823ccaa7ca3c50a1d5a --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/autosummary/base.rst @@ -0,0 +1,5 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. auto{{ objtype }}:: {{ objname }} diff --git a/testbed/mwaskom__seaborn/doc/_templates/autosummary/class.rst b/testbed/mwaskom__seaborn/doc/_templates/autosummary/class.rst new file mode 100644 index 0000000000000000000000000000000000000000..c27ca38eca8a9971d7d13edc3374d14925d8d432 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/autosummary/class.rst @@ -0,0 +1,30 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + + {% block methods %} + .. automethod:: __init__ + + {% if methods %} + .. rubric:: Methods + + .. autosummary:: + :toctree: ./ + {% for item in methods %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} + + {% block attributes %} + {% if attributes %} + .. rubric:: Attributes + + .. autosummary:: + {% for item in attributes %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} diff --git a/testbed/mwaskom__seaborn/doc/_templates/autosummary/object.rst b/testbed/mwaskom__seaborn/doc/_templates/autosummary/object.rst new file mode 100644 index 0000000000000000000000000000000000000000..d4fd5208b66817944b75d7f45a463732b4678be2 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/autosummary/object.rst @@ -0,0 +1,5 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} diff --git a/testbed/mwaskom__seaborn/doc/_templates/autosummary/plot.rst b/testbed/mwaskom__seaborn/doc/_templates/autosummary/plot.rst new file mode 100644 index 0000000000000000000000000000000000000000..aae1c66570476f274e33840f804d2fd26f283c90 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/autosummary/plot.rst @@ -0,0 +1,69 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + +{% block methods %} + +Methods +~~~~~~~ + +.. rubric:: Specification methods + +.. autosummary:: + :toctree: ./ + :nosignatures: + + ~Plot.add + ~Plot.scale + +.. rubric:: Subplot methods + +.. autosummary:: + :toctree: ./ + :nosignatures: + + ~Plot.facet + ~Plot.pair + +.. rubric:: Customization methods + +.. autosummary:: + :toctree: ./ + :nosignatures: + + ~Plot.layout + ~Plot.label + ~Plot.limit + ~Plot.share + ~Plot.theme + +.. rubric:: Integration methods + +.. autosummary:: + :toctree: ./ + :nosignatures: + + ~Plot.on + +.. rubric:: Output methods + +.. autosummary:: + :toctree: ./ + :nosignatures: + + ~Plot.plot + ~Plot.save + ~Plot.show + +{% endblock %} + +.. _plot_config: + +Configuration +~~~~~~~~~~~~~ + +The :class:`Plot` object's default behavior can be configured through its :attr:`Plot.config` attribute. Notice that this is a property of the class, not a method on an instance. + +.. include:: ../docstrings/objects.Plot.config.rst diff --git a/testbed/mwaskom__seaborn/doc/_templates/autosummary/scale.rst b/testbed/mwaskom__seaborn/doc/_templates/autosummary/scale.rst new file mode 100644 index 0000000000000000000000000000000000000000..a89d76f52be2f89f3dfde9b326670dfb61191d02 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/autosummary/scale.rst @@ -0,0 +1,9 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + + .. automethod:: tick + + .. automethod:: label diff --git a/testbed/mwaskom__seaborn/doc/_templates/layout.html b/testbed/mwaskom__seaborn/doc/_templates/layout.html new file mode 100644 index 0000000000000000000000000000000000000000..6706964fada1d679d444d64a63ce3b20e82fb079 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/layout.html @@ -0,0 +1,26 @@ +{% extends "!layout.html" %} + +{%- block footer %} + +{%- endblock %} diff --git a/testbed/mwaskom__seaborn/doc/_templates/version.html b/testbed/mwaskom__seaborn/doc/_templates/version.html new file mode 100644 index 0000000000000000000000000000000000000000..e17aac83063b4376164b16cd8a653e261970464b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_templates/version.html @@ -0,0 +1,3 @@ + diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/Makefile b/testbed/mwaskom__seaborn/doc/_tutorial/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..73168b3edc11a92838559d4cc49be0d6b9092ab8 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/Makefile @@ -0,0 +1,10 @@ +rst_files := $(patsubst %.ipynb,../tutorial/%.rst,$(wildcard *.ipynb)) +export MPLBACKEND := module://matplotlib_inline.backend_inline + +tutorial: ${rst_files} + +../tutorial/%.rst: %.ipynb + ../tools/nb_to_doc.py $*.ipynb ../tutorial + +clean: + rm -rf ../tutorial diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/aesthetics.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/aesthetics.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..63f819877957ea957aaefba49f7503e873bd8b43 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/aesthetics.ipynb @@ -0,0 +1,426 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _aesthetics_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Controlling figure aesthetics\n", + "=============================\n" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Drawing attractive figures is important. When making figures for yourself, as you explore a dataset, it's nice to have plots that are pleasant to look at. Visualizations are also central to communicating quantitative insights to an audience, and in that setting it's even more necessary to have figures that catch the attention and draw a viewer in.\n", + "\n", + "Matplotlib is highly customizable, but it can be hard to know what settings to tweak to achieve an attractive plot. Seaborn comes with a number of customized themes and a high-level interface for controlling the look of matplotlib figures." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "np.random.seed(sum(map(ord, \"aesthetics\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Let's define a simple function to plot some offset sine waves, which will help us see the different stylistic parameters we can tweak." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def sinplot(n=10, flip=1):\n", + " x = np.linspace(0, 14, 100)\n", + " for i in range(1, n + 1):\n", + " plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This is what the plot looks like with matplotlib defaults:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To switch to seaborn defaults, simply call the :func:`set_theme` function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme()\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "(Note that in versions of seaborn prior to 0.8, :func:`set_theme` was called on import. On later versions, it must be explicitly invoked).\n", + "\n", + "Seaborn splits matplotlib parameters into two independent groups. The first group sets the aesthetic style of the plot, and the second scales various elements of the figure so that it can be easily incorporated into different contexts.\n", + "\n", + "The interface for manipulating these parameters are two pairs of functions. To control the style, use the :func:`axes_style` and :func:`set_style` functions. To scale the plot, use the :func:`plotting_context` and :func:`set_context` functions. In both cases, the first function returns a dictionary of parameters and the second sets the matplotlib defaults.\n", + "\n", + ".. _axes_style:\n", + "\n", + "Seaborn figure styles\n", + "---------------------\n", + "\n", + "There are five preset seaborn themes: ``darkgrid``, ``whitegrid``, ``dark``, ``white``, and ``ticks``. They are each suited to different applications and personal preferences. The default theme is ``darkgrid``. As mentioned above, the grid helps the plot serve as a lookup table for quantitative information, and the white-on grey helps to keep the grid from competing with lines that represent data. The ``whitegrid`` theme is similar, but it is better suited to plots with heavy data elements:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"whitegrid\")\n", + "data = np.random.normal(size=(20, 6)) + np.arange(6) / 2\n", + "sns.boxplot(data=data);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "For many plots, (especially for settings like talks, where you primarily want to use figures to provide impressions of patterns in the data), the grid is less necessary." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"dark\")\n", + "sinplot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"white\")\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Sometimes you might want to give a little extra structure to the plots, which is where ticks come in handy:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"ticks\")\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _remove_spines:\n", + "\n", + "Removing axes spines\n", + "--------------------\n", + "\n", + "Both the ``white`` and ``ticks`` styles can benefit from removing the top and right axes spines, which are not needed. The seaborn function :func:`despine` can be called to remove them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sinplot()\n", + "sns.despine()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Some plots benefit from offsetting the spines away from the data, which can also be done when calling :func:`despine`. When the ticks don't cover the whole range of the axis, the ``trim`` parameter will limit the range of the surviving spines." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f, ax = plt.subplots()\n", + "sns.violinplot(data=data)\n", + "sns.despine(offset=10, trim=True);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can also control which spines are removed with additional arguments to :func:`despine`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"whitegrid\")\n", + "sns.boxplot(data=data, palette=\"deep\")\n", + "sns.despine(left=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Temporarily setting figure style\n", + "--------------------------------\n", + "\n", + "Although it's easy to switch back and forth, you can also use the :func:`axes_style` function in a ``with`` statement to temporarily set plot parameters. This also allows you to make figures with differently-styled axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f = plt.figure(figsize=(6, 6))\n", + "gs = f.add_gridspec(2, 2)\n", + "\n", + "with sns.axes_style(\"darkgrid\"):\n", + " ax = f.add_subplot(gs[0, 0])\n", + " sinplot(6)\n", + " \n", + "with sns.axes_style(\"white\"):\n", + " ax = f.add_subplot(gs[0, 1])\n", + " sinplot(6)\n", + "\n", + "with sns.axes_style(\"ticks\"):\n", + " ax = f.add_subplot(gs[1, 0])\n", + " sinplot(6)\n", + "\n", + "with sns.axes_style(\"whitegrid\"):\n", + " ax = f.add_subplot(gs[1, 1])\n", + " sinplot(6)\n", + " \n", + "f.tight_layout()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Overriding elements of the seaborn styles\n", + "-----------------------------------------\n", + "\n", + "If you want to customize the seaborn styles, you can pass a dictionary of parameters to the ``rc`` argument of :func:`axes_style` and :func:`set_style`. Note that you can only override the parameters that are part of the style definition through this method. (However, the higher-level :func:`set_theme` function takes a dictionary of any matplotlib parameters).\n", + "\n", + "If you want to see what parameters are included, you can just call the function with no arguments, which will return the current settings:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.axes_style()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can then set different versions of these parameters:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_style(\"darkgrid\", {\"axes.facecolor\": \".9\"})\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _plotting_context:\n", + "\n", + "Scaling plot elements\n", + "---------------------\n", + "\n", + "A separate set of parameters control the scale of plot elements, which should let you use the same code to make plots that are suited for use in settings where larger or smaller plots are appropriate.\n", + "\n", + "First let's reset the default parameters by calling :func:`set_theme`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The four preset contexts, in order of relative size, are ``paper``, ``notebook``, ``talk``, and ``poster``. The ``notebook`` style is the default, and was used in the plots above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"paper\")\n", + "sinplot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"talk\")\n", + "sinplot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"poster\")\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Most of what you now know about the style functions should transfer to the context functions.\n", + "\n", + "You can call :func:`set_context` with one of these names to set the parameters, and you can override the parameters by providing a dictionary of parameter values.\n", + "\n", + "You can also independently scale the size of the font elements when changing the context. (This option is also available through the top-level :func:`set` function)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_context(\"notebook\", font_scale=1.5, rc={\"lines.linewidth\": 2.5})\n", + "sinplot()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Similarly, you can temporarily control the scale of figures nested under a ``with`` statement.\n", + "\n", + "Both the style and the context can be quickly configured with the :func:`set` function. This function also sets the default color palette, but that will be covered in more detail in the :ref:`next section ` of the tutorial." + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/axis_grids.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/axis_grids.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..da3cc587e57d23787aa015b3bc2bf7ca52cc7f6d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/axis_grids.ipynb @@ -0,0 +1,553 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _grid_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Building structured multi-plot grids\n", + "====================================\n" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When exploring multi-dimensional data, a useful approach is to draw multiple instances of the same plot on different subsets of your dataset. This technique is sometimes called either \"lattice\" or \"trellis\" plotting, and it is related to the idea of `\"small multiples\" `_. It allows a viewer to quickly extract a large amount of information about a complex dataset. Matplotlib offers good support for making figures with multiple axes; seaborn builds on top of this to directly link the structure of the plot to the structure of your dataset.\n", + "\n", + "The :doc:`figure-level ` functions are built on top of the objects discussed in this chapter of the tutorial. In most cases, you will want to work with those functions. They take care of some important bookkeeping that synchronizes the multiple plots in each grid. This chapter explains how the underlying objects work, which may be useful for advanced applications." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "sns.set_theme(style=\"ticks\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "import numpy as np\n", + "np.random.seed(sum(map(ord, \"axis_grids\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _facet_grid:\n", + "\n", + "Conditional small multiples\n", + "---------------------------\n", + "\n", + "The :class:`FacetGrid` class is useful when you want to visualize the distribution of a variable or the relationship between multiple variables separately within subsets of your dataset. A :class:`FacetGrid` can be drawn with up to three dimensions: ``row``, ``col``, and ``hue``. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.\n", + "\n", + "Each of :func:`relplot`, :func:`displot`, :func:`catplot`, and :func:`lmplot` use this object internally, and they return the object when they are finished so that it can be used for further tweaking.\n", + "\n", + "The class is used by initializing a :class:`FacetGrid` object with a dataframe and the names of the variables that will form the row, column, or hue dimensions of the grid. These variables should be categorical or discrete, and then the data at each level of the variable will be used for a facet along that axis. For example, say we wanted to examine differences between lunch and dinner in the ``tips`` dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "g = sns.FacetGrid(tips, col=\"time\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Initializing the grid like this sets up the matplotlib figure and axes, but doesn't draw anything on them.\n", + "\n", + "The main approach for visualizing data on this grid is with the :meth:`FacetGrid.map` method. Provide it with a plotting function and the name(s) of variable(s) in the dataframe to plot. Let's look at the distribution of tips in each of these subsets, using a histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"time\")\n", + "g.map(sns.histplot, \"tip\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This function will draw the figure and annotate the axes, hopefully producing a finished plot in one step. To make a relational plot, just pass multiple variable names. You can also provide keyword arguments, which will be passed to the plotting function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"sex\", hue=\"smoker\")\n", + "g.map(sns.scatterplot, \"total_bill\", \"tip\", alpha=.7)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "There are several options for controlling the look of the grid that can be passed to the class constructor." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, row=\"smoker\", col=\"time\", margin_titles=True)\n", + "g.map(sns.regplot, \"size\", \"total_bill\", color=\".3\", fit_reg=False, x_jitter=.1)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Note that ``margin_titles`` isn't formally supported by the matplotlib API, and may not work well in all cases. In particular, it currently can't be used with a legend that lies outside of the plot.\n", + "\n", + "The size of the figure is set by providing the height of *each* facet, along with the aspect ratio:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"day\", height=4, aspect=.5)\n", + "g.map(sns.barplot, \"sex\", \"total_bill\", order=[\"Male\", \"Female\"])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate ``*_order`` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ordered_days = tips.day.value_counts().index\n", + "g = sns.FacetGrid(tips, row=\"day\", row_order=ordered_days,\n", + " height=1.7, aspect=4,)\n", + "g.map(sns.kdeplot, \"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Any seaborn color palette (i.e., something that can be passed to :func:`color_palette()`) can be provided. You can also use a dictionary that maps the names of values in the ``hue`` variable to valid matplotlib colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pal = dict(Lunch=\"seagreen\", Dinner=\".7\")\n", + "g = sns.FacetGrid(tips, hue=\"time\", palette=pal, height=5)\n", + "g.map(sns.scatterplot, \"total_bill\", \"tip\", s=100, alpha=.5)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If you have many levels of one variable, you can plot it along the columns but \"wrap\" them so that they span multiple rows. When doing this, you cannot use a ``row`` variable." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "attend = sns.load_dataset(\"attention\").query(\"subject <= 12\")\n", + "g = sns.FacetGrid(attend, col=\"subject\", col_wrap=4, height=2, ylim=(0, 10))\n", + "g.map(sns.pointplot, \"solutions\", \"score\", order=[1, 2, 3], color=\".3\", errorbar=None)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Once you've drawn a plot using :meth:`FacetGrid.map` (which can be called multiple times), you may want to adjust some aspects of the plot. There are also a number of methods on the :class:`FacetGrid` object for manipulating the figure at a higher level of abstraction. The most general is :meth:`FacetGrid.set`, and there are other more specialized methods like :meth:`FacetGrid.set_axis_labels`, which respects the fact that interior facets do not have axis labels. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with sns.axes_style(\"white\"):\n", + " g = sns.FacetGrid(tips, row=\"sex\", col=\"smoker\", margin_titles=True, height=2.5)\n", + "g.map(sns.scatterplot, \"total_bill\", \"tip\", color=\"#334488\")\n", + "g.set_axis_labels(\"Total bill (US Dollars)\", \"Tip\")\n", + "g.set(xticks=[10, 30, 50], yticks=[2, 6, 10])\n", + "g.figure.subplots_adjust(wspace=.02, hspace=.02)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "For even more customization, you can work directly with the underling matplotlib ``Figure`` and ``Axes`` objects, which are stored as member attributes at ``figure`` and ``axes_dict``, respectively. When making a figure without row or column faceting, you can also use the ``ax`` attribute to directly access the single axes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, col=\"smoker\", margin_titles=True, height=4)\n", + "g.map(plt.scatter, \"total_bill\", \"tip\", color=\"#338844\", edgecolor=\"white\", s=50, lw=1)\n", + "for ax in g.axes_dict.values():\n", + " ax.axline((0, 0), slope=.2, c=\".2\", ls=\"--\", zorder=0)\n", + "g.set(xlim=(0, 60), ylim=(0, 14))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _custom_map_func:\n", + "\n", + "Using custom functions\n", + "----------------------\n", + "\n", + "You're not limited to existing matplotlib and seaborn functions when using :class:`FacetGrid`. However, to work properly, any function you use must follow a few rules:\n", + "\n", + "1. It must plot onto the \"currently active\" matplotlib ``Axes``. This will be true of functions in the ``matplotlib.pyplot`` namespace, and you can call :func:`matplotlib.pyplot.gca` to get a reference to the current ``Axes`` if you want to work directly with its methods.\n", + "2. It must accept the data that it plots in positional arguments. Internally, :class:`FacetGrid` will pass a ``Series`` of data for each of the named positional arguments passed to :meth:`FacetGrid.map`.\n", + "3. It must be able to accept ``color`` and ``label`` keyword arguments, and, ideally, it will do something useful with them. In most cases, it's easiest to catch a generic dictionary of ``**kwargs`` and pass it along to the underlying plotting function.\n", + "\n", + "Let's look at minimal example of a function you can plot with. This function will just take a single vector of data for each facet:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from scipy import stats\n", + "def quantile_plot(x, **kwargs):\n", + " quantiles, xr = stats.probplot(x, fit=False)\n", + " plt.scatter(xr, quantiles, **kwargs)\n", + " \n", + "g = sns.FacetGrid(tips, col=\"sex\", height=4)\n", + "g.map(quantile_plot, \"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If we want to make a bivariate plot, you should write the function so that it accepts the x-axis variable first and the y-axis variable second:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def qqplot(x, y, **kwargs):\n", + " _, xr = stats.probplot(x, fit=False)\n", + " _, yr = stats.probplot(y, fit=False)\n", + " plt.scatter(xr, yr, **kwargs)\n", + " \n", + "g = sns.FacetGrid(tips, col=\"smoker\", height=4)\n", + "g.map(qqplot, \"total_bill\", \"tip\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Because :func:`matplotlib.pyplot.scatter` accepts ``color`` and ``label`` keyword arguments and does the right thing with them, we can add a hue facet without any difficulty:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(tips, hue=\"time\", col=\"sex\", height=4)\n", + "g.map(qqplot, \"total_bill\", \"tip\")\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Sometimes, though, you'll want to map a function that doesn't work the way you expect with the ``color`` and ``label`` keyword arguments. In this case, you'll want to explicitly catch them and handle them in the logic of your custom function. For example, this approach will allow use to map :func:`matplotlib.pyplot.hexbin`, which otherwise does not play well with the :class:`FacetGrid` API:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def hexbin(x, y, color, **kwargs):\n", + " cmap = sns.light_palette(color, as_cmap=True)\n", + " plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs)\n", + "\n", + "with sns.axes_style(\"dark\"):\n", + " g = sns.FacetGrid(tips, hue=\"time\", col=\"time\", height=4)\n", + "g.map(hexbin, \"total_bill\", \"tip\", extent=[0, 50, 0, 10]);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _pair_grid:\n", + "\n", + "Plotting pairwise data relationships\n", + "------------------------------------\n", + "\n", + ":class:`PairGrid` also allows you to quickly draw a grid of small subplots using the same plot type to visualize data in each. In a :class:`PairGrid`, each row and column is assigned to a different variable, so the resulting plot shows each pairwise relationship in the dataset. This style of plot is sometimes called a \"scatterplot matrix\", as this is the most common way to show each relationship, but :class:`PairGrid` is not limited to scatterplots.\n", + "\n", + "It's important to understand the differences between a :class:`FacetGrid` and a :class:`PairGrid`. In the former, each facet shows the same relationship conditioned on different levels of other variables. In the latter, each plot shows a different relationship (although the upper and lower triangles will have mirrored plots). Using :class:`PairGrid` can give you a very quick, very high-level summary of interesting relationships in your dataset.\n", + "\n", + "The basic usage of the class is very similar to :class:`FacetGrid`. First you initialize the grid, then you pass plotting function to a ``map`` method and it will be called on each subplot. There is also a companion function, :func:`pairplot` that trades off some flexibility for faster plotting.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iris = sns.load_dataset(\"iris\")\n", + "g = sns.PairGrid(iris)\n", + "g.map(sns.scatterplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's possible to plot a different function on the diagonal to show the univariate distribution of the variable in each column. Note that the axis ticks won't correspond to the count or density axis of this plot, though." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(iris)\n", + "g.map_diag(sns.histplot)\n", + "g.map_offdiag(sns.scatterplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A very common way to use this plot colors the observations by a separate categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(iris, hue=\"species\")\n", + "g.map_diag(sns.histplot)\n", + "g.map_offdiag(sns.scatterplot)\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default every numeric column in the dataset is used, but you can focus on particular relationships if you want." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(iris, vars=[\"sepal_length\", \"sepal_width\"], hue=\"species\")\n", + "g.map(sns.scatterplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to use a different function in the upper and lower triangles to emphasize different aspects of the relationship." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(iris)\n", + "g.map_upper(sns.scatterplot)\n", + "g.map_lower(sns.kdeplot)\n", + "g.map_diag(sns.kdeplot, lw=3, legend=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The square grid with identity relationships on the diagonal is actually just a special case, and you can plot with different variables in the rows and columns." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(tips, y_vars=[\"tip\"], x_vars=[\"total_bill\", \"size\"], height=4)\n", + "g.map(sns.regplot, color=\".3\")\n", + "g.set(ylim=(-1, 11), yticks=[0, 5, 10])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Of course, the aesthetic attributes are configurable. For instance, you can use a different palette (say, to show an ordering of the ``hue`` variable) and pass keyword arguments into the plotting functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(tips, hue=\"size\", palette=\"GnBu_d\")\n", + "g.map(plt.scatter, s=50, edgecolor=\"white\")\n", + "g.add_legend()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ":class:`PairGrid` is flexible, but to take a quick look at a dataset, it can be easier to use :func:`pairplot`. This function uses scatterplots and histograms by default, although a few other kinds will be added (currently, you can also plot regression plots on the off-diagonals and KDEs on the diagonal)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(iris, hue=\"species\", height=2.5)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can also control the aesthetics of the plot with keyword arguments, and it returns the :class:`PairGrid` instance for further tweaking." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.pairplot(iris, hue=\"species\", palette=\"Set2\", diag_kind=\"kde\", height=2.5)" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/categorical.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/categorical.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..77f6527b5680ccc46318b4dacc75f2775cd34892 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/categorical.ipynb @@ -0,0 +1,542 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _categorical_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Visualizing categorical data\n", + "============================\n", + " \n", + "In the :ref:`relational plot tutorial ` we saw how to use different visual representations to show the relationship between multiple variables in a dataset. In the examples, we focused on cases where the main relationship was between two numerical variables. If one of the main variables is \"categorical\" (divided into discrete groups) it may be helpful to use a more specialized approach to visualization.\n", + "\n", + "In seaborn, there are several different ways to visualize a relationship involving categorical data. Similar to the relationship between :func:`relplot` and either :func:`scatterplot` or :func:`lineplot`, there are two ways to make these plots. There are a number of axes-level functions for plotting categorical data in different ways and a figure-level interface, :func:`catplot`, that gives unified higher-level access to them.\n", + "\n", + "It's helpful to think of the different categorical plot kinds as belonging to three different families, which we'll discuss in detail below. They are:\n", + "\n", + "Categorical scatterplots:\n", + "\n", + "- :func:`stripplot` (with ``kind=\"strip\"``; the default)\n", + "- :func:`swarmplot` (with ``kind=\"swarm\"``)\n", + "\n", + "Categorical distribution plots:\n", + "\n", + "- :func:`boxplot` (with ``kind=\"box\"``)\n", + "- :func:`violinplot` (with ``kind=\"violin\"``)\n", + "- :func:`boxenplot` (with ``kind=\"boxen\"``)\n", + "\n", + "Categorical estimate plots:\n", + "\n", + "- :func:`pointplot` (with ``kind=\"point\"``)\n", + "- :func:`barplot` (with ``kind=\"bar\"``)\n", + "- :func:`countplot` (with ``kind=\"count\"``)\n", + "\n", + "These families represent the data using different levels of granularity. When deciding which to use, you'll have to think about the question that you want to answer. The unified API makes it easy to switch between different kinds and see your data from several perspectives.\n", + "\n", + "In this tutorial, we'll mostly focus on the figure-level interface, :func:`catplot`. Remember that this function is a higher-level interface each of the functions above, so we'll reference them when we show each kind of plot, keeping the more verbose kind-specific API documentation at hand." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme(style=\"ticks\", color_codes=True)\n", + "np.random.seed(sum(map(ord, \"categorical\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Categorical scatterplots\n", + "------------------------\n", + "\n", + "The default representation of the data in :func:`catplot` uses a scatterplot. There are actually two different categorical scatter plots in seaborn. They take different approaches to resolving the main challenge in representing categorical data with a scatter plot, which is that all of the points belonging to one category would fall on the same position along the axis corresponding to the categorical variable. The approach used by :func:`stripplot`, which is the default \"kind\" in :func:`catplot` is to adjust the positions of points on the categorical axis with a small amount of random \"jitter\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``jitter`` parameter controls the magnitude of jitter or disables it altogether:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\", jitter=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The second approach adjusts the points along the categorical axis using an algorithm that prevents them from overlapping. It can give a better representation of the distribution of observations, although it only works well for relatively small datasets. This kind of plot is sometimes called a \"beeswarm\" and is drawn in seaborn by :func:`swarmplot`, which is activated by setting ``kind=\"swarm\"`` in :func:`catplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\", kind=\"swarm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Similar to the relational plots, it's possible to add another dimension to a categorical plot by using a ``hue`` semantic. (The categorical plots do not currently support ``size`` or ``style`` semantics). Each different categorical plotting function handles the ``hue`` semantic differently. For the scatter plots, it is only necessary to change the color of the points:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\", hue=\"sex\", kind=\"swarm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Unlike with numerical data, it is not always obvious how to order the levels of the categorical variable along its axis. In general, the seaborn categorical plotting functions try to infer the order of categories from the data. If your data have a pandas ``Categorical`` datatype, then the default order of the categories can be set there. If the variable passed to the categorical axis looks numerical, the levels will be sorted. But the data are still treated as categorical and drawn at ordinal positions on the categorical axes (specifically, at 0, 1, ...) even when numbers are used to label them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips.query(\"size != 3\"), x=\"size\", y=\"total_bill\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The other option for choosing a default ordering is to take the levels of the category as they appear in the dataset. The ordering can also be controlled on a plot-specific basis using the ``order`` parameter. This can be important when drawing multiple categorical plots in the same figure, which we'll see more of below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"smoker\", y=\"tip\", order=[\"No\", \"Yes\"])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "We've referred to the idea of \"categorical axis\". In these examples, that's always corresponded to the horizontal axis. But it's often helpful to put the categorical variable on the vertical axis (particularly when the category names are relatively long or there are many categories). To do this, swap the assignment of variables to axes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"total_bill\", y=\"day\", hue=\"time\", kind=\"swarm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Comparing distributions\n", + "-----------------------\n", + "\n", + "As the size of the dataset grows, categorical scatter plots become limited in the information they can provide about the distribution of values within each category. When this happens, there are several approaches for summarizing the distributional information in ways that facilitate easy comparisons across the category levels.\n", + "\n", + "Boxplots\n", + "^^^^^^^^\n", + "\n", + "The first is the familiar :func:`boxplot`. This kind of plot shows the three quartile values of the distribution along with extreme values. The \"whiskers\" extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. This means that each value in the boxplot corresponds to an actual observation in the data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\", kind=\"box\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When adding a ``hue`` semantic, the box for each level of the semantic variable is moved along the categorical axis so they don't overlap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, x=\"day\", y=\"total_bill\", hue=\"smoker\", kind=\"box\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This behavior is called \"dodging\" and is turned on by default because it is assumed that the semantic variable is nested within the main categorical variable. If that's not the case, you can disable the dodging:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n", + "sns.catplot(\n", + " data=tips, x=\"day\", y=\"total_bill\", hue=\"weekend\",\n", + " kind=\"box\", dodge=False,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A related function, :func:`boxenplot`, draws a plot that is similar to a box plot but optimized for showing more information about the shape of the distribution. It is best suited for larger datasets:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "diamonds = sns.load_dataset(\"diamonds\")\n", + "sns.catplot(\n", + " data=diamonds.sort_values(\"color\"),\n", + " x=\"color\", y=\"price\", kind=\"boxen\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Violinplots\n", + "^^^^^^^^^^^\n", + "\n", + "A different approach is a :func:`violinplot`, which combines a boxplot with the kernel density estimation procedure described in the :ref:`distributions ` tutorial:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\", kind=\"violin\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This approach uses the kernel density estimate to provide a richer description of the distribution of values. Additionally, the quartile and whisker values from the boxplot are shown inside the violin. The downside is that, because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, x=\"total_bill\", y=\"day\", hue=\"sex\",\n", + " kind=\"violin\", bw=.15, cut=0,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to \"split\" the violins when the hue parameter has only two levels, which can allow for a more efficient use of space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, x=\"day\", y=\"total_bill\", hue=\"sex\",\n", + " kind=\"violin\", split=True,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Finally, there are several options for the plot that is drawn on the interior of the violins, including ways to show each individual observation instead of the summary boxplot values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, x=\"day\", y=\"total_bill\", hue=\"sex\",\n", + " kind=\"violin\", inner=\"stick\", split=True, palette=\"pastel\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It can also be useful to combine :func:`swarmplot` or :func:`stripplot` with a box plot or violin plot to show each observation along with a summary of the distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.catplot(data=tips, x=\"day\", y=\"total_bill\", kind=\"violin\", inner=None)\n", + "sns.swarmplot(data=tips, x=\"day\", y=\"total_bill\", color=\"k\", size=3, ax=g.ax)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Estimating central tendency\n", + "---------------------------\n", + "\n", + "For other applications, rather than showing the distribution within each category, you might want to show an estimate of the central tendency of the values. Seaborn has two main ways to show this information. Importantly, the basic API for these functions is identical to that for the ones discussed above.\n", + "\n", + "Bar plots\n", + "^^^^^^^^^\n", + "\n", + "A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the :func:`barplot` function operates on a full dataset and applies a function to obtain the estimate (taking the mean by default). When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate, which is plotted using error bars:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "titanic = sns.load_dataset(\"titanic\")\n", + "sns.catplot(data=titanic, x=\"sex\", y=\"survived\", hue=\"class\", kind=\"bar\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default error bars show 95% confidence intervals, but (starting in v0.12), it is possible to select from a number of other representations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=titanic, x=\"age\", y=\"deck\", errorbar=(\"pi\", 95), kind=\"bar\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it's easy to do so with the :func:`countplot` function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=titanic, x=\"deck\", kind=\"count\", palette=\"ch:.25\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Both :func:`barplot` and :func:`countplot` can be invoked with all of the options discussed above, along with others that are demonstrated in the detailed documentation for each function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=titanic, y=\"deck\", hue=\"class\", kind=\"count\",\n", + " palette=\"pastel\", edgecolor=\".6\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Point plots\n", + "^^^^^^^^^^^\n", + "\n", + "An alternative style for visualizing the same information is offered by the :func:`pointplot` function. This function also encodes the value of the estimate with height on the other axis, but rather than showing a full bar, it plots the point estimate and confidence interval. Additionally, :func:`pointplot` connects points from the same ``hue`` category. This makes it easy to see how the main relationship is changing as a function of the hue semantic, because your eyes are quite good at picking up on differences of slopes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=titanic, x=\"sex\", y=\"survived\", hue=\"class\", kind=\"point\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "While the categorical functions lack the ``style`` semantic of the relational functions, it can still be a good idea to vary the marker and/or linestyle along with the hue to make figures that are maximally accessible and reproduce well in black and white:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=titanic, x=\"class\", y=\"survived\", hue=\"sex\",\n", + " palette={\"male\": \"g\", \"female\": \"m\"},\n", + " markers=[\"^\", \"o\"], linestyles=[\"-\", \"--\"],\n", + " kind=\"point\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Showing additional dimensions\n", + "-----------------------------\n", + "\n", + "Just like :func:`relplot`, the fact that :func:`catplot` is built on a :class:`FacetGrid` means that it is easy to add faceting variables to visualize higher-dimensional relationships:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(\n", + " data=tips, x=\"day\", y=\"total_bill\", hue=\"smoker\",\n", + " kind=\"swarm\", col=\"time\", aspect=.7,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "For further customization of the plot, you can use the methods on the :class:`FacetGrid` object that it returns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.catplot(\n", + " data=titanic,\n", + " x=\"fare\", y=\"embark_town\", row=\"class\",\n", + " kind=\"box\", orient=\"h\",\n", + " sharex=False, margin_titles=True,\n", + " height=1.5, aspect=4,\n", + ")\n", + "g.set(xlabel=\"Fare\", ylabel=\"\")\n", + "g.set_titles(row_template=\"{row_name} class\")\n", + "for ax in g.axes.flat:\n", + " ax.xaxis.set_major_formatter('${x:.0f}')" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/color_palettes.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/color_palettes.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5b43e766c01d23d33e3c45337c99728f346f24e3 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/color_palettes.ipynb @@ -0,0 +1,1004 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "raw_mimetype": "text/restructuredtext" + }, + "source": [ + ".. _palette_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Choosing color palettes\n", + "=======================\n", + "\n", + "Seaborn makes it easy to use colors that are well-suited to the characteristics of your data and your visualization goals. This chapter discusses both the general principles that should guide your choices and the tools in seaborn that help you quickly find the best solution for a given application." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib as mpl\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme(style=\"white\", rc={\"xtick.major.pad\": 1, \"ytick.major.pad\": 1})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "np.random.seed(sum(map(ord, \"palettes\")))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "# Add colormap display methods to matplotlib colormaps.\n", + "# These are forthcoming in matplotlib 3.4, but, the matplotlib display\n", + "# method includes the colormap name, which is redundant.\n", + "def _repr_png_(self):\n", + " \"\"\"Generate a PNG representation of the Colormap.\"\"\"\n", + " import io\n", + " from PIL import Image\n", + " import numpy as np\n", + " IMAGE_SIZE = (400, 50)\n", + " X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))\n", + " pixels = self(X, bytes=True)\n", + " png_bytes = io.BytesIO()\n", + " Image.fromarray(pixels).save(png_bytes, format='png')\n", + " return png_bytes.getvalue()\n", + " \n", + "def _repr_html_(self):\n", + " \"\"\"Generate an HTML representation of the Colormap.\"\"\"\n", + " import base64\n", + " png_bytes = self._repr_png_()\n", + " png_base64 = base64.b64encode(png_bytes).decode('ascii')\n", + " return ('')\n", + " \n", + "import matplotlib as mpl\n", + "mpl.colors.Colormap._repr_png_ = _repr_png_\n", + "mpl.colors.Colormap._repr_html_ = _repr_html_" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "General principles for using color in plots\n", + "-------------------------------------------\n", + "\n", + "Components of color\n", + "~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Because of the way our eyes work, a particular color can be defined using three components. We usually program colors in a computer by specifying their RGB values, which set the intensity of the red, green, and blue channels in a display. But for analyzing the perceptual attributes of a color, it's better to think in terms of *hue*, *saturation*, and *luminance* channels.\n", + "\n", + "Hue is the component that distinguishes \"different colors\" in a non-technical sense. It's property of color that leads to first-order names like \"red\" and \"blue\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "sns.husl_palette(8, s=.7)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Saturation (or chroma) is the *colorfulness*. Two colors with different hues will look more distinct when they have more saturation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "c = sns.color_palette(\"muted\")[0]\n", + "sns.blend_palette([sns.desaturate(c, 0), c], 8)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "And lightness corresponds to how much light is emitted (or reflected, for printed colors), ranging from black to white:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "sns.blend_palette([\".1\", c, \".95\"], 8)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Vary hue to distinguish categories\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "When you want to represent multiple categories in a plot, you typically should vary the color of the elements. Consider this simple example: in which of these two plots is it easier to count the number of triangular points?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "n = 45\n", + "rng = np.random.default_rng(200)\n", + "x = rng.uniform(0, 1, n * 2)\n", + "y = rng.uniform(0, 1, n * 2)\n", + "a = np.concatenate([np.zeros(n * 2 - 10), np.ones(10)])\n", + "\n", + "f, axs = plt.subplots(1, 2, figsize=(7, 3.5), sharey=True, sharex=True)\n", + "\n", + "sns.scatterplot(\n", + " x=x[::2], y=y[::2], style=a[::2], size=a[::2], legend=False,\n", + " markers=[\"o\", (3, 1, 1)], sizes=[70, 140], ax=axs[0],\n", + ")\n", + "\n", + "sns.scatterplot(\n", + " x=x[1::2], y=y[1::2], style=a[1::2], size=a[1::2], hue=a[1::2], legend=False,\n", + " markers=[\"o\", (3, 1, 1)], sizes=[70, 140], ax=axs[1],\n", + ")\n", + "\n", + "f.tight_layout(w_pad=2)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In the plot on the right, the orange triangles \"pop out\", making it easy to distinguish them from the circles. This pop-out effect happens because our visual system prioritizes color differences.\n", + "\n", + "The blue and orange colors differ mostly in terms of their hue. Hue is useful for representing categories: most people can distinguish a moderate number of hues relatively easily, and points that have different hues but similar brightness or intensity seem equally important. It also makes plots easier to talk about. Consider this example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "b = np.tile(np.arange(10), n // 5)\n", + "\n", + "f, axs = plt.subplots(1, 2, figsize=(7, 3.5), sharey=True, sharex=True)\n", + "\n", + "sns.scatterplot(\n", + " x=x[::2], y=y[::2], hue=b[::2],\n", + " legend=False, palette=\"muted\", s=70, ax=axs[0],\n", + ")\n", + "\n", + "sns.scatterplot(\n", + " x=x[1::2], y=y[1::2], hue=b[1::2],\n", + " legend=False, palette=\"blend:.75,C0\", s=70, ax=axs[1],\n", + ")\n", + "\n", + "f.tight_layout(w_pad=2)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Most people would be able to quickly ascertain that there are five distinct categories in the plot on the left and, if asked to characterize the \"blue\" points, would be able to do so.\n", + "\n", + "With the plot on the right, where the points are all blue but vary in their luminance and saturation, it's harder to say how many unique categories are present. And how would we talk about a particular category? \"The fairly-but-not-too-blue points?\" What's more, the gray dots seem to fade into the background, de-emphasizing them relative to the more intense blue dots. If the categories are equally important, this is a poor representation.\n", + "\n", + "So as a general rule, use hue variation to represent categories. With that said, here are few notes of caution. If you have more than a handful of colors in your plot, it can become difficult to keep in mind what each one means, unless there are pre-existing associations between the categories and the colors used to represent them. This makes your plot harder to interpret: rather than focusing on the data, a viewer will have to continually refer to the legend to make sense of what is shown. So you should strive not to make plots that are too complex. And be mindful that not everyone sees colors the same way. Varying both shape (or some other attribute) and color can help people with anomalous color vision understand your plots, and it can keep them (somewhat) interpretable if they are printed to black-and-white." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Vary luminance to represent numbers\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "On the other hand, hue variations are not well suited to representing numeric data. Consider this example, where we need colors to represent the counts in a bivariate histogram. On the left, we use a circular colormap, where gradual changes in the number of observation within each bin correspond to gradual changes in hue. On the right, we use a palette that uses brighter colors to represent bins with larger counts:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "\n", + "f, axs = plt.subplots(1, 2, figsize=(7, 4.25), sharey=True, sharex=True)\n", + "\n", + "sns.histplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " binwidth=(3, .75), cmap=\"hls\", ax=axs[0],\n", + " cbar=True, cbar_kws=dict(orientation=\"horizontal\", pad=.1),\n", + ")\n", + "axs[0].set(xlabel=\"\", ylabel=\"\")\n", + "\n", + "\n", + "sns.histplot(\n", + " data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " binwidth=(3, .75), cmap=\"flare_r\", ax=axs[1],\n", + " cbar=True, cbar_kws=dict(orientation=\"horizontal\", pad=.1),\n", + ")\n", + "axs[1].set(xlabel=\"\", ylabel=\"\")\n", + "\n", + "f.tight_layout(w_pad=3)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "With the hue-based palette, it's quite difficult to ascertain the shape of the bivariate distribution. In contrast, the luminance palette makes it much more clear that there are two prominent peaks.\n", + "\n", + "Varying luminance helps you see structure in data, and changes in luminance are more intuitively processed as changes in importance. But the plot on the right does not use a grayscale colormap. Its colorfulness makes it more interesting, and the subtle hue variation increases the perceptual distance between two values. As a result, small differences slightly easier to resolve.\n", + "\n", + "These examples show that color palette choices are about more than aesthetics: the colors you choose can reveal patterns in your data if used effectively or hide them if used poorly. There is not one optimal palette, but there are palettes that are better or worse for particular datasets and visualization approaches.\n", + "\n", + "And aesthetics do matter: the more that people want to look at your figures, the greater the chance that they will learn something from them. This is true even when you are making plots for yourself. During exploratory data analysis, you may generate many similar figures. Varying the color palettes will add a sense of novelty, which keeps you engaged and prepared to notice interesting features of your data.\n", + "\n", + "So how can you choose color palettes that both represent your data well and look attractive?" + ] + }, + { + "cell_type": "raw", + "metadata": { + "raw_mimetype": "text/restructuredtext" + }, + "source": [ + "Tools for choosing color palettes\n", + "---------------------------------\n", + "\n", + "The most important function for working with color palettes is, aptly, :func:`color_palette`. This function provides an interface to most of the possible ways that one can generate color palettes in seaborn. And it's used internally by any function that has a ``palette`` argument.\n", + "\n", + "The primary argument to :func:`color_palette` is usually a string: either the name of a specific palette or the name of a family and additional arguments to select a specific member. In the latter case, :func:`color_palette` will delegate to more specific function, such as :func:`cubehelix_palette`. It's also possible to pass a list of colors specified any way that matplotlib accepts (an RGB tuple, a hex code, or a name in the X11 table). The return value is an object that wraps a list of RGB tuples with a few useful methods, such as conversion to hex codes and a rich HTML representation.\n", + "\n", + "Calling :func:`color_palette` with no arguments will return the current default color palette that matplotlib (and most seaborn functions) will use if colors are not otherwise specified. This default palette can be set with the corresponding :func:`set_palette` function, which calls :func:`color_palette` internally and accepts the same arguments.\n", + "\n", + "To motivate the different options that :func:`color_palette` provides, it will be useful to introduce a classification scheme for color palettes. Broadly, palettes fall into one of three categories:\n", + "\n", + "- qualitative palettes, good for representing categorical data\n", + "- sequential palettes, good for representing numeric data\n", + "- diverging palettes, good for representing numeric data with a categorical boundary" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _qualitative_palettes:\n", + "\n", + "Qualitative color palettes\n", + "--------------------------\n", + "\n", + "Qualitative palettes are well-suited to representing categorical data because most of their variation is in the hue component. The default color palette in seaborn is a qualitative palette with ten distinct hues:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "These colors have the same ordering as the default matplotlib color palette, ``\"tab10\"``, but they are a bit less intense. Compare:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"tab10\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Seaborn in fact has six variations of matplotlib's palette, called ``deep``, ``muted``, ``pastel``, ``bright``, ``dark``, and ``colorblind``. These span a range of average luminance and saturation values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "import io\n", + "from IPython.display import SVG\n", + "f = mpl.figure.Figure(figsize=(6, 6))\n", + "\n", + "ax_locs = dict(\n", + " deep=(.4, .4),\n", + " bright=(.8, .8),\n", + " muted=(.49, .71),\n", + " dark=(.8, .2),\n", + " pastel=(.2, .8),\n", + " colorblind=(.71, .49),\n", + ")\n", + "\n", + "s = .35\n", + "\n", + "for pal, (x, y) in ax_locs.items():\n", + " ax = f.add_axes([x - s / 2, y - s / 2, s, s])\n", + " ax.pie(np.ones(10),\n", + " colors=sns.color_palette(pal, 10),\n", + " counterclock=False, startangle=180,\n", + " wedgeprops=dict(linewidth=1, edgecolor=\"w\"))\n", + " f.text(x, y, pal, ha=\"center\", va=\"center\", size=14,\n", + " bbox=dict(facecolor=\"white\", alpha=0.85, boxstyle=\"round,pad=0.2\"))\n", + "\n", + "f.text(.1, .05, \"Saturation\", size=18, ha=\"left\", va=\"center\",\n", + " bbox=dict(facecolor=\"white\", edgecolor=\"w\"))\n", + "f.text(.05, .1, \"Luminance\", size=18, ha=\"center\", va=\"bottom\", rotation=90,\n", + " bbox=dict(facecolor=\"white\", edgecolor=\"w\"))\n", + "\n", + "ax = f.add_axes([0, 0, 1, 1])\n", + "ax.set_axis_off()\n", + "ax.arrow(.15, .05, .4, 0, width=.002, head_width=.015, color=\".15\")\n", + "ax.arrow(.05, .15, 0, .4, width=.002, head_width=.015, color=\".15\")\n", + "ax.set(xlim=(0, 1), ylim=(0, 1))\n", + "f.savefig(svg:=io.StringIO(), format=\"svg\")\n", + "SVG(svg.getvalue())" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Many people find the moderated hues of the default ``\"deep\"`` palette to be aesthetically pleasing, but they are also less distinct. As a result, they may be more difficult to discriminate in some contexts, which is something to keep in mind when making publication graphics. `This comparison `_ can be helpful for estimating how the seaborn color palettes perform when simulating different forms of colorblindess." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Using circular color systems\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "When you have an arbitrary number of categories, the easiest approach to finding unique hues is to draw evenly-spaced colors in a circular color space (one where the hue changes while keeping the brightness and saturation constant). This is what most seaborn functions default to when they need to use more colors than are currently set in the default color cycle.\n", + "\n", + "The most common way to do this uses the ``hls`` color space, which is a simple transformation of RGB values. We saw this color palette before as a counterexample for how to plot a histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"hls\", 8)" + ] + }, + { + "cell_type": "raw", + "metadata": { + "raw_mimetype": "text/restructuredtext" + }, + "source": [ + "Because of the way the human visual system works, colors that have the same luminance and saturation in terms of their RGB values won't necessarily look equally intense To remedy this, seaborn provides an interface to the `husl `_ system (since renamed to HSLuv), which achieves less intensity variation as you rotate around the color wheel:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"husl\", 8)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When seaborn needs a categorical palette with more colors than are available in the current default, it will use this approach.\n", + "\n", + "Using categorical Color Brewer palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Another source of visually pleasing categorical palettes comes from the `Color Brewer `_ tool (which also has sequential and diverging palettes, as we'll see below)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Set2\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Be aware that the qualitative Color Brewer palettes have different lengths, and the default behavior of :func:`color_palette` is to give you the full list:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Paired\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _sequential_palettes:\n", + "\n", + "Sequential color palettes\n", + "-------------------------\n", + "\n", + "The second major class of color palettes is called \"sequential\". This kind of mapping is appropriate when data range from relatively low or uninteresting values to relatively high or interesting values (or vice versa). As we saw above, the primary dimension of variation in a sequential palette is luminance. Some seaborn functions will default to a sequential palette when you are mapping numeric data. (For historical reasons, both categorical and numeric mappings are specified with the ``hue`` parameter in functions like :func:`relplot` or :func:`displot`, even though numeric mappings use color palettes with relatively little hue variation).\n", + "\n", + "Perceptually uniform palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Because they are intended to represent numeric values, the best sequential palettes will be *perceptually uniform*, meaning that the relative discriminability of two colors is proportional to the difference between the corresponding data values. Seaborn includes four perceptually uniform sequential colormaps: ``\"rocket\"``, ``\"mako\"``, ``\"flare\"``, and ``\"crest\"``. The first two have a very wide luminance range and are well suited for applications such as heatmaps, where colors fill the space they are plotted into:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"rocket\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"mako\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Because the extreme values of these colormaps approach white, they are not well-suited for coloring elements such as lines or points: it will be difficult to discriminate important values against a white or gray background. The \"flare\" and \"crest\" colormaps are a better choice for such plots. They have a more restricted range of luminance variations, which they compensate for with a slightly more pronounced variation in hue. The default direction of the luminance ramp is also reversed, so that smaller values have lighter colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"flare\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"crest\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It is also possible to use the perceptually uniform colormaps provided by matplotlib, such as ``\"magma\"`` and ``\"viridis\"``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"magma\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"viridis\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As with the convention in matplotlib, every continuous colormap has a reversed version, which has the suffix ``\"_r\"``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"rocket_r\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Discrete vs. continuous mapping\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "One thing to be aware of is that seaborn can generate discrete values from sequential colormaps and, when doing so, it will not use the most extreme values. Compare the discrete version of ``\"rocket\"`` against the continuous version shown above:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"rocket\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Internally, seaborn uses the discrete version for categorical data and the continuous version when in numeric mapping mode. Discrete sequential colormaps can be well-suited for visualizing categorical data with an intrinsic ordering, especially if there is some hue variation." + ] + }, + { + "cell_type": "raw", + "metadata": { + "raw_mimetype": "text/restructuredtext" + }, + "source": [ + ".. _cubehelix_palettes:\n", + "\n", + "Sequential \"cubehelix\" palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The perceptually uniform colormaps are difficult to programmatically generate, because they are not based on the RGB color space. The `cubehelix `_ system offers an RGB-based compromise: it generates sequential palettes with a linear increase or decrease in brightness and some continuous variation in hue. While not perfectly perceptually uniform, the resulting colormaps have many good properties. Importantly, many aspects of the design process are parameterizable.\n", + "\n", + "Matplotlib has the default cubehelix version built into it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"cubehelix\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The default palette returned by the seaborn :func:`cubehelix_palette` function is a bit different from the matplotlib default in that it does not rotate as far around the hue wheel or cover as wide a range of intensities. It also reverses the luminance ramp:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Other arguments to :func:`cubehelix_palette` control how the palette looks. The two main things you'll change are the ``start`` (a value between 0 and 3) and ``rot``, or number of rotations (an arbitrary value, but usually between -1 and 1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(start=.5, rot=-.5, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The more you rotate, the more hue variation you will see:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(start=.5, rot=-.75, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can control both how dark and light the endpoints are and their order:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.cubehelix_palette(start=2, rot=0, dark=0, light=.95, reverse=True, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :func:`color_palette` accepts a string code, starting with ``\"ch:\"``, for generating an arbitrary cubehelix palette. You can passs the names of parameters in the string:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"ch:start=.2,rot=-.3\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "And for compactness, each parameter can be specified with its first letter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"ch:s=-.2,r=.6\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Custom sequential palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "For a simpler interface to custom sequential palettes, you can use :func:`light_palette` or :func:`dark_palette`, which are both seeded with a single color and produce a palette that ramps either from light or dark desaturated values to that color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.light_palette(\"seagreen\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.dark_palette(\"#69d\", reverse=True, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As with cubehelix palettes, you can also specify light or dark palettes through :func:`color_palette` or anywhere ``palette`` is accepted:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"light:b\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Reverse the colormap by adding ``\"_r\"``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"dark:salmon_r\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Sequential Color Brewer palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The Color Brewer library also has some good options for sequential palettes. They include palettes with one primary hue:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Blues\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Along with multi-hue options:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"YlOrBr\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _diverging_palettes:\n", + "\n", + "Diverging color palettes\n", + "------------------------\n", + "\n", + "The third class of color palettes is called \"diverging\". These are used for data where both large low and high values are interesting and span a midpoint value (often 0) that should be demphasized. The rules for choosing good diverging palettes are similar to good sequential palettes, except now there should be two dominant hues in the colormap, one at (or near) each pole. It's also important that the starting values are of similar brightness and saturation.\n", + "\n", + "Perceptually uniform diverging palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Seaborn includes two perceptually uniform diverging palettes: ``\"vlag\"`` and ``\"icefire\"``. They both use blue and red at their poles, which many intuitively processes as \"cold\" and \"hot\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"vlag\", as_cmap=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"icefire\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Custom diverging palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "You can also use the seaborn function :func:`diverging_palette` to create a custom colormap for diverging data. This function makes diverging palettes using the ``husl`` color system. You pass it two hues (in degrees) and, optionally, the lightness and saturation values for the extremes. Using ``husl`` means that the extreme values, and the resulting ramps to the midpoint, while not perfectly perceptually uniform, will be well-balanced:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(220, 20, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This is convenient when you want to stray from the boring confines of cold-hot approaches:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(145, 300, s=60, as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to make a palette where the midpoint is dark rather than light:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.diverging_palette(250, 30, l=65, center=\"dark\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's important to emphasize here that using red and green, while intuitive, `should be avoided `_.\n", + "\n", + "Other diverging palettes\n", + "~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "There are a few other good diverging palettes built into matplotlib, including Color Brewer palettes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"Spectral\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "And the ``coolwarm`` palette, which has less contrast between the middle values and the extremes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.color_palette(\"coolwarm\", as_cmap=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As you can see, there are many options for using color in your visualizations. Seaborn tries both to use good defaults and to offer a lot of flexibility.\n", + "\n", + "This discussion is only the beginning, and there are a number of good resources for learning more about techniques for using color in visualizations. One great example is this `series of blog posts `_ from the NASA Earth Observatory. The matplotlib docs also have a `nice tutorial `_ that illustrates some of the perceptual properties of their colormaps." + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/data_structure.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/data_structure.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7fda56b6ecb534a77fdb68015aa3006cdce092ca --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/data_structure.ipynb @@ -0,0 +1,497 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _data_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Data structures accepted by seaborn\n", + "===================================\n", + "\n", + "As a data visualization library, seaborn requires that you provide it with data. This chapter explains the various ways to accomplish that task. Seaborn supports several different dataset formats, and most functions accept data represented with objects from the `pandas `_ or `numpy `_ libraries as well as built-in Python types like lists and dictionaries. Understanding the usage patterns associated with these different options will help you quickly create useful visualizations for nearly any dataset.\n", + "\n", + ".. note::\n", + " As of current writing (v0.11.0), the full breadth of options covered here are supported by only a subset of the modules in seaborn (namely, the :ref:`relational ` and :ref:`distribution ` modules). The other modules offer much of the same flexibility, but have some exceptions (e.g., :func:`catplot` and :func:`lmplot` are limited to long-form data with named variables). The data-ingest code will be standardized over the next few release cycles, but until that point, be mindful of the specific documentation for each function if it is not doing what you expect with your dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Long-form vs. wide-form data\n", + "----------------------------\n", + "\n", + "Most plotting functions in seaborn are oriented towards *vectors* of data. When plotting ``x`` against ``y``, each variable should be a vector. Seaborn accepts data *sets* that have more than one vector organized in some tabular fashion. There is a fundamental distinction between \"long-form\" and \"wide-form\" data tables, and seaborn will treat each differently.\n", + "\n", + "Long-form data\n", + "~~~~~~~~~~~~~~\n", + "\n", + "A long-form data table has the following characteristics:\n", + "\n", + "- Each variable is a column\n", + "- Each observation is a row" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As a simple example, consider the \"flights\" dataset, which records the number of airline passengers who flew in each month from 1949 to 1960. This dataset has three variables (*year*, *month*, and number of *passengers*):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights = sns.load_dataset(\"flights\")\n", + "flights.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "With long-form data, columns in the table are given roles in the plot by explicitly assigning them to one of the variables. For example, making a monthly plot of the number of passengers per year looks like this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=flights, x=\"year\", y=\"passengers\", hue=\"month\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The advantage of long-form data is that it lends itself well to this explicit specification of the plot. It can accommodate datasets of arbitrary complexity, so long as the variables and observations can be clearly defined. But this format takes some getting used to, because it is often not the model of the data that one has in their head.\n", + "\n", + "Wide-form data\n", + "~~~~~~~~~~~~~~\n", + "\n", + "For simple datasets, it is often more intuitive to think about data the way it might be viewed in a spreadsheet, where the columns and rows contain *levels* of different variables. For example, we can convert the flights dataset into a wide-form organization by \"pivoting\" it so that each column has each month's time series over years:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_wide = flights.pivot(index=\"year\", columns=\"month\", values=\"passengers\")\n", + "flights_wide.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Here we have the same three variables, but they are organized differently. The variables in this dataset are linked to the *dimensions* of the table, rather than to named fields. Each observation is defined by both the value at a cell in the table and the coordinates of that cell with respect to the row and column indices." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "With long-form data, we can access variables in the dataset by their name. That is not the case with wide-form data. Nevertheless, because there is a clear association between the dimensions of the table and the variable in the dataset, seaborn is able to assign those variables roles in the plot.\n", + "\n", + ".. note::\n", + " Seaborn treats the argument to ``data`` as wide form when neither ``x`` nor ``y`` are assigned." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=flights_wide, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This plot looks very similar to the one before. Seaborn has assigned the index of the dataframe to ``x``, the values of the dataframe to ``y``, and it has drawn a separate line for each month. There is a notable difference between the two plots, however. When the dataset went through the \"pivot\" operation that converted it from long-form to wide-form, the information about what the values mean was lost. As a result, there is no y axis label. (The lines also have dashes here, because :func:`relplot` has mapped the column variable to both the ``hue`` and ``style`` semantic so that the plot is more accessible. We didn't do that in the long-form case, but we could have by setting ``style=\"month\"``).\n", + "\n", + "Thus far, we did much less typing while using wide-form data and made nearly the same plot. This seems easier! But a big advantage of long-form data is that, once you have the data in the correct format, you no longer need to think about its *structure*. You can design your plots by thinking only about the variables contained within it. For example, to draw lines that represent the monthly time series for each year, simply reassign the variables:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=flights, x=\"month\", y=\"passengers\", hue=\"year\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To achieve the same remapping with the wide-form dataset, we would need to transpose the table:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=flights_wide.transpose(), kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "(This example also illustrates another wrinkle, which is that seaborn currently considers the column variable in a wide-form dataset to be categorical regardless of its datatype, whereas, because the long-form variable is numeric, it is assigned a quantitative color palette and legend. This may change in the future).\n", + "\n", + "The absence of explicit variable assignments also means that each plot type needs to define a fixed mapping between the dimensions of the wide-form data and the roles in the plot. Because this natural mapping may vary across plot types, the results are less predictable when using wide-form data. For example, the :ref:`categorical ` plots assign the *column* dimension of the table to ``x`` and then aggregate across the rows (ignoring the index):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=flights_wide, kind=\"box\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When using pandas to represent wide-form data, you are limited to just a few variables (no more than three). This is because seaborn does not make use of multi-index information, which is how pandas represents additional variables in a tabular format. The `xarray `_ project offers labeled N-dimensional array objects, which can be considered a generalization of wide-form data to higher dimensions. At present, seaborn does not directly support objects from ``xarray``, but they can be transformed into a long-form :class:`pandas.DataFrame` using the ``to_pandas`` method and then plotted in seaborn like any other long-form data set.\n", + "\n", + "In summary, we can think of long-form and wide-form datasets as looking something like this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "f = plt.figure(figsize=(7, 5))\n", + "\n", + "gs = plt.GridSpec(\n", + " ncols=6, nrows=2, figure=f,\n", + " left=0, right=.35, bottom=0, top=.9,\n", + " height_ratios=(1, 20),\n", + " wspace=.1, hspace=.01\n", + ")\n", + "\n", + "colors = [c + (.5,) for c in sns.color_palette()]\n", + "\n", + "f.add_subplot(gs[0, :], facecolor=\".8\")\n", + "[\n", + " f.add_subplot(gs[1:, i], facecolor=colors[i])\n", + " for i in range(gs.ncols)\n", + "]\n", + "\n", + "gs = plt.GridSpec(\n", + " ncols=2, nrows=2, figure=f,\n", + " left=.4, right=1, bottom=.2, top=.8,\n", + " height_ratios=(1, 8), width_ratios=(1, 11),\n", + " wspace=.015, hspace=.02\n", + ")\n", + "\n", + "f.add_subplot(gs[0, 1:], facecolor=colors[2])\n", + "f.add_subplot(gs[1:, 0], facecolor=colors[1])\n", + "f.add_subplot(gs[1, 1], facecolor=colors[0])\n", + "\n", + "for ax in f.axes:\n", + " ax.set(xticks=[], yticks=[])\n", + "\n", + "f.text(.35 / 2, .91, \"Long-form\", ha=\"center\", va=\"bottom\", size=15)\n", + "f.text(.7, .81, \"Wide-form\", ha=\"center\", va=\"bottom\", size=15)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Messy data\n", + "~~~~~~~~~~\n", + "\n", + "Many datasets cannot be clearly interpreted using either long-form or wide-form rules. If datasets that are clearly long-form or wide-form are `\"tidy\" `_, we might say that these more ambiguous datasets are \"messy\". In a messy dataset, the variables are neither uniquely defined by the keys nor by the dimensions of the table. This often occurs with *repeated-measures* data, where it is natural to organize a table such that each row corresponds to the *unit* of data collection. Consider this simple dataset from a psychology experiment in which twenty subjects performed a memory task where they studied anagrams while their attention was either divided or focused:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "anagrams = sns.load_dataset(\"anagrams\")\n", + "anagrams" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The attention variable is *between-subjects*, but there is also a *within-subjects* variable: the number of possible solutions to the anagrams, which varied from 1 to 3. The dependent measure is a score of memory performance. These two variables (number and score) are jointly encoded across several columns. As a result, the whole dataset is neither clearly long-form nor clearly wide-form.\n", + "\n", + "How might we tell seaborn to plot the average score as a function of attention and number of solutions? We'd first need to coerce the data into one of our two structures. Let's transform it to a tidy long-form table, such that each variable is a column and each row is an observation. We can use the method :meth:`pandas.DataFrame.melt` to accomplish this task:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "anagrams_long = anagrams.melt(id_vars=[\"subidr\", \"attnr\"], var_name=\"solutions\", value_name=\"score\")\n", + "anagrams_long.head()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Now we can make the plot that we want:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=anagrams_long, x=\"solutions\", y=\"score\", hue=\"attnr\", kind=\"point\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Further reading and take-home points\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "For a longer discussion about tabular data structures, you could read the `\"Tidy Data\" `_ paper by Hadley Whickham. Note that seaborn uses a slightly different set of concepts than are defined in the paper. While the paper associates tidyness with long-form structure, we have drawn a distinction between \"tidy wide-form\" data, where there is a clear mapping between variables in the dataset and the dimensions of the table, and \"messy data\", where no such mapping exists.\n", + "\n", + "The long-form structure has clear advantages. It allows you to create figures by explicitly assigning variables in the dataset to roles in plot, and you can do so with more than three variables. When possible, try to represent your data with a long-form structure when embarking on serious analysis. Most of the examples in the seaborn documentation will use long-form data. But in cases where it is more natural to keep the dataset wide, remember that seaborn can remain useful." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Options for visualizing long-form data\n", + "--------------------------------------\n", + "\n", + "While long-form data has a precise definition, seaborn is fairly flexible in terms of how it is actually organized across the data structures in memory. The examples in the rest of the documentation will typically use :class:`pandas.DataFrame` objects and reference variables in them by assigning names of their columns to the variables in the plot. But it is also possible to store vectors in a Python dictionary or a class that implements that interface:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_dict = flights.to_dict()\n", + "sns.relplot(data=flights_dict, x=\"year\", y=\"passengers\", hue=\"month\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Many pandas operations, such as the split-apply-combine operations of a group-by, will produce a dataframe where information has moved from the columns of the input dataframe to the index of the output. So long as the name is retained, you can still reference the data as normal:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_avg = flights.groupby(\"year\").mean()\n", + "sns.relplot(data=flights_avg, x=\"year\", y=\"passengers\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Additionally, it's possible to pass vectors of data directly as arguments to ``x``, ``y``, and other plotting variables. If these vectors are pandas objects, the ``name`` attribute will be used to label the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "year = flights_avg.index\n", + "passengers = flights_avg[\"passengers\"]\n", + "sns.relplot(x=year, y=passengers, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Numpy arrays and other objects that implement the Python sequence interface work too, but if they don't have names, the plot will not be as informative without further tweaking:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(x=year.to_numpy(), y=passengers.to_list(), kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Options for visualizing wide-form data\n", + "--------------------------------------\n", + "\n", + "The options for passing wide-form data are even more flexible. As with long-form data, pandas objects are preferable because the name (and, in some cases, index) information can be used. But in essence, any format that can be viewed as a single vector or a collection of vectors can be passed to ``data``, and a valid plot can usually be constructed.\n", + "\n", + "The example we saw above used a rectangular :class:`pandas.DataFrame`, which can be thought of as a collection of its columns. A dict or list of pandas objects will also work, but we'll lose the axis labels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_wide_list = [col for _, col in flights_wide.items()]\n", + "sns.relplot(data=flights_wide_list, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The vectors in a collection do not need to have the same length. If they have an ``index``, it will be used to align them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "two_series = [flights_wide.loc[:1955, \"Jan\"], flights_wide.loc[1952:, \"Aug\"]]\n", + "sns.relplot(data=two_series, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Whereas an ordinal index will be used for numpy arrays or simple Python sequences:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "two_arrays = [s.to_numpy() for s in two_series]\n", + "sns.relplot(data=two_arrays, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "But a dictionary of such vectors will at least use the keys:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "two_arrays_dict = {s.name: s.to_numpy() for s in two_series}\n", + "sns.relplot(data=two_arrays_dict, kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Rectangular numpy arrays are treated just like a dataframe without index information, so they are viewed as a collection of column vectors. Note that this is different from how numpy indexing operations work, where a single indexer will access a row. But it is consistent with how pandas would turn the array into a dataframe or how matplotlib would plot it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "flights_array = flights_wide.to_numpy()\n", + "sns.relplot(data=flights_array, kind=\"line\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/distributions.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/distributions.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ae80838b9f19f4b680b22192fe0a0bf25cf55af --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/distributions.ipynb @@ -0,0 +1,858 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _distribution_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Visualizing distributions of data\n", + "==================================\n", + "\n", + "An early step in any effort to analyze or model data should be to understand how the variables are distributed. Techniques for distribution visualization can provide quick answers to many important questions. What range do the observations cover? What is their central tendency? Are they heavily skewed in one direction? Is there evidence for bimodality? Are there significant outliers? Do the answers to these questions vary across subsets defined by other variables?\n", + "\n", + "The :ref:`distributions module ` contains several functions designed to answer questions such as these. The axes-level functions are :func:`histplot`, :func:`kdeplot`, :func:`ecdfplot`, and :func:`rugplot`. They are grouped together within the figure-level :func:`displot`, :func:`jointplot`, and :func:`pairplot` functions.\n", + "\n", + "There are several different approaches to visualizing a distribution, and each has its relative advantages and drawbacks. It is important to understand these factors so that you can choose the best approach for your particular aim." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "import seaborn as sns; sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _tutorial_hist:\n", + "\n", + "Plotting univariate histograms\n", + "------------------------------\n", + "\n", + "Perhaps the most common approach to visualizing a distribution is the *histogram*. This is the default approach in :func:`displot`, which uses the same underlying code as :func:`histplot`. A histogram is a bar plot where the axis representing the data variable is divided into a set of discrete bins and the count of observations falling within each bin is shown using the height of the corresponding bar:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.displot(penguins, x=\"flipper_length_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This plot immediately affords a few insights about the ``flipper_length_mm`` variable. For instance, we can see that the most common flipper length is about 195 mm, but the distribution appears bimodal, so this one number does not represent the data well.\n", + "\n", + "Choosing the bin size\n", + "^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The size of the bins is an important parameter, and using the wrong bin size can mislead by obscuring important features of the data or by creating apparent features out of random variability. By default, :func:`displot`/:func:`histplot` choose a default bin size based on the variance of the data and the number of observations. But you should not be over-reliant on such automatic approaches, because they depend on particular assumptions about the structure of your data. It is always advisable to check that your impressions of the distribution are consistent across different bin sizes. To choose the size directly, set the `binwidth` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", binwidth=3)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In other circumstances, it may make more sense to specify the *number* of bins, rather than their size:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", bins=20)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "One example of a situation where defaults fail is when the variable takes a relatively small number of integer values. In that case, the default bin width may be too small, creating awkward gaps in the distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.displot(tips, x=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "One approach would be to specify the precise bin breaks by passing an array to ``bins``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(tips, x=\"size\", bins=[1, 2, 3, 4, 5, 6, 7])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This can also be accomplished by setting ``discrete=True``, which chooses bin breaks that represent the unique values in a dataset with bars that are centered on their corresponding value." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(tips, x=\"size\", discrete=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to visualize the distribution of a categorical variable using the logic of a histogram. Discrete bins are automatically set for categorical variables, but it may also be helpful to \"shrink\" the bars slightly to emphasize the categorical nature of the axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(tips, x=\"day\", shrink=.8)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Conditioning on other variables\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "Once you understand the distribution of a variable, the next step is often to ask whether features of that distribution differ across other variables in the dataset. For example, what accounts for the bimodal distribution of flipper lengths that we saw above? :func:`displot` and :func:`histplot` provide support for conditional subsetting via the ``hue`` semantic. Assigning a variable to ``hue`` will draw a separate histogram for each of its unique values and distinguish them by color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, the different histograms are \"layered\" on top of each other and, in some cases, they may be difficult to distinguish. One option is to change the visual representation of the histogram from a bar plot to a \"step\" plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", element=\"step\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Alternatively, instead of layering each bar, they can be \"stacked\", or moved vertically. In this plot, the outline of the full histogram will match the plot with only a single variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The stacked histogram emphasizes the part-whole relationship between the variables, but it can obscure other features (for example, it is difficult to determine the mode of the Adelie distribution. Another option is \"dodge\" the bars, which moves them horizontally and reduces their width. This ensures that there are no overlaps and that the bars remain comparable in terms of height. But it only works well when the categorical variable has a small number of levels:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"sex\", multiple=\"dodge\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Because :func:`displot` is a figure-level function and is drawn onto a :class:`FacetGrid`, it is also possible to draw each individual distribution in a separate subplot by assigning the second variable to ``col`` or ``row`` rather than (or in addition to) ``hue``. This represents the distribution of each subset well, but it makes it more difficult to draw direct comparisons:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", col=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "None of these approaches are perfect, and we will soon see some alternatives to a histogram that are better-suited to the task of comparison.\n", + "\n", + "Normalized histogram statistics\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "Before we do, another point to note is that, when the subsets have unequal numbers of observations, comparing their distributions in terms of counts may not be ideal. One solution is to *normalize* the counts using the ``stat`` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", stat=\"density\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "By default, however, the normalization is applied to the entire distribution, so this simply rescales the height of the bars. By setting ``common_norm=False``, each subset will be normalized independently:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", stat=\"density\", common_norm=False)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Density normalization scales the bars so that their *areas* sum to 1. As a result, the density axis is not directly interpretable. Another option is to normalize the bars to that their *heights* sum to 1. This makes most sense when the variable is discrete, but it is an option for all histograms:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", stat=\"probability\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _tutorial_kde:\n", + "\n", + "Kernel density estimation\n", + "-------------------------\n", + "\n", + "A histogram aims to approximate the underlying probability density function that generated the data by binning and counting observations. Kernel density estimation (KDE) presents a different solution to the same problem. Rather than using discrete bins, a KDE plot smooths the observations with a Gaussian kernel, producing a continuous density estimate:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Choosing the smoothing bandwidth\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "Much like with the bin size in the histogram, the ability of the KDE to accurately represent the data depends on the choice of smoothing bandwidth. An over-smoothed estimate might erase meaningful features, but an under-smoothed estimate can obscure the true shape within random noise. The easiest way to check the robustness of the estimate is to adjust the default bandwidth:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", kind=\"kde\", bw_adjust=.25)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Note how the narrow bandwidth makes the bimodality much more apparent, but the curve is much less smooth. In contrast, a larger bandwidth obscures the bimodality almost completely:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", kind=\"kde\", bw_adjust=2)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Conditioning on other variables\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "As with histograms, if you assign a ``hue`` variable, a separate density estimate will be computed for each level of that variable:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In many cases, the layered KDE is easier to interpret than the layered histogram, so it is often a good choice for the task of comparison. Many of the same options for resolving multiple distributions apply to the KDE as well, however:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", kind=\"kde\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Note how the stacked plot filled in the area between each curve by default. It is also possible to fill in the curves for single or layered densities, although the default alpha value (opacity) will be different, so that the individual densities are easier to resolve." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", kind=\"kde\", fill=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Kernel density estimation pitfalls\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "KDE plots have many advantages. Important features of the data are easy to discern (central tendency, bimodality, skew), and they afford easy comparisons between subsets. But there are also situations where KDE poorly represents the underlying data. This is because the logic of KDE assumes that the underlying distribution is smooth and unbounded. One way this assumption can fail is when a variable reflects a quantity that is naturally bounded. If there are observations lying close to the bound (for example, small values of a variable that cannot be negative), the KDE curve may extend to unrealistic values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(tips, x=\"total_bill\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This can be partially avoided with the ``cut`` parameter, which specifies how far the curve should extend beyond the extreme datapoints. But this influences only where the curve is drawn; the density estimate will still smooth over the range where no data can exist, causing it to be artificially low at the extremes of the distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(tips, x=\"total_bill\", kind=\"kde\", cut=0)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The KDE approach also fails for discrete data or when data are naturally continuous but specific values are over-represented. The important thing to keep in mind is that the KDE will *always show you a smooth curve*, even when the data themselves are not smooth. For example, consider this distribution of diamond weights:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "diamonds = sns.load_dataset(\"diamonds\")\n", + "sns.displot(diamonds, x=\"carat\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "While the KDE suggests that there are peaks around specific values, the histogram reveals a much more jagged distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(diamonds, x=\"carat\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As a compromise, it is possible to combine these two approaches. While in histogram mode, :func:`displot` (as with :func:`histplot`) has the option of including the smoothed KDE curve (note ``kde=True``, not ``kind=\"kde\"``):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(diamonds, x=\"carat\", kde=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _tutorial_ecdf:\n", + "\n", + "Empirical cumulative distributions\n", + "----------------------------------\n", + "\n", + "A third option for visualizing distributions computes the \"empirical cumulative distribution function\" (ECDF). This plot draws a monotonically-increasing curve through each datapoint such that the height of the curve reflects the proportion of observations with a smaller value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", kind=\"ecdf\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ECDF plot has two key advantages. Unlike the histogram or KDE, it directly represents each datapoint. That means there is no bin size or smoothing parameter to consider. Additionally, because the curve is monotonically increasing, it is well-suited for comparing multiple distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", kind=\"ecdf\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The major downside to the ECDF plot is that it represents the shape of the distribution less intuitively than a histogram or density curve. Consider how the bimodality of flipper lengths is immediately apparent in the histogram, but to see it in the ECDF plot, you must look for varying slopes. Nevertheless, with practice, you can learn to answer all of the important questions about a distribution by examining the ECDF, and doing so can be a powerful approach." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Visualizing bivariate distributions\n", + "-----------------------------------\n", + "\n", + "All of the examples so far have considered *univariate* distributions: distributions of a single variable, perhaps conditional on a second variable assigned to ``hue``. Assigning a second variable to ``y``, however, will plot a *bivariate* distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A bivariate histogram bins the data within rectangles that tile the plot and then shows the count of observations within each rectangle with the fill color (analogous to a :func:`heatmap`). Similarly, a bivariate KDE plot smoothes the (x, y) observations with a 2D Gaussian. The default representation then shows the *contours* of the 2D density:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Assigning a ``hue`` variable will plot multiple heatmaps or contour sets using different colors. For bivariate histograms, this will only work well if there is minimal overlap between the conditional distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The contour approach of the bivariate KDE plot lends itself better to evaluating overlap, although a plot with too many contours can get busy:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Just as with univariate plots, the choice of bin size or smoothing bandwidth will determine how well the plot represents the underlying bivariate distribution. The same parameters apply, but they can be tuned for each variable by passing a pair of values:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", binwidth=(2, .5))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To aid interpretation of the heatmap, add a colorbar to show the mapping between counts and color intensity:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", binwidth=(2, .5), cbar=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The meaning of the bivariate density contours is less straightforward. Because the density is not directly interpretable, the contours are drawn at *iso-proportions* of the density, meaning that each curve shows a level set such that some proportion *p* of the density lies below it. The *p* values are evenly spaced, with the lowest level contolled by the ``thresh`` parameter and the number controlled by ``levels``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"kde\", thresh=.2, levels=4)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The ``levels`` parameter also accepts a list of values, for more control:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", kind=\"kde\", levels=[.01, .05, .1, .8])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The bivariate histogram allows one or both variables to be discrete. Plotting one discrete and one continuous variable offers another way to compare conditional univariate distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(diamonds, x=\"price\", y=\"clarity\", log_scale=(True, False))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In contrast, plotting two discrete variables is an easy to way show the cross-tabulation of the observations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(diamonds, x=\"color\", y=\"clarity\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Distribution visualization in other settings\n", + "--------------------------------------------\n", + "\n", + "Several other figure-level plotting functions in seaborn make use of the :func:`histplot` and :func:`kdeplot` functions.\n", + "\n", + "\n", + "Plotting joint and marginal distributions\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The first is :func:`jointplot`, which augments a bivariate relatonal or distribution plot with the marginal distributions of the two variables. By default, :func:`jointplot` represents the bivariate distribution using :func:`scatterplot` and the marginal distributions using :func:`histplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Similar to :func:`displot`, setting a different ``kind=\"kde\"`` in :func:`jointplot` will change both the joint and marginal plots the use :func:`kdeplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(\n", + " data=penguins,\n", + " x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\",\n", + " kind=\"kde\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ":func:`jointplot` is a convenient interface to the :class:`JointGrid` class, which offeres more flexibility when used directly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.JointGrid(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "g.plot_joint(sns.histplot)\n", + "g.plot_marginals(sns.boxplot)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A less-obtrusive way to show marginal distributions uses a \"rug\" plot, which adds a small tick on the edge of the plot to represent each individual observation. This is built into :func:`displot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(\n", + " penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " kind=\"kde\", rug=True\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "And the axes-level :func:`rugplot` function can be used to add rugs on the side of any other kind of plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + "sns.rugplot(data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Plotting many distributions\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The :func:`pairplot` function offers a similar blend of joint and marginal distributions. Rather than focusing on a single relationship, however, :func:`pairplot` uses a \"small-multiple\" approach to visualize the univariate distribution of all variables in a dataset along with all of their pairwise relationships:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(penguins)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As with :func:`jointplot`/:class:`JointGrid`, using the underlying :class:`PairGrid` directly will afford more flexibility with only a bit more typing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins)\n", + "g.map_upper(sns.histplot)\n", + "g.map_lower(sns.kdeplot, fill=True)\n", + "g.map_diag(sns.histplot, kde=True)" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/error_bars.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/error_bars.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f101a80edf860941aea88649874db7b1ac57bca5 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/error_bars.ipynb @@ -0,0 +1,369 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _errorbar_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import matplotlib as mpl\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme(style=\"darkgrid\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "np.random.seed(sum(map(ord, \"errorbars\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Statistical estimation and error bars\n", + "=====================================\n", + "\n", + "Data visualization sometimes involves a step of aggregation or estimation, where multiple data points are reduced to a summary statistic such as the mean or median. When showing a summary statistic, it is usually appropriate to add *error bars*, which provide a visual cue about how well the summary represents the underlying data points.\n", + "\n", + "Several seaborn functions will automatically calculate both summary statistics and the error bars when given a full dataset. This chapter explains how you can control what the error bars show and why you might choose each of the options that seaborn affords.\n", + "\n", + "The error bars around an estimate of central tendency can show one of two general things: either the range of uncertainty about the estimate or the spread of the underlying data around it. These measures are related: given the same sample size, estimates will be more uncertain when data has a broader spread. But uncertainty will decrease as sample sizes grow, whereas spread will not.\n", + "\n", + "In seaborn, there are two approaches for constructing each kind of error bar. One approach is parametric, using a formula that relies on assumptions about the shape of the distribution. The other approach is nonparametric, using only the data that you provide.\n", + "\n", + "Your choice is made with the `errorbar` parameter, which exists for each function that does estimation as part of plotting. This parameter accepts the name of the method to use and, optionally, a parameter that controls the size of the interval. The choices can be defined in a 2D taxonomy that depends on what is shown and how it is constructed:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "import io\n", + "from IPython.display import SVG\n", + "f = mpl.figure.Figure(figsize=(8, 5))\n", + "axs = f.subplots(2, 2, sharex=True, sharey=True,)\n", + "\n", + "plt.setp(axs, xlim=(-1, 1), ylim=(-1, 1), xticks=[], yticks=[])\n", + "for ax, color in zip(axs.flat, [\"C0\", \"C2\", \"C3\", \"C1\"]):\n", + " ax.set_facecolor(mpl.colors.to_rgba(color, .25))\n", + "\n", + "kws = dict(x=0, y=.2, ha=\"center\", va=\"center\", size=18)\n", + "axs[0, 0].text(s=\"Standard deviation\", **kws)\n", + "axs[0, 1].text(s=\"Standard error\", **kws)\n", + "axs[1, 0].text(s=\"Percentile interval\", **kws)\n", + "axs[1, 1].text(s=\"Confidence interval\", **kws)\n", + "\n", + "kws = dict(x=0, y=-.2, ha=\"center\", va=\"center\", size=18, font=\"Courier New\")\n", + "axs[0, 0].text(s='errorbar=(\"sd\", scale)', **kws)\n", + "axs[0, 1].text(s='errorbar=(\"se\", scale)', **kws)\n", + "axs[1, 0].text(s='errorbar=(\"pi\", width)', **kws)\n", + "axs[1, 1].text(s='errorbar=(\"ci\", width)', **kws)\n", + "\n", + "kws = dict(size=18)\n", + "axs[0, 0].set_title(\"Spread\", **kws)\n", + "axs[0, 1].set_title(\"Uncertainty\", **kws)\n", + "axs[0, 0].set_ylabel(\"Parametric\", **kws)\n", + "axs[1, 0].set_ylabel(\"Nonparametric\", **kws)\n", + "\n", + "f.tight_layout()\n", + "f.subplots_adjust(hspace=.05, wspace=.05 * (4 / 6))\n", + "f.savefig(svg:=io.StringIO(), format=\"svg\")\n", + "SVG(svg.getvalue())" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You will note that the size parameter is defined differently for the parametric and nonparametric approaches. For parametric error bars, it is a scalar factor that is multiplied by the statistic defining the error (standard error or standard deviation). For nonparametric error bars, it is a percentile width. This is explained further for each specific approach below.\n", + "\n", + "\n", + ".. note::\n", + " The `errorbar` API described here was introduced in seaborn v0.12. In prior versions, the only options were to show a bootstrap confidence interval or a standard deviation, with the choice controlled by the `ci` parameter (i.e., `ci=` or `ci=\"sd\"`).\n", + "\n", + "To compare the different parameterizations, we'll use the following helper function:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def plot_errorbars(arg, **kws):\n", + " np.random.seed(sum(map(ord, \"error_bars\")))\n", + " x = np.random.normal(0, 1, 100)\n", + " f, axs = plt.subplots(2, figsize=(7, 2), sharex=True, layout=\"tight\")\n", + " sns.pointplot(x=x, errorbar=arg, **kws, capsize=.3, ax=axs[0])\n", + " sns.stripplot(x=x, jitter=.3, ax=axs[1])" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Measures of data spread\n", + "-----------------------\n", + "\n", + "Error bars that represent data spread present a compact display of the distribution, using three numbers where :func:`boxplot` would use 5 or more and :func:`violinplot` would use a complicated algorithm.\n", + "\n", + "Standard deviation error bars\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Standard deviation error bars are the simplest to explain, because the standard deviation is a familiar statistic. It is the average distance from each data point to the sample mean. By default, `errorbar=\"sd\"` will draw error bars at +/- 1 sd around the estimate, but the range can be increased by passing a scaling size parameter. Note that, assuming normally-distributed data, ~68% of the data will lie within one standard deviation, ~95% will lie within two, and ~99.7% will lie within three:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(\"sd\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Percentile interval error bars\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Percentile intervals also represent the range where some amount of the data fall, but they do so by \n", + "computing those percentiles directly from your sample. By default, `errorbar=\"pi\"` will show a 95% interval, ranging from the 2.5 to the 97.5 percentiles. You can choose a different range by passing a size parameter, e.g., to show the inter-quartile range:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars((\"pi\", 50))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The standard deviation error bars will always be symmetrical around the estimate. This can be a problem when the data are skewed, especially if there are natural bounds (e.g., if the data represent a quantity that can only be positive). In some cases, standard deviation error bars may extend to \"impossible\" values. The nonparametric approach does not have this problem, because it can account for asymmetrical spread and will never extend beyond the range of the data." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Measures of estimate uncertainty\n", + "--------------------------------\n", + "\n", + "If your data are a random sample from a larger population, then the mean (or other estimate) will be an imperfect measure of the true population average. Error bars that show estimate uncertainty try to represent the range of likely values for the true parameter.\n", + "\n", + "Standard error bars\n", + "~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The standard error statistic is related to the standard deviation: in fact it is just the standard deviation divided by the square root of the sample size. The default, with `errorbar=\"se\"`, draws an interval +/-1 standard error from the mean:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(\"se\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Confidence interval error bars\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The nonparametric approach to representing uncertainty uses *bootstrapping*: a procedure where the dataset is randomly resampled with replacement a number of times, and the estimate is recalculated from each resample. This procedure creates a distribution of statistics approximating the distribution of values that you could have gotten for your estimate if you had a different sample.\n", + "\n", + "The confidence interval is constructed by taking a percentile interval of the *bootstrap distribution*. By default `errorbar=\"ci\"` draws a 95% confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(\"ci\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The seaborn terminology is somewhat specific, because a confidence interval in statistics can be parametric or nonparametric. To draw a parametric confidence interval, you scale the standard error, using a formula similar to the one mentioned above. For example, an approximate 95% confidence interval can be constructed by taking the mean +/- two standard errors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars((\"se\", 2))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The nonparametric bootstrap has advantages similar to those of the percentile interval: it will naturally adapt to skewed and bounded data in a way that a standard error interval cannot. It is also more general. While the standard error formula is specific to the mean, error bars can be computed using the bootstrap for any estimator:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(\"ci\", estimator=\"median\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Bootstrapping involves randomness, and the error bars will appear slightly different each time you run the code that creates them. A few parameters control this. One sets the number of iterations (`n_boot`): with more iterations, the resulting intervals will be more stable. The other sets the `seed` for the random number generator, which will ensure identical results:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(\"ci\", n_boot=5000, seed=10)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Because of its iterative process, bootstrap intervals can be expensive to compute, especially for large datasets. But because uncertainty decreases with sample size, it may be more informative in that case to use an error bar that represents data spread.\n", + "\n", + "Custom error bars\n", + "~~~~~~~~~~~~~~~~~\n", + "\n", + "If these recipes are not sufficient, it is also possible to pass a generic function to the `errorbar` parameter. This function should take a vector and produce a pair of values representing the minimum and maximum points of the interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_errorbars(lambda x: (x.min(), x.max()))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "(In practice, you could show the full range of the data with `errorbar=(\"pi\", 100)` rather than the custom function shown above).\n", + "\n", + "Note that seaborn functions cannot currently draw error bars from values that have been calculated externally, although matplotlib functions can be used to add such error bars to seaborn plots." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Error bars on regression fits\n", + "-----------------------------\n", + "\n", + "The preceding discussion has focused on error bars shown around parameter estimates for aggregate data. Error bars also arise in seaborn when estimating regression models to visualize relationships. Here, the error bars will be represented by a \"band\" around the regression line:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = np.random.normal(0, 1, 50)\n", + "y = x * 2 + np.random.normal(0, 2, size=x.size)\n", + "sns.regplot(x=x, y=y)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Currently, the error bars on a regression estimate are less flexible, only showing a confidence interval with a size set through `ci=`. This may change in the future." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Are error bars enough?\n", + "----------------------\n", + "\n", + "You should always ask yourself whether it's best to use a plot that displays only a summary statistic and error bar. In many cases, it isn't.\n", + "\n", + "If you are interested in questions about summaries (such as whether the mean value differs between groups or increases over time), aggregation reduces the complexity of the plot and makes those inferences easier. But in doing so, it obscures valuable information about the underlying data points, such as the shape of the distributions and the presence of outliers.\n", + "\n", + "When analyzing your own data, don't be satisfied with summary statistics. Always look at the underlying distributions too. Sometimes, it can be helpful to combine both perspectives into the same figure. Many seaborn functions can help with this task, especially those discussed in the :doc:`categorical tutorial `." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/function_overview.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/function_overview.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3648504cf5b2f65d843ea67a0bcbe318ce1164a6 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/function_overview.ipynb @@ -0,0 +1,496 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _function_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Overview of seaborn plotting functions\n", + "======================================\n", + "\n", + "Most of your interactions with seaborn will happen through a set of plotting functions. Later chapters in the tutorial will explore the specific features offered by each function. This chapter will introduce, at a high-level, the different kinds of functions that you will encounter." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "from IPython.display import HTML\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Similar functions for similar tasks\n", + "-----------------------------------\n", + "\n", + "The seaborn namespace is flat; all of the functionality is accessible at the top level. But the code itself is hierarchically structured, with modules of functions that achieve similar visualization goals through different means. Most of the docs are structured around these modules: you'll encounter names like \"relational\", \"distributional\", and \"categorical\".\n", + "\n", + "For example, the :ref:`distributions module ` defines functions that specialize in representing the distribution of datapoints. This includes familiar methods like the histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.histplot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Along with similar, but perhaps less familiar, options such as kernel density estimation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.kdeplot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Functions within a module share a lot of underlying code and offer similar features that may not be present in other components of the library (such as ``multiple=\"stack\"`` in the examples above). They are designed to facilitate switching between different visual representations as you explore a dataset, because different representations often have complementary strengths and weaknesses." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Figure-level vs. axes-level functions\n", + "-------------------------------------\n", + "\n", + "In addition to the different modules, there is a cross-cutting classification of seaborn functions as \"axes-level\" or \"figure-level\". The examples above are axes-level functions. They plot data onto a single :class:`matplotlib.pyplot.Axes` object, which is the return value of the function.\n", + "\n", + "In contrast, figure-level functions interface with matplotlib through a seaborn object, usually a :class:`FacetGrid`, that manages the figure. Each module has a single figure-level function, which offers a unitary interface to its various axes-level functions. The organization looks a bit like this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "from matplotlib.patches import FancyBboxPatch\n", + "\n", + "f, ax = plt.subplots(figsize=(7, 5))\n", + "f.subplots_adjust(0, 0, 1, 1)\n", + "ax.set_axis_off()\n", + "ax.set(xlim=(0, 1), ylim=(0, 1))\n", + "\n", + "\n", + "modules = \"relational\", \"distributions\", \"categorical\"\n", + "\n", + "pal = sns.color_palette(\"deep\")\n", + "colors = dict(relational=pal[0], distributions=pal[1], categorical=pal[2])\n", + "\n", + "pal = sns.color_palette(\"dark\")\n", + "text_colors = dict(relational=pal[0], distributions=pal[1], categorical=pal[2])\n", + "\n", + "\n", + "functions = dict(\n", + " relational=[\"scatterplot\", \"lineplot\"],\n", + " distributions=[\"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\"],\n", + " categorical=[\"stripplot\", \"swarmplot\", \"boxplot\", \"violinplot\", \"pointplot\", \"barplot\"],\n", + ")\n", + "\n", + "pad = .06\n", + "\n", + "w = .2\n", + "h = .15\n", + "\n", + "xs = np.arange(0, 1, 1 / 3) + pad * 1.05\n", + "y = .7\n", + "\n", + "for x, mod in zip(xs, modules):\n", + " color = colors[mod] + (.2,)\n", + " text_color = text_colors[mod]\n", + " box = FancyBboxPatch((x, y), w, h, f\"round,pad={pad}\", color=\"white\")\n", + " ax.add_artist(box)\n", + " box = FancyBboxPatch((x, y), w, h, f\"round,pad={pad}\", linewidth=1, edgecolor=text_color, facecolor=color)\n", + " ax.add_artist(box)\n", + " ax.text(x + w / 2, y + h / 2, f\"{mod[:3]}plot\\n({mod})\", ha=\"center\", va=\"center\", size=22, color=text_color)\n", + "\n", + " for i, func in enumerate(functions[mod]):\n", + " x_i = x + w / 2\n", + " y_i = y - i * .1 - h / 2 - pad\n", + " box = FancyBboxPatch((x_i - w / 2, y_i - pad / 3), w, h / 4, f\"round,pad={pad / 3}\",\n", + " color=\"white\")\n", + " ax.add_artist(box)\n", + " box = FancyBboxPatch((x_i - w / 2, y_i - pad / 3), w, h / 4, f\"round,pad={pad / 3}\",\n", + " linewidth=1, edgecolor=text_color, facecolor=color)\n", + " ax.add_artist(box)\n", + " ax.text(x_i, y_i, func, ha=\"center\", va=\"center\", size=18, color=text_color)\n", + "\n", + " ax.plot([x_i, x_i], [y, y_i], zorder=-100, color=text_color, lw=1)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "For example, :func:`displot` is the figure-level function for the distributions module. Its default behavior is to draw a histogram, using the same code as :func:`histplot` behind the scenes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To draw a kernel density plot instead, using the same code as :func:`kdeplot`, select it using the ``kind`` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\", kind=\"kde\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You'll notice that the figure-level plots look mostly like their axes-level counterparts, but there are a few differences. Notably, the legend is placed outside the plot. They also have a slightly different shape (more on that shortly).\n", + "\n", + "The most useful feature offered by the figure-level functions is that they can easily create figures with multiple subplots. For example, instead of stacking the three distributions for each species of penguins in the same axes, we can \"facet\" them by plotting each distribution across the columns of the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=penguins, x=\"flipper_length_mm\", hue=\"species\", col=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The figure-level functions wrap their axes-level counterparts and pass the kind-specific keyword arguments (such as the bin size for a histogram) down to the underlying function. That means they are no less flexible, but there is a downside: the kind-specific parameters don't appear in the function signature or docstrings. Some of their features might be less discoverable, and you may need to look at two different pages of the documentation before understanding how to achieve a specific goal." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Axes-level functions make self-contained plots\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The axes-level functions are written to act like drop-in replacements for matplotlib functions. While they add axis labels and legends automatically, they don't modify anything beyond the axes that they are drawn into. That means they can be composed into arbitrarily-complex matplotlib figures with predictable results.\n", + "\n", + "The axes-level functions call :func:`matplotlib.pyplot.gca` internally, which hooks into the matplotlib state-machine interface so that they draw their plots on the \"currently-active\" axes. But they additionally accept an ``ax=`` argument, which integrates with the object-oriented interface and lets you specify exactly where each plot should go:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f, axs = plt.subplots(1, 2, figsize=(8, 4), gridspec_kw=dict(width_ratios=[4, 3]))\n", + "sns.scatterplot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", hue=\"species\", ax=axs[0])\n", + "sns.histplot(data=penguins, x=\"species\", hue=\"species\", shrink=.8, alpha=.8, legend=False, ax=axs[1])\n", + "f.tight_layout()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Figure-level functions own their figure\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "In contrast, figure-level functions cannot (easily) be composed with other plots. By design, they \"own\" their own figure, including its initialization, so there's no notion of using a figure-level function to draw a plot onto an existing axes. This constraint allows the figure-level functions to implement features such as putting the legend outside of the plot.\n", + "\n", + "Nevertheless, it is possible to go beyond what the figure-level functions offer by accessing the matplotlib axes on the object that they return and adding other elements to the plot that way:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "g = sns.relplot(data=tips, x=\"total_bill\", y=\"tip\")\n", + "g.ax.axline(xy1=(10, 2), slope=.2, color=\"b\", dashes=(5, 2))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Customizing plots from a figure-level function\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "The figure-level functions return a :class:`FacetGrid` instance, which has a few methods for customizing attributes of the plot in a way that is \"smart\" about the subplot organization. For example, you can change the labels on the external axes using a single line of code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.relplot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", col=\"sex\")\n", + "g.set_axis_labels(\"Flipper length (mm)\", \"Bill length (mm)\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "While convenient, this does add a bit of extra complexity, as you need to remember that this method is not part of the matplotlib API and exists only when using a figure-level function." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _figure_size_tutorial:\n", + "\n", + "Specifying figure sizes\n", + "^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "To increase or decrease the size of a matplotlib plot, you set the width and height of the entire figure, either in the `global rcParams `_, while setting up the plot (e.g. with the ``figsize`` parameter of :func:`matplotlib.pyplot.subplots`), or by calling a method on the figure object (e.g. :meth:`matplotlib.Figure.set_size_inches`). When using an axes-level function in seaborn, the same rules apply: the size of the plot is determined by the size of the figure it is part of and the axes layout in that figure.\n", + "\n", + "When using a figure-level function, there are several key differences. First, the functions themselves have parameters to control the figure size (although these are actually parameters of the underlying :class:`FacetGrid` that manages the figure). Second, these parameters, ``height`` and ``aspect``, parameterize the size slightly differently than the ``width``, ``height`` parameterization in matplotlib (using the seaborn parameters, ``width = height * aspect``). Most importantly, the parameters correspond to the size of each *subplot*, rather than the size of the overall figure.\n", + "\n", + "To illustrate the difference between these approaches, here is the default output of :func:`matplotlib.pyplot.subplots` with one subplot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f, ax = plt.subplots()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A figure with multiple columns will have the same overall size, but the axes will be squeezed horizontally to fit in the space:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f, ax = plt.subplots(1, 2, sharey=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In contrast, a plot created by a figure-level function will be square. To demonstrate that, let's set up an empty plot by using :class:`FacetGrid` directly. This happens behind the scenes in functions like :func:`relplot`, :func:`displot`, or :func:`catplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(penguins)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When additional columns are added, the figure itself will become wider, so that its subplots have the same size and shape:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(penguins, col=\"sex\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "And you can adjust the size and shape of each subplot without accounting for the total number of rows and columns in the figure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.FacetGrid(penguins, col=\"sex\", height=3.5, aspect=.75)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The upshot is that you can assign faceting variables without stopping to think about how you'll need to adjust the total figure size. A downside is that, when you do want to change the figure size, you'll need to remember that things work a bit differently than they do in matplotlib." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Relative merits of figure-level functions\n", + "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + "\n", + "Here is a summary of the pros and cons that we have discussed above:\n", + "\n", + ".. list-table::\n", + " :header-rows: 1\n", + "\n", + " * - Advantages\n", + " - Drawbacks\n", + " * - Easy faceting by data variables\n", + " - Many parameters not in function signature\n", + " * - Legend outside of plot by default\n", + " - Cannot be part of a larger matplotlib figure\n", + " * - Easy figure-level customization\n", + " - Different API from matplotlib\n", + " * - Different figure size parameterization\n", + " - Different figure size parameterization\n", + "\n", + "On balance, the figure-level functions add some additional complexity that can make things more confusing for beginners, but their distinct features give them additional power. The tutorial documentation mostly uses the figure-level functions, because they produce slightly cleaner plots, and we generally recommend their use for most applications. The one situation where they are not a good choice is when you need to make a complex, standalone figure that composes multiple different plot kinds. At this point, it's recommended to set up the figure using matplotlib directly and to fill in the individual components using axes-level functions." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Combining multiple views on the data\n", + "------------------------------------\n", + "\n", + "Two important plotting functions in seaborn don't fit cleanly into the classification scheme discussed above. These functions, :func:`jointplot` and :func:`pairplot`, employ multiple kinds of plots from different modules to represent multiple aspects of a dataset in a single figure. Both plots are figure-level functions and create figures with multiple subplots by default. But they use different objects to manage the figure: :class:`JointGrid` and :class:`PairGrid`, respectively.\n", + "\n", + ":func:`jointplot` plots the relationship or joint distribution of two variables while adding marginal axes that show the univariate distribution of each one separately:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ":func:`pairplot` is similar — it combines joint and marginal views — but rather than focusing on a single relationship, it visualizes every pairwise combination of variables simultaneously:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(data=penguins, hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Behind the scenes, these functions are using axes-level functions that you have already met (:func:`scatterplot` and :func:`kdeplot`), and they also have a ``kind`` parameter that lets you quickly swap in a different representation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", hue=\"species\", kind=\"hist\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/introduction.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/introduction.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37792610a1ced18bb26e0b05f1515c64fa60db14 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/introduction.ipynb @@ -0,0 +1,469 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _introduction:\n", + "\n", + ".. currentmodule:: seaborn\n", + "\n", + "An introduction to seaborn\n", + "==========================\n", + "\n", + "Seaborn is a library for making statistical graphics in Python. It builds on top of `matplotlib `_ and integrates closely with `pandas `_ data structures.\n", + "\n", + "Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.\n", + "\n", + "Here's an example of what seaborn can do:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Import seaborn\n", + "import seaborn as sns\n", + "\n", + "# Apply the default theme\n", + "sns.set_theme()\n", + "\n", + "# Load an example dataset\n", + "tips = sns.load_dataset(\"tips\")\n", + "\n", + "# Create a visualization\n", + "sns.relplot(\n", + " data=tips,\n", + " x=\"total_bill\", y=\"tip\", col=\"time\",\n", + " hue=\"smoker\", style=\"smoker\", size=\"size\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A few things have happened here. Let's go through them one by one:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "# Import seaborn\n", + "import seaborn as sns" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Seaborn is the only library we need to import for this simple example. By convention, it is imported with the shorthand ``sns``.\n", + "\n", + "Behind the scenes, seaborn uses matplotlib to draw its plots. For interactive work, it's recommended to use a Jupyter/IPython interface in `matplotlib mode `_, or else you'll have to call :func:`matplotlib.pyplot.show` when you want to see the plot." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "# Apply the default theme\n", + "sns.set_theme()" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This uses the matplotlib rcParam system and will affect how all matplotlib plots look, even if you don't make them with seaborn. Beyond the default theme, there are :doc:`several other options `, and you can independently control the style and scaling of the plot to quickly translate your work between presentation contexts (e.g., making a version of your figure that will have readable fonts when projected during a talk). If you like the matplotlib defaults or prefer a different theme, you can skip this step and still use the seaborn plotting functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "# Load an example dataset\n", + "tips = sns.load_dataset(\"tips\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Most code in the docs will use the :func:`load_dataset` function to get quick access to an example dataset. There's nothing special about these datasets: they are just pandas dataframes, and we could have loaded them with :func:`pandas.read_csv` or built them by hand. Most of the examples in the documentation will specify data using pandas dataframes, but seaborn is very flexible about the :doc:`data structures ` that it accepts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "# Create a visualization\n", + "sns.relplot(\n", + " data=tips,\n", + " x=\"total_bill\", y=\"tip\", col=\"time\",\n", + " hue=\"smoker\", style=\"smoker\", size=\"size\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "This plot shows the relationship between five variables in the tips dataset using a single call to the seaborn function :func:`relplot`. Notice how we provided only the names of the variables and their roles in the plot. Unlike when using matplotlib directly, it wasn't necessary to specify attributes of the plot elements in terms of the color values or marker codes. Behind the scenes, seaborn handled the translation from values in the dataframe to arguments that matplotlib understands. This declarative approach lets you stay focused on the questions that you want to answer, rather than on the details of how to control matplotlib.\n", + "\n", + ".. _intro_api_abstraction:\n", + "\n", + "A high-level API for statistical graphics\n", + "-----------------------------------------\n", + "\n", + "There is no universally best way to visualize data. Different questions are best answered by different plots. Seaborn makes it easy to switch between different visual representations by using a consistent dataset-oriented API.\n", + "\n", + "The function :func:`relplot` is named that way because it is designed to visualize many different statistical *relationships*. While scatter plots are often effective, relationships where one variable represents a measure of time are better represented by a line. The :func:`relplot` function has a convenient ``kind`` parameter that lets you easily switch to this alternate representation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dots = sns.load_dataset(\"dots\")\n", + "sns.relplot(\n", + " data=dots, kind=\"line\",\n", + " x=\"time\", y=\"firing_rate\", col=\"align\",\n", + " hue=\"choice\", size=\"coherence\", style=\"choice\",\n", + " facet_kws=dict(sharex=False),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Notice how the ``size`` and ``style`` parameters are used in both the scatter and line plots, but they affect the two visualizations differently: changing the marker area and symbol in the scatter plot vs the line width and dashing in the line plot. We did not need to keep those details in mind, letting us focus on the overall structure of the plot and the information we want it to convey.\n", + "\n", + ".. _intro_stat_estimation:\n", + "\n", + "Statistical estimation\n", + "~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Often, we are interested in the *average* value of one variable as a function of other variables. Many seaborn functions will automatically perform the statistical estimation that is necessary to answer these questions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fmri = sns.load_dataset(\"fmri\")\n", + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", col=\"region\",\n", + " hue=\"event\", style=\"event\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When statistical values are estimated, seaborn will use bootstrapping to compute confidence intervals and draw error bars representing the uncertainty of the estimate.\n", + "\n", + "Statistical estimation in seaborn goes beyond descriptive statistics. For example, it is possible to enhance a scatterplot by including a linear regression model (and its uncertainty) using :func:`lmplot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(data=tips, x=\"total_bill\", y=\"tip\", col=\"time\", hue=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_distributions:\n", + "\n", + "\n", + "Distributional representations\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Statistical analyses require knowledge about the distribution of variables in your dataset. The seaborn function :func:`displot` supports several approaches to visualizing distributions. These include classic techniques like histograms and computationally-intensive approaches like kernel density estimation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=tips, x=\"total_bill\", col=\"time\", kde=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Seaborn also tries to promote techniques that are powerful but less familiar, such as calculating and plotting the empirical cumulative distribution function of the data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.displot(data=tips, kind=\"ecdf\", x=\"total_bill\", col=\"time\", hue=\"smoker\", rug=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_categorical:\n", + "\n", + "Plots for categorical data\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Several specialized plot types in seaborn are oriented towards visualizing categorical data. They can be accessed through :func:`catplot`. These plots offer different levels of granularity. At the finest level, you may wish to see every observation by drawing a \"swarm\" plot: a scatter plot that adjusts the positions of the points along the categorical axis so that they don't overlap:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, kind=\"swarm\", x=\"day\", y=\"total_bill\", hue=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Alternately, you could use kernel density estimation to represent the underlying distribution that the points are sampled from:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, kind=\"violin\", x=\"day\", y=\"total_bill\", hue=\"smoker\", split=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or you could show only the mean value and its confidence interval within each nested category:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.catplot(data=tips, kind=\"bar\", x=\"day\", y=\"total_bill\", hue=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_dataset_funcs:\n", + "\n", + "Multivariate views on complex datasets\n", + "--------------------------------------\n", + "\n", + "Some seaborn functions combine multiple kinds of plots to quickly give informative summaries of a dataset. One, :func:`jointplot`, focuses on a single relationship. It plots the joint distribution between two variables along with each variable's marginal distribution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "penguins = sns.load_dataset(\"penguins\")\n", + "sns.jointplot(data=penguins, x=\"flipper_length_mm\", y=\"bill_length_mm\", hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The other, :func:`pairplot`, takes a broader view: it shows joint and marginal distributions for all pairwise relationships and for each variable, respectively:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(data=penguins, hue=\"species\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_figure_classes:\n", + "\n", + "Lower-level tools for building figures\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "These tools work by combining :doc:`axes-level ` plotting functions with objects that manage the layout of the figure, linking the structure of a dataset to a :doc:`grid of axes `. Both elements are part of the public API, and you can use them directly to create complex figures with only a few more lines of code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "g = sns.PairGrid(penguins, hue=\"species\", corner=True)\n", + "g.map_lower(sns.kdeplot, hue=None, levels=5, color=\".2\")\n", + "g.map_lower(sns.scatterplot, marker=\"+\")\n", + "g.map_diag(sns.histplot, element=\"step\", linewidth=0, kde=True)\n", + "g.add_legend(frameon=True)\n", + "g.legend.set_bbox_to_anchor((.61, .6))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_defaults:\n", + "\n", + "Opinionated defaults and flexible customization\n", + "-----------------------------------------------\n", + "\n", + "Seaborn creates complete graphics with a single function call: when possible, its functions will automatically add informative axis labels and legends that explain the semantic mappings in the plot.\n", + "\n", + "In many cases, seaborn will also choose default values for its parameters based on characteristics of the data. For example, the :doc:`color mappings ` that we have seen so far used distinct hues (blue, orange, and sometimes green) to represent different levels of the categorical variables assigned to ``hue``. When mapping a numeric variable, some functions will switch to a continuous gradient:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=penguins,\n", + " x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"body_mass_g\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When you're ready to share or publish your work, you'll probably want to polish the figure beyond what the defaults achieve. Seaborn allows for several levels of customization. It defines multiple built-in :doc:`themes ` that apply to all figures, its functions have standardized parameters that can modify the semantic mappings for each plot, and additional keyword arguments are passed down to the underlying matplotlib artists, allowing even more control. Once you've created a plot, its properties can be modified through both the seaborn API and by dropping down to the matplotlib layer for fine-grained tweaking:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.set_theme(style=\"ticks\", font_scale=1.25)\n", + "g = sns.relplot(\n", + " data=penguins,\n", + " x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"body_mass_g\",\n", + " palette=\"crest\", marker=\"x\", s=100,\n", + ")\n", + "g.set_axis_labels(\"Bill length (mm)\", \"Bill depth (mm)\", labelpad=10)\n", + "g.legend.set_title(\"Body mass (g)\")\n", + "g.figure.set_size_inches(6.5, 4.5)\n", + "g.ax.margins(.15)\n", + "g.despine(trim=True)" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_matplotlib:\n", + "\n", + "Relationship to matplotlib\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Seaborn's integration with matplotlib allows you to use it across the many environments that matplotlib supports, including exploratory analysis in notebooks, real-time interaction in GUI applications, and archival output in a number of raster and vector formats.\n", + "\n", + "While you can be productive using only seaborn functions, full customization of your graphics will require some knowledge of matplotlib's concepts and API. One aspect of the learning curve for new users of seaborn will be knowing when dropping down to the matplotlib layer is necessary to achieve a particular customization. On the other hand, users coming from matplotlib will find that much of their knowledge transfers.\n", + "\n", + "Matplotlib has a comprehensive and powerful API; just about any attribute of the figure can be changed to your liking. A combination of seaborn's high-level interface and matplotlib's deep customizability will allow you both to quickly explore your data and to create graphics that can be tailored into a `publication quality `_ final product." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _intro_next_steps:\n", + "\n", + "Next steps\n", + "~~~~~~~~~~\n", + "\n", + "You have a few options for where to go next. You might first want to learn how to :doc:`install seaborn `. Once that's done, you can browse the :doc:`example gallery ` to get a broader sense for what kind of graphics seaborn can produce. Or you can read through the rest of the :doc:`user guide and tutorial ` for a deeper discussion of the different tools and what they are designed to accomplish. If you have a specific plot in mind and want to know how to make it, you could check out the :doc:`API reference `, which documents each function's parameters and shows many examples to illustrate usage." + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/objects_interface.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/objects_interface.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8839baf081bb1194cc60a1bcf8b4e574688707f0 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/objects_interface.ipynb @@ -0,0 +1,1090 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "35110bb9-6889-4bd5-b9d6-5a0479131433", + "metadata": {}, + "source": [ + ".. _objects_tutorial:\n", + "\n", + ".. currentmodule:: seaborn.objects\n", + "\n", + "The seaborn.objects interface\n", + "=============================\n", + "\n", + "The `seaborn.objects` namespace was introduced in version 0.12 as a completely new interface for making seaborn plots. It offers a more consistent and flexible API, comprising a collection of composable classes for transforming and plotting data. In contrast to the existing `seaborn` functions, the new interface aims to support end-to-end plot specification and customization without dropping down to matplotlib (although it will remain possible to do so if necessary).\n", + "\n", + ".. note::\n", + " The objects interface is currently experimental and incomplete. It is stable enough for serious use, but there certainly are some rough edges and missing features." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "706badfa-58be-4808-9016-bd0ca3ebaf12", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "import matplotlib as mpl\n", + "tips = sns.load_dataset(\"tips\")\n", + "penguins = sns.load_dataset(\"penguins\").dropna()\n", + "diamonds = sns.load_dataset(\"diamonds\")\n", + "healthexp = sns.load_dataset(\"healthexp\").sort_values([\"Country\", \"Year\"]).query(\"Year <= 2020\")" + ] + }, + { + "cell_type": "raw", + "id": "dd1ceae5-f930-41c2-8a18-f3cf94a161ad", + "metadata": {}, + "source": [ + "Specifying a plot and mapping data\n", + "----------------------------------\n", + "\n", + "The objects interface should be imported with the following convention:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c113156-20ad-4612-a9f5-0071d7fd35dd", + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn.objects as so" + ] + }, + { + "cell_type": "raw", + "id": "6518484e-828b-4e7c-8529-ed6c9e61fa69", + "metadata": {}, + "source": [ + "The `seaborn.objects` namespace will provide access to all of the relevant classes. The most important is :class:`Plot`. You specify plots by instantiating a :class:`Plot` object and calling its methods. Let's see a simple example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2e7f8ad0-9831-464b-9825-60733f110f34", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + " .add(so.Dot())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "52785052-6c80-4f35-87e4-b27df499bd5c", + "metadata": {}, + "source": [ + "This code, which produces a scatter plot, should look reasonably familiar. Just as when using :func:`seaborn.scatterplot`, we passed a tidy dataframe (`penguins`) and assigned two of its columns to the `x` and `y` coordinates of the plot. But instead of starting with the type of chart and then adding some data assignments, here we started with the data assignments and then added a graphical element.\n", + "\n", + "Setting properties\n", + "~~~~~~~~~~~~~~~~~~\n", + "\n", + "The :class:`Dot` class is an example of a :class:`Mark`: an object that graphically represents data values. Each mark will have a number of properties that can be set to change its appearance:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "310bac42-cfe4-4c45-9ddf-27c2cb200a8a", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\")\n", + " .add(so.Dot(color=\"g\", pointsize=4))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "3f817822-dd96-4263-a42e-824f9ca4083a", + "metadata": {}, + "source": [ + "Mapping properties\n", + "~~~~~~~~~~~~~~~~~~\n", + "\n", + "As with seaborn's functions, it is also possible to *map* data values to various graphical properties:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6267e411-1f75-461e-a189-ead4452b2ec6", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " color=\"species\", pointsize=\"body_mass_g\",\n", + " )\n", + " .add(so.Dot())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "b6bfc0bf-cae1-44ed-9f52-e9f748c3877d", + "metadata": {}, + "source": [ + "While this basic functionality is not novel, an important difference from the function API is that properties are mapped using the same parameter names that would set them directly (instead of having `hue` vs. `color`, etc.). What matters is *where* the property is defined: passing a value when you initialize :class:`Dot` will set it directly, whereas assigning a variable when you set up the :class:`Plot` will *map* the corresponding data.\n", + "\n", + "Beyond this difference, the objects interface also allows a much wider range of mark properties to be mapped:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b8637528-4e17-4a41-be1c-2cb4275a5586", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(\n", + " penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n", + " edgecolor=\"sex\", edgewidth=\"body_mass_g\",\n", + " )\n", + " .add(so.Dot(color=\".8\"))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "220930c4-410c-4452-a89e-95045f325cc0", + "metadata": {}, + "source": [ + "Defining groups\n", + "~~~~~~~~~~~~~~~\n", + "\n", + "The :class:`Dot` mark represents each data point independently, so the assignment of a variable to a property only has the effect of changing each dot's appearance. For marks that group or connect observations, such as :class:`Line`, it also determines the number of distinct graphical elements:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95f892e1-8adc-43d3-8b30-84d8c848040a", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Life_Expectancy\", color=\"Country\")\n", + " .add(so.Line())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "6665552c-674b-405e-a3ee-237517649349", + "metadata": {}, + "source": [ + "It is also possible to define a grouping without changing any visual properties, by using `group`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9287beb-7a66-4dcb-bccf-9c5cab2790f4", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Life_Expectancy\", group=\"Country\")\n", + " .add(so.Line())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "be097dfa-e33c-41f5-8b5a-09013cb33e6e", + "metadata": {}, + "source": [ + "Transforming data before plotting\n", + "---------------------------------\n", + "\n", + "Statistical transformation\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "As with many seaborn functions, the objects interface supports statistical transformations. These are performed by :class:`Stat` objects, such as :class:`Agg`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0964d2af-ce53-48b5-b79a-3277b05584dd", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\")\n", + " .add(so.Bar(), so.Agg())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "5ac229b2-3692-4d35-8ba3-e35262f198ce", + "metadata": {}, + "source": [ + "In the function interface, statistical transformations are possible with some visual representations (e.g. :func:`seaborn.barplot`) but not others (e.g. :func:`seaborn.scatterplot`). The objects interface more cleanly separates representation and transformation, allowing you to compose :class:`Mark` and :class:`Stat` objects:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5c2f917d-1cb7-4d33-b8c4-2126a4f91ccc", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\")\n", + " .add(so.Dot(pointsize=10), so.Agg())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "1b9d7688-22f5-4f4a-b58e-71d8ff550b48", + "metadata": {}, + "source": [ + "When forming groups by mapping properties, the :class:`Stat` transformation is applied to each group separately:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "734f9dac-4663-4e51-8070-716c0c0296c6", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\", color=\"sex\")\n", + " .add(so.Dot(pointsize=10), so.Agg())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e60a8e83-c34c-4769-b34f-e0c23c80b870", + "metadata": {}, + "source": [ + "Resolving overplotting\n", + "~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Some seaborn functions also have mechanisms that automatically resolve overplotting, as when :func:`seaborn.barplot` \"dodges\" bars once `hue` is assigned. The objects interface has less complex default behavior. Bars representing multiple groups will overlap by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96653815-7da3-4a77-877a-485b5e7578a4", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\", color=\"sex\")\n", + " .add(so.Bar(), so.Agg())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "06ee3b9f-0ae9-467f-8a40-e340e6f3ce7d", + "metadata": {}, + "source": [ + "Nevertheless, it is possible to compose the :class:`Bar` mark with the :class:`Agg` stat and a second transformation, implemented by :class:`Dodge`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e29792ae-c238-4538-952a-5af81adcefe0", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\", color=\"sex\")\n", + " .add(so.Bar(), so.Agg(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a27dcb37-be58-427b-a722-9039b91b6503", + "metadata": {}, + "source": [ + "The :class:`Dodge` class is an example of a :class:`Move` transformation, which is like a :class:`Stat` but only adjusts `x` and `y` coordinates. The :class:`Move` classes can be applied with any mark, and it's not necessary to use a :class:`Stat` first:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c4509ea7-36fe-4ffb-b784-e945d13fb93c", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\", color=\"sex\")\n", + " .add(so.Dot(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a62e44ae-d6e7-4ab5-af2e-7b49a2031b1d", + "metadata": {}, + "source": [ + "It's also possible to apply multiple :class:`Move` operations in sequence:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "07536818-9ddd-46d1-b10c-b034fa257335", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\", y=\"body_mass_g\", color=\"sex\")\n", + " .add(so.Dot(), so.Dodge(), so.Jitter(.3))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "fd8ed5cc-6ba4-4d03-8414-57a782971d4c", + "metadata": {}, + "source": [ + "Creating variables through transformation\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The :class:`Agg` stat requires both `x` and `y` to already be defined, but variables can also be *created* through statistical transformation. For example, the :class:`Hist` stat requires only one of `x` *or* `y` to be defined, and it will create the other by counting observations:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4b1f2c61-d294-4a85-a383-384d92523c36", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"species\")\n", + " .add(so.Bar(), so.Hist())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "9b33ea0c-f11d-48d7-be7c-13e9993906d8", + "metadata": {}, + "source": [ + "The :class:`Hist` stat will also create new `x` values (by binning) when given numeric data:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "25123abd-75d4-4550-ac86-5281fdabc023", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"flipper_length_mm\")\n", + " .add(so.Bars(), so.Hist())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0dd84c56-eeb3-4904-b957-1677eaebd33c", + "metadata": {}, + "source": [ + "Notice how we used :class:`Bars`, rather than :class:`Bar` for the plot with the continuous `x` axis. These two marks are related, but :class:`Bars` has different defaults and works better for continuous histograms. It also produces a different, more efficient matplotlib artist. You will find the pattern of singular/plural marks elsewhere. The plural version is typically optimized for cases with larger numbers of marks.\n", + "\n", + "Some transforms accept both `x` and `y`, but add *interval* data for each coordinate. This is particularly relevant for plotting error bars after aggregating:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6bc29e9d-d660-4638-80fd-8d77e15d9109", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"body_mass_g\", y=\"species\", color=\"sex\")\n", + " .add(so.Range(), so.Est(errorbar=\"sd\"), so.Dodge())\n", + " .add(so.Dot(), so.Agg(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "3aecc891-1abb-45b2-bf15-c6944820b242", + "metadata": {}, + "source": [ + "Orienting marks and transforms\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "When aggregating, dodging, and drawing a bar, the `x` and `y` variables are treated differently. Each operation has the concept of an *orientation*. The :class:`Plot` tries to determine the orientation automatically based on the data types of the variables. For instance, if we flip the assignment of `species` and `body_mass_g`, we'll get the same plot, but oriented horizontally:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1dd7ebeb-893e-4d27-aeaf-a8ff0cd2cc15", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"body_mass_g\", y=\"species\", color=\"sex\")\n", + " .add(so.Bar(), so.Agg(), so.Dodge())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "382603cb-9ae9-46ed-bceb-b48456781092", + "metadata": {}, + "source": [ + "Sometimes, the correct orientation is ambiguous, as when both the `x` and `y` variables are numeric. In these cases, you can be explicit by passing the `orient` parameter to :meth:`Plot.add`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75277dda-47c4-443c-9454-b8d97fc399e2", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"size\", color=\"time\")\n", + " .add(so.Bar(), so.Agg(), so.Dodge(), orient=\"y\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "dc845c14-03e5-495d-9dc8-3a90f7879346", + "metadata": {}, + "source": [ + "Building and displaying the plot\n", + "--------------------------------\n", + "\n", + "Each example thus far has produced a single subplot with a single kind of mark on it. But :class:`Plot` does not limit you to this.\n", + "\n", + "Adding multiple layers\n", + "~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "More complex single-subplot graphics can be created by calling :meth:`Plot.add` repeatedly. Each time it is called, it defines a *layer* in the plot. For example, we may want to add a scatterplot (now using :class:`Dots`) and then a regression fit:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "922b6d3d-7a81-4921-97f2-953a1fbc69ec", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"tip\")\n", + " .add(so.Dots())\n", + " .add(so.Line(), so.PolyFit())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "f0309733-a86a-4952-bc3b-533d639f0b52", + "metadata": {}, + "source": [ + "Variable mappings that are defined in the :class:`Plot` constructor will be used for all layers:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "604d16b9-383b-4b88-9ed7-fdefed55039a", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"tip\", color=\"time\")\n", + " .add(so.Dots())\n", + " .add(so.Line(), so.PolyFit())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "eb56fb8d-aaa3-4b6e-b311-0354562174b5", + "metadata": {}, + "source": [ + "Layer-specific mappings\n", + "~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "You can also define a mapping such that it is used only in a specific layer. This is accomplished by defining the mapping within the call to :class:`Plot.add` for the relevant layer:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f69a3a38-97e8-40fb-b7d4-95a751ebdcfb", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"tip\")\n", + " .add(so.Dots(), color=\"time\")\n", + " .add(so.Line(color=\".2\"), so.PolyFit())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "b3f94f01-23d4-4f7a-98f8-de93dafc230a", + "metadata": {}, + "source": [ + "Alternatively, define the layer for the entire plot, but *remove* it from a specific layer by setting the variable to `None`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45706bec-3453-4a7e-9ac7-c743baff4da6", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(tips, x=\"total_bill\", y=\"tip\", color=\"time\")\n", + " .add(so.Dots())\n", + " .add(so.Line(color=\".2\"), so.PolyFit(), color=None)\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "295013b3-7d91-4a59-b63b-fe50e642954c", + "metadata": {}, + "source": [ + "To recap, there are three ways to specify the value of a mark property: (1) by mapping a variable in all layers, (2) by mapping a variable in a specific layer, and (3) by setting the property directy:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2341eafd-4d6f-4530-835a-a409d2057d74", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "from io import StringIO\n", + "from IPython.display import SVG\n", + "C = sns.color_palette(\"deep\")\n", + "f = mpl.figure.Figure(figsize=(7, 3))\n", + "ax = f.subplots()\n", + "fontsize = 18\n", + "ax.add_artist(mpl.patches.Rectangle((.13, .53), .45, .09, color=C[0], alpha=.3))\n", + "ax.add_artist(mpl.patches.Rectangle((.22, .43), .235, .09, color=C[1], alpha=.3))\n", + "ax.add_artist(mpl.patches.Rectangle((.49, .43), .26, .09, color=C[2], alpha=.3))\n", + "ax.text(.05, .55, \"Plot(data, 'x', 'y', color='var1')\", size=fontsize, color=\".2\")\n", + "ax.text(.05, .45, \".add(Dot(pointsize=10), marker='var2')\", size=fontsize, color=\".2\")\n", + "annots = [\n", + " (\"Mapped\\nin all layers\", (.35, .65), (0, 45)),\n", + " (\"Set directly\", (.35, .4), (0, -45)),\n", + " (\"Mapped\\nin this layer\", (.63, .4), (0, -45)),\n", + "]\n", + "for i, (text, xy, xytext) in enumerate(annots):\n", + " ax.annotate(\n", + " text, xy, xytext,\n", + " textcoords=\"offset points\", fontsize=14, ha=\"center\", va=\"center\",\n", + " arrowprops=dict(arrowstyle=\"->\", color=C[i]), color=C[i],\n", + " )\n", + "ax.set_axis_off()\n", + "f.subplots_adjust(0, 0, 1, 1)\n", + "f.savefig(s:=StringIO(), format=\"svg\")\n", + "SVG(s.getvalue())" + ] + }, + { + "cell_type": "raw", + "id": "cf2d8e39-d332-41f4-b327-2ac352878e58", + "metadata": {}, + "source": [ + "Faceting and pairing subplots\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "As with seaborn's figure-level functions (:func:`seaborn.displot`, :func:`seaborn.catplot`, etc.), the :class:`Plot` interface can also produce figures with multiple \"facets\", or subplots containing subsets of data. This is accomplished with the :meth:`Plot.facet` method:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "af737dfd-1cb2-418d-9f52-1deb93154a92", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"flipper_length_mm\")\n", + " .facet(\"species\")\n", + " .add(so.Bars(), so.Hist())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "81c2a445-5ae1-4272-8a6c-8bfe1f3b907f", + "metadata": {}, + "source": [ + "Call :meth:`Plot.facet` with the variables that should be used to define the columns and/or rows of the plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b7b3495f-9a38-4976-b718-ce3672b8c186", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"flipper_length_mm\")\n", + " .facet(col=\"species\", row=\"sex\")\n", + " .add(so.Bars(), so.Hist())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "8b7fe085-acd2-46d2-81f6-a806dec338d3", + "metadata": {}, + "source": [ + "You can facet using a variable with a larger number of levels by \"wrapping\" across the other dimension:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d62d2310-ae33-4b42-bdea-7b7456afd640", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Life_Expectancy\")\n", + " .facet(col=\"Country\", wrap=3)\n", + " .add(so.Line())\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "86ecbeee-3ac2-41eb-b79e-9d6ed026061d", + "metadata": {}, + "source": [ + "All layers will be faceted unless you explicitly exclude them, which can be useful for providing additional context on each subplot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c38be724-8564-4fa0-861c-1d96ffbbda20", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(healthexp, x=\"Year\", y=\"Life_Expectancy\")\n", + " .facet(\"Country\", wrap=3)\n", + " .add(so.Line(alpha=.3), group=\"Country\", col=None)\n", + " .add(so.Line(linewidth=3))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "f97dad75-65e6-47fd-9fc4-08a8f2cb49ee", + "metadata": {}, + "source": [ + "An alternate way to produce subplots is :meth:`Plot.pair`. Like :class:`seaborn.PairGrid`, this draws all of the data on each subplot, using different variables for the x and/or y coordinates:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6350e99-2c70-4a96-87eb-74756a0fa335", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, y=\"body_mass_g\", color=\"species\")\n", + " .pair(x=[\"bill_length_mm\", \"bill_depth_mm\"])\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "4deea650-b4b9-46ea-876c-2e5a3a258649", + "metadata": {}, + "source": [ + "You can combine faceting and pairing so long as the operations add subplots on opposite dimensions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9de7948c-4c43-4116-956c-cbcb84d8652c", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, y=\"body_mass_g\", color=\"species\")\n", + " .pair(x=[\"bill_length_mm\", \"bill_depth_mm\"])\n", + " .facet(row=\"sex\")\n", + " .add(so.Dots())\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0a0febe3-9daf-4271-aef9-9637d59aaf10", + "metadata": {}, + "source": [ + "Integrating with matplotlib\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "There may be cases where you want multiple subplots to appear in a figure with a more complex structure than what :meth:`Plot.facet` or :meth:`Plot.pair` can provide. The current solution is to delegate figure setup to matplotlib and to supply the matplotlib object that :class:`Plot` should use with the :meth:`Plot.on` method. This object can be either a :class:`matplotlib.axes.Axes`, :class:`matplotlib.figure.Figure`, or :class:`matplotlib.figure.SubFigure`; the latter is most useful for constructing bespoke subplot layouts:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b046466d-f6c2-43fa-9ae9-f40a292a82b7", + "metadata": {}, + "outputs": [], + "source": [ + "f = mpl.figure.Figure(figsize=(8, 4))\n", + "sf1, sf2 = f.subfigures(1, 2)\n", + "(\n", + " so.Plot(penguins, x=\"body_mass_g\", y=\"flipper_length_mm\")\n", + " .add(so.Dots())\n", + " .on(sf1)\n", + " .plot()\n", + ")\n", + "(\n", + " so.Plot(penguins, x=\"body_mass_g\")\n", + " .facet(row=\"sex\")\n", + " .add(so.Bars(), so.Hist())\n", + " .on(sf2)\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "7074f599-8b9f-4b77-9e15-55349592c747", + "metadata": {}, + "source": [ + "Building and displaying the plot\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "An important thing to know is that :class:`Plot` methods clone the object they are called on and return that clone instead of updating the object in place. This means that you can define a common plot spec and then produce several variations on it.\n", + "\n", + "So, take this basic specification:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b79b2148-b867-4e96-9b84-b3fc44ad0c82", + "metadata": {}, + "outputs": [], + "source": [ + "p = so.Plot(healthexp, \"Year\", \"Spending_USD\", color=\"Country\")" + ] + }, + { + "cell_type": "raw", + "id": "135f89e5-c41e-4c6c-9865-5413787bdc62", + "metadata": {}, + "source": [ + "We could use it to draw a line plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10722a20-dc8c-4421-a433-8ff21fed9495", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Line())" + ] + }, + { + "cell_type": "raw", + "id": "f9db1184-f352-41b8-a45a-02ff6eb85071", + "metadata": {}, + "source": [ + "Or perhaps a stacked area plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea2ad629-c718-44a9-92af-144728094cd5", + "metadata": {}, + "outputs": [], + "source": [ + "p.add(so.Area(), so.Stack())" + ] + }, + { + "cell_type": "raw", + "id": "17fb2676-6199-4a2c-9f10-3d5aebb7a285", + "metadata": {}, + "source": [ + "The :class:`Plot` methods are fully declarative. Calling them updates the plot spec, but it doesn't actually do any plotting. One consequence of this is that methods can be called in any order, and many of them can be called multiple times.\n", + "\n", + "When does the plot actually get rendered? :class:`Plot` is optimized for use in notebook environments. The rendering is automatically triggered when the :class:`Plot` gets displayed in the Jupyter REPL. That's why we didn't see anything in the example above, where we defined a :class:`Plot` but assigned it to `p` rather than letting it return out to the REPL.\n", + "\n", + "To see a plot in a notebook, either return it from the final line of a cell or call Jupyter's built-in `display` function on the object. The notebook integration bypasses :mod:`matplotlib.pyplot` entirely, but you can use its figure-display machinery in other contexts by calling :meth:`Plot.show`.\n", + "\n", + "You can also save the plot to a file (or buffer) by calling :meth:`Plot.save`." + ] + }, + { + "cell_type": "raw", + "id": "abfa0384-af88-4409-a119-912601a14f13", + "metadata": {}, + "source": [ + "Customizing the appearance\n", + "--------------------------\n", + "\n", + "The new interface aims to support a deep amount of customization through :class:`Plot`, reducing the need to switch gears and use matplotlib functionality directly. (But please be patient; not all of the features needed to achieve this goal have been implemented!)\n", + "\n", + "Parameterizing scales\n", + "~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "All of the data-dependent properties are controlled by the concept of a :class:`Scale` and the :meth:`Plot.scale` method. This method accepts several different types of arguments. One possibility, which is closest to the use of scales in matplotlib, is to pass the name of a function that transforms the coordinates:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5acfe6d2-144a-462d-965b-2900fb619eac", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, x=\"carat\", y=\"price\")\n", + " .add(so.Dots())\n", + " .scale(y=\"log\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "ccff884b-53cb-4c15-aab2-f5d4e5551d72", + "metadata": {}, + "source": [ + ":meth:`Plot.scale` can also control the mappings for semantic properties like `color`. You can directly pass it any argument that you would pass to the `palette` parameter in seaborn's function interface:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f243a31-d7da-43d2-8dc4-aad1b584ff48", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, x=\"carat\", y=\"price\", color=\"clarity\")\n", + " .add(so.Dots())\n", + " .scale(color=\"flare\")\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "4fdf291e-a008-4a8e-8ced-a24f78d9b49f", + "metadata": {}, + "source": [ + "Another option is to provide a tuple of `(min, max)` values, controlling the range that the scale should map into. This works both for numeric properties and for colors:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4cdc12ee-83f9-4472-b198-85bfe5cf0e4f", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, x=\"carat\", y=\"price\", color=\"clarity\", pointsize=\"carat\")\n", + " .add(so.Dots())\n", + " .scale(color=(\"#88c\", \"#555\"), pointsize=(2, 10))\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e326bf46-a296-4997-8e91-6531a7eef304", + "metadata": {}, + "source": [ + "For additional control, you can pass a :class:`Scale` object. There are several different types of :class:`Scale`, each with appropriate parameters. For example, :class:`Continuous` lets you define the input domain (`norm`), the output range (`values`), and the function that maps between them (`trans`), while :class:`Nominal` allows you to specify an ordering:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "53682db4-2ba4-4dfd-80c2-1fef466cfab2", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, x=\"carat\", y=\"price\", color=\"carat\", marker=\"cut\")\n", + " .add(so.Dots())\n", + " .scale(\n", + " color=so.Continuous(\"crest\", norm=(0, 3), trans=\"sqrt\"),\n", + " marker=so.Nominal([\"o\", \"+\", \"x\"], order=[\"Ideal\", \"Premium\", \"Good\"]),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "7bf112fe-136d-4e63-a397-1e7d2ff4f543", + "metadata": {}, + "source": [ + "Customizing legends and ticks\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The :class:`Scale` objects are also how you specify which values should appear as tick labels / in the legend, along with how they appear. For example, the :meth:`Continuous.tick` method lets you control the density or locations of the ticks, and the :meth:`Continuous.label` method lets you modify the format:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f8e821f-bd19-4af1-bb66-488593b3c968", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(diamonds, x=\"carat\", y=\"price\", color=\"carat\")\n", + " .add(so.Dots())\n", + " .scale(\n", + " x=so.Continuous().tick(every=0.5),\n", + " y=so.Continuous().label(like=\"${x:.0f}\"),\n", + " color=so.Continuous().tick(at=[1, 2, 3, 4]),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "4f6646c9-084b-49ae-ad6f-39c0bd12fc4e", + "metadata": {}, + "source": [ + "Customizing limits, labels, and titles\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + ":class:`Plot` has a number of methods for simple customization, including :meth:`Plot.label`, :meth:`Plot.limit`, and :meth:`Plot.share`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9586669-35ea-4784-9594-ea375a06aec0", + "metadata": {}, + "outputs": [], + "source": [ + "(\n", + " so.Plot(penguins, x=\"body_mass_g\", y=\"species\", color=\"island\")\n", + " .facet(col=\"sex\")\n", + " .add(so.Dot(), so.Jitter(.5))\n", + " .share(x=False)\n", + " .limit(y=(2.5, -.5))\n", + " .label(\n", + " x=\"Body mass (g)\", y=\"\",\n", + " color=str.capitalize,\n", + " title=\"{} penguins\".format,\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "3b38607a-9b41-49c0-8031-e05bc87701c8", + "metadata": {}, + "source": [ + "Theme customization\n", + "~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Finally, :class:`Plot` supports data-independent theming through the :class:`Plot.theme` method. Currently, this method accepts a dictionary of matplotlib rc parameters. You can set them directly and/or pass a package of parameters from seaborn's theming functions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2df40831-fd41-4b76-90ff-042aecd694d4", + "metadata": {}, + "outputs": [], + "source": [ + "from seaborn import axes_style\n", + "theme_dict = {**axes_style(\"whitegrid\"), \"grid.linestyle\": \":\"}\n", + "so.Plot().theme(theme_dict)" + ] + }, + { + "cell_type": "raw", + "id": "475d5157-5e88-473e-991f-528219ed3744", + "metadata": {}, + "source": [ + "To change the theme for all :class:`Plot` instances, update the settings in :attr:`Plot.config:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "41ac347c-766f-495c-8a7f-43fee8cad29a", + "metadata": {}, + "outputs": [], + "source": [ + "so.Plot.config.theme.update(theme_dict)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/properties.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/properties.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..70de0e9ea2fc513e2d1c36e1be5ffe26aa28036f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/properties.ipynb @@ -0,0 +1,1127 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "6cb222bb-4781-48b6-9675-c0ba195b5efb", + "metadata": {}, + "source": [ + ".. _properties_tutorial:\n", + "\n", + "Properties of Mark objects\n", + "===========================" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae9d52dc-55ad-4804-a533-f2b724d0b85b", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib as mpl\n", + "import seaborn.objects as so\n", + "from seaborn import axes_style, color_palette" + ] + }, + { + "cell_type": "raw", + "id": "dd828c60-3895-46e4-a2f4-782a6e6cd9a6", + "metadata": {}, + "source": [ + "Coordinate properties\n", + "---------------------" + ] + }, + { + "cell_type": "raw", + "id": "fa97cc40-f02f-477b-90ec-a764b7253b68", + "metadata": {}, + "source": [ + ".. _coordinate_property:\n", + "\n", + "x, y, xmin, xmax, ymin, ymax\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Coordinate properties determine where a mark is drawn on a plot. Canonically, the `x` coordinate is the horizontal positon and the `y` coordinate is the vertical position. Some marks accept a span (i.e., `min`, `max`) parameterization for one or both variables. Others may accept `x` and `y` but also use a `baseline` parameter to show a span. The layer's `orient` parameter determines how this works.\n", + "\n", + "If a variable does not contain numeric data, its scale will apply a conversion so that data can be drawn on a screen. For instance, :class:`Nominal` scales assign an integer index to each distinct category, and :class:`Temporal` scales represent dates as the number of days from a reference \"epoch\":" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b418365-b99c-45d6-bf1e-e347e2b9012a", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "(\n", + " so.Plot(y=[0, 0, 0])\n", + " .pair(x=[\n", + " [1, 2, 3],\n", + " [\"A\", \"B\", \"C\"],\n", + " np.array([\"2020-01-01\", \"2020-02-01\", \"2020-03-01\"], dtype=\"datetime64\"),\n", + " ])\n", + " .limit(\n", + " x0=(0, 10),\n", + " x1=(-.5, 2.5),\n", + " x2=(pd.Timestamp(\"2020-01-01\"), pd.Timestamp(\"2020-03-01\"))\n", + " )\n", + " .scale(y=so.Continuous().tick(count=0), x2=so.Temporal().label(concise=True))\n", + " .layout(size=(7, 1), engine=\"tight\")\n", + " .label(x0=\"Continuous\", x1=\"Nominal\", x2=\"Temporal\")\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " })\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0ae06665-2ce5-470d-b90a-02d990221fc5", + "metadata": {}, + "source": [ + "A :class:`Continuous` scale can also apply a nonlinear transform between data values and spatial positions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b731a3bb-a52e-4b12-afbb-b036753adcbe", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "(\n", + " so.Plot(y=[0, 0, 0])\n", + " .pair(x=[[1, 10, 100], [-100, 0, 100], [0, 10, 40]])\n", + " .limit(\n", + " )\n", + " .add(so.Dot(marker=\"\"))\n", + " .scale(\n", + " y=so.Continuous().tick(count=0),\n", + " x0=so.Continuous(trans=\"log\"),\n", + " x1=so.Continuous(trans=\"symlog\").tick(at=[-100, -10, 0, 10, 100]),\n", + " x2=so.Continuous(trans=\"sqrt\").tick(every=10),\n", + " )\n", + " .layout(size=(7, 1), engine=\"tight\")\n", + " .label(x0=\"trans='log'\", x1=\"trans='symlog'\", x2=\"trans='sqrt'\")\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"axes.labelpad\": 8,\n", + " })\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e384941a-da38-4e12-997d-d750b19b1fa6", + "metadata": { + "tags": [ + "hide-input", + "hide" + ] + }, + "outputs": [], + "source": [ + "# Hiding from the page but keeping around for now\n", + "(\n", + " so.Plot()\n", + " .add(\n", + " so.Dot(edgewidth=3, stroke=3),\n", + " so.Dodge(by=[\"group\"]),\n", + " x=[\"A\", \"A\", \"A\", \"A\", \"A\"],\n", + " y=[1.75, 2.25, 2.75, 2.0, 2.5],\n", + " color=[1, 2, 3, 1, 3],\n", + " marker=[mpl.markers.MarkerStyle(x) for x in \"os^+o\"],\n", + " pointsize=(9, 9, 9, 13, 10),\n", + " fill=[True, False, True, True, False],\n", + " group=[1, 2, 3, 4, 5], width=.5, legend=False,\n", + " )\n", + " .add(\n", + " so.Bar(edgewidth=2.5, alpha=.2, width=.9),\n", + " so.Dodge(gap=.05),\n", + " x=[\"B\", \"B\", \"B\",], y=[2, 2.5, 1.75], color=[1, 2, 3],\n", + " legend=False,\n", + " )\n", + " .add(\n", + " so.Range({\"capstyle\": \"round\"}, linewidth=3),\n", + " so.Dodge(by=[\"group\"]),\n", + " x=[\"C\", \"C\", \"C\"], ymin=[1.5, 1.75, 1.25], ymax=[2.5, 2.75, 2.25],\n", + " color=[1, 2, 2], linestyle=[\"-\", \"-\", \":\"],\n", + " group=[1, 2, 3], width=.5, legend=False,\n", + " )\n", + " .layout(size=(4, 4), engine=None)\n", + " .limit(x=(-.5, 2.5), y=(0, 3))\n", + " .label(x=\"X Axis (nominal)\", y=\"Y Axis (continuous)\")\n", + " .scale(\n", + " color=\"dark:C0_r\", #None,\n", + " fill=None, marker=None,\n", + " pointsize=None, linestyle=None,\n", + " y=so.Continuous().tick(every=1, minor=1)\n", + " )\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " \"axes.spines.top\": False, \"axes.spines.right\": False,\n", + " \"axes.labelsize\": 14,\n", + " })\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "8279d74f-0cd0-4ba8-80ed-c6051541d956", + "metadata": {}, + "source": [ + "Color properties\n", + "----------------" + ] + }, + { + "cell_type": "raw", + "id": "fca25527-6bbe-42d6-beea-a996a46d9761", + "metadata": {}, + "source": [ + ".. _color_property:\n", + "\n", + "color, fillcolor, edgecolor\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "All marks can be given a `color`, and many distinguish between the color of the mark's \"edge\" and \"fill\". Often, simply using `color` will set both, while the more-specific properties allow further control:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff7a1e64-7b02-45b8-b1e7-d7ec2bf1e7f7", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "no_spines = {\n", + " f\"axes.spines.{side}\": False\n", + " for side in [\"left\", \"right\", \"bottom\", \"top\"]\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1dda4c42-31f4-4316-baad-f30a465d3fd9", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "color_mark = so.Dot(marker=\"s\", pointsize=20, edgewidth=2.5, alpha=.7, edgealpha=1)\n", + "color_plot = (\n", + " so.Plot()\n", + " .theme({\n", + " **axes_style(\"white\"),\n", + " **no_spines,\n", + " \"axes.titlesize\": 15,\n", + " \"figure.subplot.wspace\": .1,\n", + " \"axes.xmargin\": .1,\n", + " })\n", + " .scale(\n", + " x=so.Continuous().tick(count=0),\n", + " y=so.Continuous().tick(count=0),\n", + " color=None, edgecolor=None,\n", + " )\n", + " .layout(size=(9, .5), engine=None)\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "54fc98b4-dc4c-45e1-a2a7-840a724fc746", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "n = 6\n", + "rgb = [f\"C{i}\" for i in range(n)]\n", + "(\n", + " color_plot\n", + " .facet([\"color\"] * n + [\"edgecolor\"] * n + [\"fillcolor\"] * n)\n", + " .add(\n", + " color_mark,\n", + " x=np.tile(np.arange(n), 3),\n", + " y=np.zeros(n * 3),\n", + " color=rgb + [\".8\"] * n + rgb,\n", + " edgecolor=rgb + rgb + [\".3\"] * n,\n", + " legend=False,\n", + " )\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "0dc26a01-6290-44f4-9815-5cea531207e2", + "metadata": {}, + "source": [ + "When the color property is mapped, the default palette depends on the type of scale. Nominal scales use discrete, unordered hues, while continuous scales (including temporal ones) use a sequential gradient:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6927a0d3-687b-4ca0-a425-0376b39f1b1f", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "n = 9\n", + "rgb = color_palette(\"deep\", n) + color_palette(\"ch:\", n)\n", + "(\n", + " color_plot\n", + " .facet([\"nominal\"] * n + [\"continuous\"] * n)\n", + " .add(\n", + " color_mark,\n", + " x=list(range(n)) * 2,\n", + " y=[0] * n * 2,\n", + " color=rgb,\n", + " legend=False,\n", + " )\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "e79d0da7-a53e-468c-9952-726eeae810d1", + "metadata": {}, + "source": [ + ".. note::\n", + " The default continuous scale is subject to change in future releases to improve discriminability.\n", + "\n", + "Color scales are parameterized by the name of a palette, such as `'viridis'`, `'rocket'`, or `'deep'`. Some palette names can include parameters, including simple gradients (e.g. `'dark:blue'`) or the cubehelix system (e.g. `'ch:start=.2,rot=-.4``). See the :doc:`color palette tutorial ` for guidance on making an appropriate selection.\n", + "\n", + "Continuous scales can also be parameterized by a tuple of colors that the scale should interpolate between. When using a nominal scale, it is possible to provide either the name of the palette (which will be discretely-sampled, if necessary), a list of individual color values, or a dictionary directly mapping data values to colors.\n", + "\n", + "Individual colors may be specified `in a wide range of formats `_. These include indexed references to the current color cycle (`'C0'`), single-letter shorthands (`'b'`), grayscale values (`'.4'`), RGB hex codes (`'#4c72b0'`), X11 color names (`'seagreen'`), and XKCD color survey names (`'purpleish'`):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ce7300dc-0ed2-4eb3-bd6f-2e42280f5e54", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "color_dict = {\n", + " \"cycle\": [\"C0\", \"C1\", \"C2\"],\n", + " \"short\": [\"r\", \"y\", \"b\"],\n", + " \"gray\": [\".3\", \".7\", \".5\"],\n", + " \"hex\": [\"#825f87\", \"#05696b\", \"#de7e5d\"],\n", + " \"X11\": [\"seagreen\", \"sienna\", \"darkblue\"],\n", + " \"XKCD\": [\"xkcd:gold\", \"xkcd:steel\", \"xkcd:plum\"],\n", + "}\n", + "groups = [k for k in color_dict for _ in range(3)]\n", + "colors = [c for pal in color_dict.values() for c in pal]\n", + "(\n", + " so.Plot(\n", + " x=[0] * len(colors),\n", + " y=[f\"'{c}'\" for c in colors],\n", + " color=colors,\n", + " )\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **no_spines,\n", + " \"axes.ymargin\": .2,\n", + " \"axes.titlesize\": 14,\n", + " \n", + " })\n", + " .facet(groups)\n", + " .layout(size=(8, 1.15), engine=\"constrained\")\n", + " .scale(x=so.Continuous().tick(count=0))\n", + " .add(color_mark)\n", + " .limit(x=(-.2, .5))\n", + " # .label(title=\"{} \".format)\n", + " .label(title=\"\")\n", + " .scale(color=None)\n", + " .share(y=False)\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "4ea6ac35-2a73-4dec-8b9b-bf15ba67f01b", + "metadata": {}, + "source": [ + ".. _alpha_property:\n", + "\n", + "alpha, fillalpha, edgealpha\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The `alpha` property determines the mark's opacity. Lowering the alpha can be helpful for representing density in the case of overplotting:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e73839d2-27c4-42b8-8587-9f6e99c8a464", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "rng = np.random.default_rng(3)\n", + "n_samp = 300\n", + "x = 1 - rng.exponential(size=n_samp)\n", + "y = rng.uniform(-1, 1, size=n_samp)\n", + "keep = np.sqrt(x ** 2 + y ** 2) < 1\n", + "x, y = x[keep], y[keep]\n", + "n = keep.sum()\n", + "alpha_vals = np.linspace(.1, .9, 9).round(1)\n", + "xs = np.concatenate([x for _ in alpha_vals])\n", + "ys = np.concatenate([y for _ in alpha_vals])\n", + "alphas = np.repeat(alpha_vals, n)\n", + "(\n", + " so.Plot(x=xs, y=ys, alpha=alphas)\n", + " .facet(alphas)\n", + " .add(so.Dot(color=\".2\", pointsize=3))\n", + " .scale(\n", + " alpha=None,\n", + " x=so.Continuous().tick(count=0),\n", + " y=so.Continuous().tick(count=0)\n", + " )\n", + " .layout(size=(9, 1), engine=None)\n", + " .theme({\n", + " **axes_style(\"white\"),\n", + " **no_spines,\n", + " })\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "a551732e-e8f5-45f0-9345-7ef45248d9d7", + "metadata": {}, + "source": [ + "Mapping the `alpha` property can also be useful even when marks do not overlap because it conveys a sense of importance and can be combined with a `color` scale to represent two variables. Moreover, colors with lower alpha appear less saturated, which can improve the appearance of larger filled marks (such as bars).\n", + "\n", + "As with `color`, some marks define separate `edgealpha` and `fillalpha` properties for additional control." + ] + }, + { + "cell_type": "raw", + "id": "77d168e4-0539-409f-8542-750d3981e22b", + "metadata": {}, + "source": [ + "Style properties\n", + "----------------" + ] + }, + { + "cell_type": "raw", + "id": "95e342fa-1086-4e63-81ae-dce1c628df9b", + "metadata": {}, + "source": [ + ".. _fill_property:\n", + "\n", + "fill\n", + "~~~~\n", + "\n", + "The `fill` property is relevant to marks with a distinction between the edge and interior and determines whether the interior is visible. It is a boolean state: `fill` can be set only to `True` or `False`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5fb3b839-8bae-4392-b5f0-70dfc5a33c7a", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "nan = float(\"nan\")\n", + "x_bar = [0, 1]\n", + "y_bar = [2, 1]\n", + "f_bar = [True, False]\n", + "\n", + "x_dot = [2.2, 2.5, 2.8, 3.2, 3.5, 3.8]\n", + "y_dot = [1.2, 1.7, 1.4, 0.7, 1.2, 0.9]\n", + "f_dot = [True, True, True, False, False, False]\n", + "\n", + "xx = np.linspace(0, .8, 100)\n", + "yy = xx ** 2 * np.exp(-xx * 10)\n", + "x_area = list(4.5 + xx) + list(5.5 + xx)\n", + "y_area = list(yy / yy.max() * 2) + list(yy / yy.max())\n", + "f_area = [True] * 100 + [False] * 100\n", + "\n", + "(\n", + " so.Plot()\n", + " .add(\n", + " so.Bar(color=\".3\", edgecolor=\".2\", edgewidth=2.5),\n", + " x=x_bar + [nan for _ in x_dot + x_area],\n", + " y=y_bar + [nan for _ in y_dot + y_area],\n", + " fill=f_bar + [nan for _ in f_dot + f_area]\n", + " )\n", + " .add(\n", + " so.Dot(color=\".2\", pointsize=13, stroke=2.5),\n", + " x=[nan for _ in x_bar] + x_dot + [nan for _ in x_area],\n", + " y=[nan for _ in y_bar] + y_dot + [nan for _ in y_area],\n", + " fill=[nan for _ in f_bar] + f_dot + [nan for _ in f_area],\n", + " )\n", + " .add(\n", + " so.Area(color=\".2\", edgewidth=2.5),\n", + " x=[nan for _ in x_bar + x_dot] + x_area,\n", + " y=[nan for _ in y_bar + y_dot] + y_area,\n", + " fill=[nan for _ in f_bar + f_dot] + f_area,\n", + " )\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " \"axes.spines.left\": False,\n", + " \"axes.spines.top\": False,\n", + " \"axes.spines.right\": False,\n", + " \"xtick.labelsize\": 14,\n", + " })\n", + " .layout(size=(9, 1.25), engine=None)\n", + " .scale(\n", + " fill=None,\n", + " x=so.Continuous().tick(at=[0, 1, 2.5, 3.5, 4.8, 5.8]).label(\n", + " like={\n", + " 0: True, 1: False, 2.5: True, 3.5: False, 4.8: True, 5.8: False\n", + " }.get,\n", + " ),\n", + " y=so.Continuous().tick(count=0),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "119741b0-9eca-45a1-983e-35effc49c7fa", + "metadata": {}, + "source": [ + ".. _marker_property:\n", + "\n", + "marker\n", + "~~~~~~\n", + "\n", + "The `marker` property is relevant for dot marks and some line marks. The API for specifying markers is very flexible, as detailed in the matplotlib API docs: :mod:`matplotlib.markers`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ba9c5aa-3d9c-47c7-8aee-5851e1f3c4dd", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "marker_plot = (\n", + " so.Plot()\n", + " .scale(marker=None, y=so.Continuous().tick(count=0))\n", + " .layout(size=(10, .5), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " \"axes.spines.left\": False,\n", + " \"axes.spines.top\": False,\n", + " \"axes.spines.right\": False,\n", + " \"xtick.labelsize\":12,\n", + " \"axes.xmargin\": .02,\n", + " })\n", + "\n", + ")\n", + "marker_mark = so.Dot(pointsize=15, color=\".2\", stroke=1.5)" + ] + }, + { + "cell_type": "raw", + "id": "3c07a874-18a1-485a-8d65-70ea3f246340", + "metadata": {}, + "source": [ + "Markers can be specified using a number of simple string codes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6a764efd-df55-412b-8a01-8eba6f897893", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "marker_codes = [\n", + " \"o\", \"^\", \"v\", \"<\", \">\",\"s\", \"D\", \"d\", \"p\", \"h\", \"H\", \"8\",\n", + " \"X\", \"*\", \".\", \"P\", \"x\", \"+\", \"1\", \"2\", \"3\", \"4\", \"|\", \"_\",\n", + "]\n", + "x, y = [f\"'{m}'\" for m in marker_codes], [0] * len(marker_codes)\n", + "marker_objs = [mpl.markers.MarkerStyle(m) for m in marker_codes]\n", + "marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()" + ] + }, + { + "cell_type": "raw", + "id": "1c614f08-3aa4-450d-bfe2-3295c29155d5", + "metadata": {}, + "source": [ + "They can also be programatically generated using a `(num_sides, fill_style, angle)` tuple:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c9c1efe7-33e1-4add-9c4e-567d8dfbb821", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "marker_codes = [\n", + " (4, 0, 0), (4, 0, 45), (8, 0, 0),\n", + " (4, 1, 0), (4, 1, 45), (8, 1, 0),\n", + " (4, 2, 0), (4, 2, 45), (8, 2, 0),\n", + "]\n", + "x, y = [f\"{m}\" for m in marker_codes], [0] * len(marker_codes)\n", + "marker_objs = [mpl.markers.MarkerStyle(m) for m in marker_codes]\n", + "marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()" + ] + }, + { + "cell_type": "raw", + "id": "dc518508-cb08-4508-a7f3-5762841da6fc", + "metadata": {}, + "source": [ + "See the matplotlib docs for additional formats, including mathtex character codes (`'$...$'`) and arrays of vertices.\n", + "\n", + "A marker property is always mapped with a nominal scale; there is no inherent ordering to the different shapes. If no scale is provided, the plot will programmatically generate a suitably large set of unique markers:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3466dc10-07a5-470f-adac-c3c05326945d", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "from seaborn._core.properties import Marker\n", + "n = 14\n", + "marker_objs = Marker()._default_values(n)\n", + "x, y = list(map(str, range(n))), [0] * n\n", + "marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()" + ] + }, + { + "cell_type": "raw", + "id": "30916c65-6d4c-4294-a5e2-58af8b9392f3", + "metadata": {}, + "source": [ + "While this ensures that the shapes are technically distinct, bear in mind that — in most cases — it will be difficult to tell the markers apart if more than a handful are used in a single plot.\n", + "\n", + ".. note::\n", + " The default marker scale is subject to change in future releases to improve discriminability." + ] + }, + { + "cell_type": "raw", + "id": "3b1d0630-808a-4099-8bd0-768718f86f72", + "metadata": {}, + "source": [ + ".. _linestyle_property:\n", + "\n", + "linestyle, edgestyle\n", + "~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The `linestyle` property is relevant to line marks, and the `edgestyle` propety is relevant to a number of marks with \"edges. Both properties determine the \"dashing\" of a line in terms of on-off segments.\n", + "\n", + "Dashes can be specified with a small number of shorthand codes (`'-'`, `'--'`, `'-.'`, and `':'`) or programatically using `(on, off, ...)` tuples. In the tuple specification, the unit is equal to the linewidth:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "33a729db-84e4-4619-bd1a-1f60c77f7073", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "xx = np.linspace(0, 1, 100)\n", + "dashes = [\"-\", \"--\", \"-.\", \":\", (6, 2), (2, 1), (.5, .5), (4, 1, 2, 1)] \n", + "dash_data = (\n", + " pd.DataFrame({i: xx for i in range(len(dashes))})\n", + " .stack()\n", + " .reset_index(1)\n", + " .set_axis([\"y\", \"x\"], axis=1)\n", + " .reset_index(drop=True)\n", + ")\n", + "(\n", + " so.Plot(dash_data, \"x\", \"y\", linestyle=\"y\")\n", + " .add(so.Line(linewidth=1.7, color=\".2\"), legend=None)\n", + " .scale(\n", + " linestyle=dashes,\n", + " x=so.Continuous().tick(count=0),\n", + " y=so.Continuous().tick(every=1).label(like={\n", + " i: f\"'$\\mathtt{{{pat}}}$'\" if isinstance(pat, str) else pat\n", + " for i, pat in enumerate(dashes)\n", + " }.get)\n", + " )\n", + " .label(x=\"\", y=\"\")\n", + " .limit(x=(0, 1), y=(7.5, -0.5))\n", + " .layout(size=(9, 2.5), engine=None)\n", + " .theme({\n", + " **axes_style(\"white\"),\n", + " **no_spines,\n", + " \"ytick.labelsize\": 12,\n", + " })\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "41063f3b-a207-4f03-a606-78e2826be522", + "metadata": {}, + "source": [ + "Size properties\n", + "---------------" + ] + }, + { + "cell_type": "raw", + "id": "7a909d91-9d60-4e95-a855-18b2779f19ce", + "metadata": {}, + "source": [ + ".. _pointsize_property:\n", + "\n", + "pointsize\n", + "~~~~~~~~~\n", + "\n", + "The `pointsize` property is relevant to dot marks and to line marks that can show markers at individual data points. The units correspond to the diameter of the mark in points.\n", + "\n", + "The `pointsize` scales with the square root of the data by default so that magnitude is represented by diameter rather than area:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55b106d-ba14-43ec-ab9b-5d7a04fb813c", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "x = np.arange(1, 21)\n", + "y = [0 for _ in x]\n", + "(\n", + " so.Plot(x, y)\n", + " .add(so.Dots(color=\".2\", stroke=1), pointsize=x)\n", + " .layout(size=(9, .5), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"xtick.labelsize\": 12,\n", + " \"axes.xmargin\": .025,\n", + " })\n", + " .scale(\n", + " pointsize=None,\n", + " x=so.Continuous().tick(every=1),\n", + " y=so.Continuous().tick(count=0),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "66660d74-0252-4cb1-960a-c2c4823bb0e6", + "metadata": {}, + "source": [ + ".. _linewidth_property:\n", + "\n", + "linewidth\n", + "~~~~~~~~~\n", + "\n", + "The `linewidth` property is relevant to line marks and determines their thickness. The value should be non-negative and has point units:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a77c60d5-0d21-43a5-ab8c-f3f4abbc70ad", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "lw = np.arange(0.5, 5, .5)\n", + "x = [i for i in [0, 1] for _ in lw]\n", + "y = [*lw, *lw]\n", + "(\n", + " so.Plot(x=x, y=y, linewidth=y)\n", + " .add(so.Line(color=\".2\"))\n", + " .limit(y=(4.9, .1))\n", + " .layout(size=(9, 1.4), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"bottom\", \"right\", \"top\"]},\n", + " \"xtick.labelsize\": 12,\n", + " \"axes.xmargin\": .015,\n", + " \"ytick.labelsize\": 12,\n", + " })\n", + " .scale(\n", + " linewidth=None,\n", + " x=so.Continuous().tick(count=0),\n", + " y=so.Continuous().tick(every=1, between=(.5, 4.5), minor=1),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "dcbdfcb9-d55e-467a-8514-bdb4cc2bec90", + "metadata": {}, + "source": [ + ".. _edgewidth_property:\n", + "\n", + "edgewidth\n", + "~~~~~~~~~\n", + "\n", + "The `edgewidth` property is akin to `linewidth` but applies to marks with an edge/fill rather than to lines. It also has a different default range when used in a scale. The units are the same:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7a1f1d5a-a2d5-4b8e-a172-73104f5ec715", + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "x = np.arange(0, 21) / 5\n", + "y = [0 for _ in x]\n", + "edge_plot = (\n", + " so.Plot(x, y)\n", + " .layout(size=(9, .5), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"xtick.labelsize\": 12,\n", + " \"axes.xmargin\": .02,\n", + " })\n", + " .scale(\n", + " x=so.Continuous().tick(every=1, minor=4),\n", + " y=so.Continuous().tick(count=0),\n", + " )\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ba70ed6c-d902-41b0-a043-d8f27bf65e9b", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "(\n", + " edge_plot\n", + " .add(so.Dot(color=\".75\", edgecolor=\".2\", marker=\"o\", pointsize=14), edgewidth=x)\n", + " .scale(edgewidth=None)\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "98a25a16-67fa-4467-a425-6a78a17c63ab", + "metadata": {}, + "source": [ + ".. _stroke_property:\n", + "\n", + "stroke\n", + "~~~~~~\n", + "\n", + "The `stroke` property is akin to `edgewidth` but applies when a dot mark is defined by its stroke rather than its fill. It also has a slightly different default scale range, but otherwise behaves similarly:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f73a0428-a787-4f21-8098-848eb1c816fb", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "(\n", + " edge_plot\n", + " .add(so.Dot(color=\".2\", marker=\"x\", pointsize=11), stroke=x)\n", + " .scale(stroke=None)\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "c2ca33db-df52-4958-889a-320b4833a0d7", + "metadata": {}, + "source": [ + "Text properties\n", + "---------------" + ] + }, + { + "cell_type": "raw", + "id": "b75af2fe-4d81-407c-9858-23362710f25f", + "metadata": {}, + "source": [ + ".. _horizontalalignment_property:\n", + "\n", + ".. _verticalalignment_property:\n", + "\n", + "halign, valign\n", + "~~~~~~~~~~~~~~\n", + "\n", + "The `halign` and `valign` properties control the *horizontal* and *vertical* alignment of text marks. The options for horizontal alignment are `'left'`, `'right'`, and `'center'`, while the options for vertical alignment are `'top'`, `'bottom'`, `'center'`, `'baseline'`, and `'center_baseline'`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9588309-bee4-4b97-b428-eb91ea582105", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "x = [\"left\", \"right\", \"top\", \"bottom\", \"baseline\", \"center\"]\n", + "ha = x[:2] + [\"center\"] * 4\n", + "va = [\"center_baseline\"] * 2 + x[2:]\n", + "y = np.zeros(len(x))\n", + "(\n", + " so.Plot(x=[f\"'{_x_}'\" for _x_ in x], y=y, halign=ha, valign=va)\n", + " .add(so.Dot(marker=\"+\", color=\"r\", alpha=.5, stroke=1, pointsize=24))\n", + " .add(so.Text(text=\"XyZ\", fontsize=14, offset=0))\n", + " .scale(y=so.Continuous().tick(at=[]), halign=None, valign=None)\n", + " .limit(x=(-.25, len(x) - .75))\n", + " .layout(size=(9, .6), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"xtick.labelsize\": 12,\n", + " \"axes.xmargin\": .015,\n", + " \"ytick.labelsize\": 12,\n", + " })\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "ea74c7e5-798b-47bc-bc18-9086902fb5c6", + "metadata": {}, + "source": [ + ".. _fontsize_property:\n", + "\n", + "fontsize\n", + "~~~~~~~~\n", + "\n", + "The `fontsize` property controls the size of textual marks. The value has point units:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c515b790-385d-4521-b14a-0769c1902928", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "from string import ascii_uppercase\n", + "n = 26\n", + "s = np.arange(n) + 1\n", + "y = np.zeros(n)\n", + "t = list(ascii_uppercase[:n])\n", + "(\n", + " so.Plot(x=s, y=y, text=t, fontsize=s)\n", + " .add(so.Text())\n", + " .scale(x=so.Nominal(), y=so.Continuous().tick(at=[]))\n", + " .layout(size=(9, .5), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"xtick.labelsize\": 12,\n", + " \"axes.xmargin\": .015,\n", + " \"ytick.labelsize\": 12,\n", + " })\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "4b367f36-fb96-44fa-83a3-1cc66c7a3279", + "metadata": {}, + "source": [ + ".. _offset_property:\n", + "\n", + "offset\n", + "~~~~~~\n", + "\n", + "The `offset` property controls the spacing between a text mark and its anchor position. It applies when *not* using `center` alignment (i.e., when using left/right or top/bottom). The value has point units. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "25a49331-9580-4578-8bdb-d0d1829dde71", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "n = 17\n", + "x = np.linspace(0, 8, n)\n", + "y = np.full(n, .5)\n", + "(\n", + " so.Plot(x=x, y=y, offset=x)\n", + " .add(so.Bar(color=\".6\", edgecolor=\"k\"))\n", + " .add(so.Text(text=\"abc\", valign=\"bottom\"))\n", + " .scale(\n", + " x=so.Continuous().tick(every=1, minor=1),\n", + " y=so.Continuous().tick(at=[]),\n", + " offset=None,\n", + " )\n", + " .limit(y=(0, 1.5))\n", + " .layout(size=(9, .5), engine=None)\n", + " .theme({\n", + " **axes_style(\"ticks\"),\n", + " **{f\"axes.spines.{side}\": False for side in [\"left\", \"right\", \"top\"]},\n", + " \"axes.xmargin\": .015,\n", + " \"xtick.labelsize\": 12,\n", + " \"ytick.labelsize\": 12,\n", + " })\n", + " .plot()\n", + ")" + ] + }, + { + "cell_type": "raw", + "id": "77723ffd-2da3-4ece-a97a-3c00e864c743", + "metadata": {}, + "source": [ + "Other properties\n", + "----------------" + ] + }, + { + "cell_type": "raw", + "id": "287bb259-0194-4c8c-8836-5e3eb6d88e79", + "metadata": {}, + "source": [ + ".. _property_property:\n", + "\n", + "text\n", + "~~~~\n", + "\n", + "The `text` property is used to set the content of a textual mark. It is always used literally (not mapped), and cast to string when necessary.\n", + "\n", + "group\n", + "~~~~~\n", + "\n", + "The `group` property is special in that it does not change anything about the mark's appearance but defines additional data subsets that transforms should operate on independently." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f23c9251-1685-4150-b5c2-ab5b0589d8e6", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/regression.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/regression.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d957101e07e757b879c8060c19ffd80b4b4e6e20 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/regression.ipynb @@ -0,0 +1,454 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _regression_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Estimating regression fits\n", + "==========================" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Many datasets contain multiple quantitative variables, and the goal of an analysis is often to relate those variables to each other. We :ref:`previously discussed ` functions that can accomplish this by showing the joint distribution of two variables. It can be very helpful, though, to use statistical models to estimate a simple relationship between two noisy sets of observations. The functions discussed in this chapter will do so through the common framework of linear regression.\n", + "\n", + "In the spirit of Tukey, the regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. That is to say that seaborn is not itself a package for statistical analysis. To obtain quantitative measures related to the fit of regression models, you should use `statsmodels `_. The goal of seaborn, however, is to make exploring a dataset through visualization quick and easy, as doing so is just as (if not more) important than exploring a dataset through tables of statistics." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.set_theme(color_codes=True)\n", + "np.random.seed(sum(map(ord, \"regression\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Functions for drawing linear regression models\n", + "----------------------------------------------\n", + "\n", + "The two functions that can be used to visualize a linear fit are :func:`regplot` and :func:`lmplot`.\n", + "\n", + "In the simplest invocation, both functions draw a scatterplot of two variables, ``x`` and ``y``, and then fit the regression model ``y ~ x`` and plot the resulting regression line and a 95% confidence interval for that regression:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.regplot(x=\"total_bill\", y=\"tip\", data=tips);" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", data=tips);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "These functions draw similar plots, but :func:`regplot` is an :doc:`axes-level function `, and :func:`lmplot` is a figure-level function. Additionally, :func:`regplot` accepts the ``x`` and ``y`` variables in a variety of formats including simple numpy arrays, :class:`pandas.Series` objects, or as references to variables in a :class:`pandas.DataFrame` object passed to `data`. In contrast, :func:`lmplot` has `data` as a required parameter and the `x` and `y` variables must be specified as strings. Finally, only :func:`lmplot` has `hue` as a parameter.\n", + "\n", + "The core functionality is otherwise similar, though, so this tutorial will focus on :func:`lmplot`:.\n", + "\n", + "It's possible to fit a linear regression when one of the variables takes discrete values, however, the simple scatterplot produced by this kind of dataset is often not optimal:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"size\", y=\"tip\", data=tips);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "One option is to add some random noise (\"jitter\") to the discrete values to make the distribution of those values more clear. Note that jitter is applied only to the scatterplot data and does not influence the regression line fit itself:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"size\", y=\"tip\", data=tips, x_jitter=.05);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A second option is to collapse over the observations in each discrete bin to plot an estimate of central tendency along with a confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"size\", y=\"tip\", data=tips, x_estimator=np.mean);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Fitting different kinds of models\n", + "---------------------------------\n", + "\n", + "The simple linear regression model used above is very simple to fit, however, it is not appropriate for some kinds of datasets. The `Anscombe's quartet `_ dataset shows a few examples where simple linear regression provides an identical estimate of a relationship where simple visual inspection clearly shows differences. For example, in the first case, the linear regression is a good model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "anscombe = sns.load_dataset(\"anscombe\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'I'\"),\n", + " ci=None, scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The linear relationship in the second dataset is the same, but the plot clearly shows that this is not a good model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'II'\"),\n", + " ci=None, scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In the presence of these kind of higher-order relationships, :func:`lmplot` and :func:`regplot` can fit a polynomial regression model to explore simple kinds of nonlinear trends in the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'II'\"),\n", + " order=2, ci=None, scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "A different problem is posed by \"outlier\" observations that deviate for some reason other than the main relationship under study:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'III'\"),\n", + " ci=None, scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In the presence of outliers, it can be useful to fit a robust regression, which uses a different loss function to downweight relatively large residuals:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'III'\"),\n", + " robust=True, ci=None, scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When the ``y`` variable is binary, simple linear regression also \"works\" but provides implausible predictions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips[\"big_tip\"] = (tips.tip / tips.total_bill) > .15\n", + "sns.lmplot(x=\"total_bill\", y=\"big_tip\", data=tips,\n", + " y_jitter=.03);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The solution in this case is to fit a logistic regression, such that the regression line shows the estimated probability of ``y = 1`` for a given value of ``x``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"big_tip\", data=tips,\n", + " logistic=True, y_jitter=.03);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Note that the logistic regression estimate is considerably more computationally intensive (this is true of robust regression as well). As the confidence interval around the regression line is computed using a bootstrap procedure, you may wish to turn this off for faster iteration (using ``ci=None``).\n", + "\n", + "An altogether different approach is to fit a nonparametric regression using a `lowess smoother `_. This approach has the fewest assumptions, although it is computationally intensive and so currently confidence intervals are not computed at all:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", data=tips,\n", + " lowess=True, line_kws={\"color\": \"C1\"});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The :func:`residplot` function can be a useful tool for checking whether the simple regression model is appropriate for a dataset. It fits and removes a simple linear regression and then plots the residual values for each observation. Ideally, these values should be randomly scattered around ``y = 0``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'I'\"),\n", + " scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "If there is structure in the residuals, it suggests that simple linear regression is not appropriate:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.residplot(x=\"x\", y=\"y\", data=anscombe.query(\"dataset == 'II'\"),\n", + " scatter_kws={\"s\": 80});" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Conditioning on other variables\n", + "-------------------------------\n", + "\n", + "The plots above show many ways to explore the relationship between a pair of variables. Often, however, a more interesting question is \"how does the relationship between these two variables change as a function of a third variable?\" This is where the main differences between :func:`regplot` and :func:`lmplot` appear. While :func:`regplot` always shows a single relationship, :func:`lmplot` combines :func:`regplot` with :class:`FacetGrid` to show multiple fits using `hue` mapping or faceting.\n", + "\n", + "The best way to separate out a relationship is to plot both levels on the same axes and to use color to distinguish them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", hue=\"smoker\", data=tips);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Unlike :func:`relplot`, it's not possible to map a distinct variable to the style properties of the scatter plot, but you can redundantly code the `hue` variable with marker shape:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", hue=\"smoker\", data=tips,\n", + " markers=[\"o\", \"x\"], palette=\"Set1\");" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To add another variable, you can draw multiple \"facets\" with each level of the variable appearing in the rows or columns of the grid:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", hue=\"smoker\", col=\"time\", data=tips);" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.lmplot(x=\"total_bill\", y=\"tip\", hue=\"smoker\",\n", + " col=\"time\", row=\"sex\", data=tips, height=3);" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Plotting a regression in other contexts\n", + "---------------------------------------\n", + "\n", + "A few other seaborn functions use :func:`regplot` in the context of a larger, more complex plot. The first is the :func:`jointplot` function that we introduced in the :ref:`distributions tutorial `. In addition to the plot styles previously discussed, :func:`jointplot` can use :func:`regplot` to show the linear regression fit on the joint axes by passing ``kind=\"reg\"``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.jointplot(x=\"total_bill\", y=\"tip\", data=tips, kind=\"reg\");" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Using the :func:`pairplot` function with ``kind=\"reg\"`` combines :func:`regplot` and :class:`PairGrid` to show the linear relationship between variables in a dataset. Take care to note how this is different from :func:`lmplot`. In the figure below, the two axes don't show the same relationship conditioned on two levels of a third variable; rather, :func:`PairGrid` is used to show multiple relationships between different pairings of the variables in a dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(tips, x_vars=[\"total_bill\", \"size\"], y_vars=[\"tip\"],\n", + " height=5, aspect=.8, kind=\"reg\");" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Conditioning on an additional categorical variable is built into both of these functions using the ``hue`` parameter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.pairplot(tips, x_vars=[\"total_bill\", \"size\"], y_vars=[\"tip\"],\n", + " hue=\"smoker\", height=5, aspect=.8, kind=\"reg\");" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/_tutorial/relational.ipynb b/testbed/mwaskom__seaborn/doc/_tutorial/relational.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f96ed638df75f9773dc72de9d296ef322f029d57 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/_tutorial/relational.ipynb @@ -0,0 +1,685 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _relational_tutorial:\n", + "\n", + ".. currentmodule:: seaborn" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Visualizing statistical relationships\n", + "=====================================\n", + "\n", + "Statistical analysis is a process of understanding how variables in a dataset relate to each other and how those relationships depend on other variables. Visualization can be a core component of this process because, when data are visualized properly, the human visual system can see trends and patterns that indicate a relationship.\n", + "\n", + "We will discuss three seaborn functions in this tutorial. The one we will use most is :func:`relplot`. This is a :doc:`figure-level function ` for visualizing statistical relationships using two common approaches: scatter plots and line plots. :func:`relplot` combines a :class:`FacetGrid` with one of two axes-level functions:\n", + "\n", + "- :func:`scatterplot` (with ``kind=\"scatter\"``; the default)\n", + "- :func:`lineplot` (with ``kind=\"line\"``)\n", + "\n", + "As we will see, these functions can be quite illuminating because they use simple and easily-understood representations of data that can nevertheless represent complex dataset structures. They can do so because they plot two-dimensional graphics that can be enhanced by mapping up to three additional variables using the semantics of hue, size, and style." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "sns.set_theme(style=\"darkgrid\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "np.random.seed(sum(map(ord, \"relational\")))" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _scatterplot_tutorial:\n", + "\n", + "Relating variables with scatter plots\n", + "-------------------------------------\n", + "\n", + "The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them.\n", + "\n", + "There are several ways to draw a scatter plot in seaborn. The most basic, which should be used when both variables are numeric, is the :func:`scatterplot` function. In the :ref:`categorical visualization tutorial `, we will see specialized tools for using scatterplots to visualize categorical data. The :func:`scatterplot` is the default ``kind`` in :func:`relplot` (it can also be forced by setting ``kind=\"scatter\"``):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tips = sns.load_dataset(\"tips\")\n", + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable. In seaborn, this is referred to as using a \"hue semantic\", because the color of the point gains meaning:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"smoker\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To emphasize the difference between the classes, and to improve accessibility, you can use a different marker style for each class:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips,\n", + " x=\"total_bill\", y=\"tip\", hue=\"smoker\", style=\"smoker\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to represent four variables by changing the hue and style of each point independently. But this should be done carefully, because the eye is much less sensitive to shape than to color:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips,\n", + " x=\"total_bill\", y=\"tip\", hue=\"smoker\", style=\"time\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In the examples above, the hue semantic was categorical, so the default :ref:`qualitative palette ` was applied. If the hue semantic is numeric (specifically, if it can be cast to float), the default coloring switches to a sequential palette:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\", hue=\"size\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "In both cases, you can customize the color palette. There are many options for doing so. Here, we customize a sequential palette using the string interface to :func:`cubehelix_palette`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips, \n", + " x=\"total_bill\", y=\"tip\",\n", + " hue=\"size\", palette=\"ch:r=-.5,l=.75\"\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The third kind of semantic variable changes the size of each point:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(data=tips, x=\"total_bill\", y=\"tip\", size=\"size\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Unlike with :func:`matplotlib.pyplot.scatter`, the literal value of the variable is not used to pick the area of the point. Instead, the range of values in data units is normalized into a range in area units. This range can be customized:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips, x=\"total_bill\", y=\"tip\",\n", + " size=\"size\", sizes=(15, 200)\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "More examples for customizing how the different semantics are used to show statistical relationships are shown in the :func:`scatterplot` API examples." + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + ".. _lineplot_tutorial:\n", + "\n", + "Emphasizing continuity with line plots\n", + "--------------------------------------\n", + "\n", + "Scatter plots are highly effective, but there is no universally optimal type of visualisation. Instead, the visual representation should be adapted for the specifics of the dataset and to the question you are trying to answer with the plot.\n", + "\n", + "With some datasets, you may want to understand changes in one variable as a function of time, or a similarly continuous variable. In this situation, a good choice is to draw a line plot. In seaborn, this can be accomplished by the :func:`lineplot` function, either directly or with :func:`relplot` by setting ``kind=\"line\"``:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dowjones = sns.load_dataset(\"dowjones\")\n", + "sns.relplot(data=dowjones, x=\"Date\", y=\"Price\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Aggregation and representing uncertainty\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "More complex datasets will have multiple measurements for the same value of the ``x`` variable. The default behavior in seaborn is to aggregate the multiple measurements at each ``x`` value by plotting the mean and the 95% confidence interval around the mean:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fmri = sns.load_dataset(\"fmri\")\n", + "sns.relplot(data=fmri, x=\"timepoint\", y=\"signal\", kind=\"line\")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The confidence intervals are computed using bootstrapping, which can be time-intensive for larger datasets. It's therefore possible to disable them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", errorbar=None,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Another good option, especially with larger data, is to represent the spread of the distribution at each timepoint by plotting the standard deviation instead of a confidence interval:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", errorbar=\"sd\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "To turn off aggregation altogether, set the ``estimator`` parameter to ``None`` This might produce a strange effect when the data have multiple observations at each point." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\",\n", + " estimator=None,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Plotting subsets of data with semantic mappings\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "The :func:`lineplot` function has the same flexibility as :func:`scatterplot`: it can show up to three additional variables by modifying the hue, size, and style of the plot elements. It does so using the same API as :func:`scatterplot`, meaning that we don't need to stop and think about the parameters that control the look of lines vs. points in matplotlib.\n", + "\n", + "Using semantics in :func:`lineplot` will also determine how the data get aggregated. For example, adding a hue semantic with two levels splits the plot into two lines and error bands, coloring each to indicate which subset of the data they correspond to." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"event\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Adding a style semantic to a line plot changes the pattern of dashes in the line by default:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\",\n", + " hue=\"region\", style=\"event\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "But you can identify subsets by the markers used at each observation, either together with the dashes or instead of them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"region\", style=\"event\",\n", + " dashes=False, markers=True,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "As with scatter plots, be cautious about making line plots using multiple semantics. While sometimes informative, they can also be difficult to parse and interpret. But even when you are only examining changes across one additional variable, it can be useful to alter both the color and style of the lines. This can make the plot more accessible when printed to black-and-white or viewed by someone with color blindness:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"event\", style=\"event\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When you are working with repeated measures data (that is, you have units that were sampled multiple times), you can also plot each sampling unit separately without distinguishing them through semantics. This avoids cluttering the legend:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri.query(\"event == 'stim'\"), kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"region\",\n", + " units=\"subject\", estimator=None,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The default colormap and handling of the legend in :func:`lineplot` also depends on whether the hue semantic is categorical or numeric:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dots = sns.load_dataset(\"dots\").query(\"align == 'dots'\")\n", + "sns.relplot(\n", + " data=dots, kind=\"line\",\n", + " x=\"time\", y=\"firing_rate\",\n", + " hue=\"coherence\", style=\"choice\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It may happen that, even though the ``hue`` variable is numeric, it is poorly represented by a linear color scale. That's the case here, where the levels of the ``hue`` variable are logarithmically scaled. You can provide specific color values for each line by passing a list or dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "palette = sns.cubehelix_palette(light=.8, n_colors=6)\n", + "sns.relplot(\n", + " data=dots, kind=\"line\", \n", + " x=\"time\", y=\"firing_rate\",\n", + " hue=\"coherence\", style=\"choice\", palette=palette,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Or you can alter how the colormap is normalized:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from matplotlib.colors import LogNorm\n", + "palette = sns.cubehelix_palette(light=.7, n_colors=6)\n", + "sns.relplot(\n", + " data=dots.query(\"coherence > 0\"), kind=\"line\",\n", + " x=\"time\", y=\"firing_rate\",\n", + " hue=\"coherence\", style=\"choice\",\n", + " hue_norm=LogNorm(),\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "The third semantic, size, changes the width of the lines:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=dots, kind=\"line\",\n", + " x=\"time\", y=\"firing_rate\",\n", + " size=\"coherence\", style=\"choice\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "While the ``size`` variable will typically be numeric, it's also possible to map a categorical variable with the width of the lines. Be cautious when doing so, because it will be difficult to distinguish much more than \"thick\" vs \"thin\" lines. However, dashes can be hard to perceive when lines have high-frequency variability, so using different widths may be more effective in that case:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=dots, kind=\"line\",\n", + " x=\"time\", y=\"firing_rate\",\n", + " hue=\"coherence\", size=\"choice\", palette=palette,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Controlling sorting and orientation\n", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", + "\n", + "Because :func:`lineplot` assumes that you are most often trying to draw ``y`` as a function of ``x``, the default behavior is to sort the data by the ``x`` values before plotting. However, this can be disabled:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "healthexp = sns.load_dataset(\"healthexp\").sort_values(\"Year\")\n", + "sns.relplot(\n", + " data=healthexp, kind=\"line\",\n", + " x=\"Spending_USD\", y=\"Life_Expectancy\", hue=\"Country\",\n", + " sort=False\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "It's also possible to sort (and aggregate) along the y axis:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"signal\", y=\"timepoint\", hue=\"event\",\n", + " orient=\"y\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Showing multiple relationships with facets\n", + "------------------------------------------\n", + "\n", + "We've emphasized in this tutorial that, while these functions *can* show several semantic variables at once, it's not always effective to do so. But what about when you do want to understand how a relationship between two variables depends on more than one other variable?\n", + "\n", + "The best approach may be to make more than one plot. Because :func:`relplot` is based on the :class:`FacetGrid`, this is easy to do. To show the influence of an additional variable, instead of assigning it to one of the semantic roles in the plot, use it to \"facet\" the visualization. This means that you make multiple axes and plot subsets of the data on each of them:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=tips,\n", + " x=\"total_bill\", y=\"tip\", hue=\"smoker\", col=\"time\",\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "You can also show the influence of two variables this way: one by faceting on the columns and one by faceting on the rows. As you start adding more variables to the grid, you may want to decrease the figure size. Remember that the size :class:`FacetGrid` is parameterized by the height and aspect ratio of *each facet*:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "hide" + ] + }, + "outputs": [], + "source": [ + "subject_number = fmri[\"subject\"].str[1:].astype(int)\n", + "fmri= fmri.iloc[subject_number.argsort()]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri, kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"subject\",\n", + " col=\"region\", row=\"event\", height=3,\n", + " estimator=None\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "When you want to examine effects across many levels of a variable, it can be a good idea to facet that variable on the columns and then \"wrap\" the facets into the rows:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sns.relplot(\n", + " data=fmri.query(\"region == 'frontal'\"), kind=\"line\",\n", + " x=\"timepoint\", y=\"signal\", hue=\"event\", style=\"event\",\n", + " col=\"subject\", col_wrap=5,\n", + " height=3, aspect=.75, linewidth=2.5,\n", + ")" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "These visualizations, which are sometimes called \"lattice\" plots or \"small-multiples\", are very effective because they present the data in a format that makes it easy for the eye to detect both overall patterns and deviations from those patterns. While you should make use of the flexibility afforded by :func:`scatterplot` and :func:`relplot`, always try to keep in mind that several simple plots are usually more effective than one complex plot." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "py310", + "language": "python", + "name": "py310" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/testbed/mwaskom__seaborn/doc/api.rst b/testbed/mwaskom__seaborn/doc/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..189e79046781d4e1229ab7e14966060852295a9c --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/api.rst @@ -0,0 +1,316 @@ +.. _api_ref: + +API reference +============= + +.. currentmodule:: seaborn.objects + +.. _objects_api: + +Objects interface +----------------- + +Plot object +~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :template: plot + :nosignatures: + + Plot + +Mark objects +~~~~~~~~~~~~ + +.. rubric:: Dot marks + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Dot + Dots + +.. rubric:: Line marks + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Line + Lines + Path + Paths + Dash + Range + +.. rubric:: Bar marks + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Bar + Bars + +.. rubric:: Fill marks + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Area + Band + +.. rubric:: Text marks + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Text + +Stat objects +~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Agg + Est + Count + Hist + KDE + Perc + PolyFit + +Move objects +~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Dodge + Jitter + Norm + Stack + Shift + +Scale objects +~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :template: scale + :nosignatures: + + Boolean + Continuous + Nominal + Temporal + +Base classes +~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :template: object + :nosignatures: + + Mark + Stat + Move + Scale + +.. currentmodule:: seaborn + +Function interface +------------------ + +.. _relational_api: + +Relational plots +~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + relplot + scatterplot + lineplot + +.. _distribution_api: + +Distribution plots +~~~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + displot + histplot + kdeplot + ecdfplot + rugplot + distplot + +.. _categorical_api: + +Categorical plots +~~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + catplot + stripplot + swarmplot + boxplot + violinplot + boxenplot + pointplot + barplot + countplot + +.. _regression_api: + +Regression plots +~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + lmplot + regplot + residplot + +.. _matrix_api: + +Matrix plots +~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + heatmap + clustermap + +.. _grid_api: + +Multi-plot grids +---------------- + +Facet grids +~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + FacetGrid + +Pair grids +~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + pairplot + PairGrid + +Joint grids +~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + jointplot + JointGrid + +.. _style_api: + +Themeing +-------- + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + set_theme + axes_style + set_style + plotting_context + set_context + set_color_codes + reset_defaults + reset_orig + set + +.. _palette_api: + +Color palettes +-------------- + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + set_palette + color_palette + husl_palette + hls_palette + cubehelix_palette + dark_palette + light_palette + diverging_palette + blend_palette + xkcd_palette + crayon_palette + mpl_palette + +Palette widgets +~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + choose_colorbrewer_palette + choose_cubehelix_palette + choose_light_palette + choose_dark_palette + choose_diverging_palette + + +Utility functions +----------------- + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + despine + move_legend + saturate + desaturate + set_hls_values + load_dataset + get_dataset_names + get_data_home diff --git a/testbed/mwaskom__seaborn/doc/citing.rst b/testbed/mwaskom__seaborn/doc/citing.rst new file mode 100644 index 0000000000000000000000000000000000000000..f539f9813456fc1114878a4183dfdc7485b7f265 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/citing.rst @@ -0,0 +1,57 @@ +.. _citing: + +Citing and logo +=============== + +Citing seaborn +-------------- + +If seaborn is integral to a scientific publication, please cite it. +A paper describing seaborn has been published in the `Journal of Open Source Software `_. +Here is a ready-made BibTeX entry: + +.. highlight:: none + +:: + + @article{Waskom2021, + doi = {10.21105/joss.03021}, + url = {https://doi.org/10.21105/joss.03021}, + year = {2021}, + publisher = {The Open Journal}, + volume = {6}, + number = {60}, + pages = {3021}, + author = {Michael L. Waskom}, + title = {seaborn: statistical data visualization}, + journal = {Journal of Open Source Software} + } + +In most situations where seaborn is cited, a citation to `matplotlib `_ would also be appropriate. + +Logo files +---------- + +Additional logo files, including hi-res PNGs and images suitable for use over a dark background, are available +`on GitHub `_. + +Wide logo +~~~~~~~~~ + +.. image:: _static/logo-wide-lightbg.svg + :width: 400px + +Tall logo +~~~~~~~~~ + +.. image:: _static/logo-tall-lightbg.svg + :width: 150px + +Logo mark +~~~~~~~~~ + +.. image:: _static/logo-mark-lightbg.svg + :width: 150px + +Credit to `Matthias Bussonnier `_ for the initial design +and implementation of the logo. diff --git a/testbed/mwaskom__seaborn/doc/conf.py b/testbed/mwaskom__seaborn/doc/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..81d2c1b9ff601ef60eced0744ae9362a9e28af25 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/conf.py @@ -0,0 +1,179 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +import time +import seaborn +from seaborn._core.properties import PROPERTIES + +sys.path.insert(0, os.path.abspath('sphinxext')) + + +# -- Project information ----------------------------------------------------- + +project = 'seaborn' +copyright = f'2012-{time.strftime("%Y")}' +author = 'Michael Waskom' +version = release = seaborn.__version__ + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (amed 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.coverage', + 'sphinx.ext.mathjax', + 'sphinx.ext.autosummary', + 'sphinx.ext.intersphinx', + 'matplotlib.sphinxext.plot_directive', + 'gallery_generator', + 'tutorial_builder', + 'numpydoc', + 'sphinx_copybutton', + 'sphinx_issues', + 'sphinx_design', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The root document. +root_doc = 'index' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'docstrings', 'nextgen', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all documents. +default_role = 'literal' + +# Generate the API documentation when building +autosummary_generate = True +numpydoc_show_class_members = False + +# Sphinx-issues configuration +issues_github_path = 'mwaskom/seaborn' + +# Include the example source for plots in API docs +plot_include_source = True +plot_formats = [('png', 90)] +plot_html_show_formats = False +plot_html_show_source_link = False + +# Don't add a source link in the sidebar +html_show_sourcelink = False + +# Control the appearance of type hints +autodoc_typehints = "none" +autodoc_typehints_format = "short" + +# Allow shorthand references for main function interface +rst_prolog = """ +.. currentmodule:: seaborn +""" + +# Define replacements (used in whatsnew bullets) +rst_epilog = """ + +.. role:: raw-html(raw) + :format: html + +.. role:: raw-latex(raw) + :format: latex + +.. |API| replace:: :raw-html:`API` :raw-latex:`{\small\sc [API]}` +.. |Defaults| replace:: :raw-html:`Defaults` :raw-latex:`{\small\sc [Defaults]}` +.. |Docs| replace:: :raw-html:`Docs` :raw-latex:`{\small\sc [Docs]}` +.. |Feature| replace:: :raw-html:`Feature` :raw-latex:`{\small\sc [Feature]}` +.. |Enhancement| replace:: :raw-html:`Enhancement` :raw-latex:`{\small\sc [Enhancement]}` +.. |Fix| replace:: :raw-html:`Fix` :raw-latex:`{\small\sc [Fix]}` +.. |Build| replace:: :raw-html:`Build` :raw-latex:`{\small\sc [Deps]}` + +""" # noqa + +rst_epilog += "\n".join([ + f".. |{key}| replace:: :ref:`{key} <{val.__class__.__name__.lower()}_property>`" + for key, val in PROPERTIES.items() +]) + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'pydata_sphinx_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named 'default.css' will overwrite the builtin 'default.css'. +html_static_path = ['_static', 'example_thumbs'] +for path in html_static_path: + if not os.path.exists(path): + os.makedirs(path) + +html_css_files = [f'css/custom.css?v={seaborn.__version__}'] + +html_logo = "_static/logo-wide-lightbg.svg" +html_favicon = "_static/favicon.ico" + +html_theme_options = { + "icon_links": [ + { + "name": "GitHub", + "url": "https://github.com/mwaskom/seaborn", + "icon": "fab fa-github", + "type": "fontawesome", + }, + { + "name": "StackOverflow", + "url": "https://stackoverflow.com/tags/seaborn", + "icon": "fab fa-stack-overflow", + "type": "fontawesome", + }, + { + "name": "Twitter", + "url": "https://twitter.com/michaelwaskom", + "icon": "fab fa-twitter", + "type": "fontawesome", + }, + ], + "show_prev_next": False, + "navbar_start": ["navbar-logo"], + "navbar_end": ["navbar-icon-links"], + "header_links_before_dropdown": 8, +} + +html_context = { + "default_mode": "light", +} + +html_sidebars = { + "index": [], + "examples/index": [], + "**": ["sidebar-nav-bs.html"], +} + +# -- Intersphinx ------------------------------------------------ + +intersphinx_mapping = { + 'numpy': ('https://numpy.org/doc/stable/', None), + 'scipy': ('https://docs.scipy.org/doc/scipy/', None), + 'matplotlib': ('https://matplotlib.org/stable', None), + 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), + 'statsmodels': ('https://www.statsmodels.org/stable/', None) +} diff --git a/testbed/mwaskom__seaborn/doc/example_thumbs/.gitkeep b/testbed/mwaskom__seaborn/doc/example_thumbs/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/mwaskom__seaborn/doc/faq.rst b/testbed/mwaskom__seaborn/doc/faq.rst new file mode 100644 index 0000000000000000000000000000000000000000..1d7f3fcf27b06b25e4f531cee1a3ddc2edb08b76 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/faq.rst @@ -0,0 +1,381 @@ +.. currentmodule:: seaborn + +Frequently asked questions +========================== + +This is a collection of answers to questions that are commonly raised about seaborn. + +Getting started +--------------- + +.. _faq_cant_import: + +I've installed seaborn, why can't I import it? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*It looks like you successfully installed seaborn by doing* `pip install seaborn` *but it cannot be imported. You get an error like "ModuleNotFoundError: No module named 'seaborn'" when you try.* + +This is probably not a `seaborn` problem, *per se*. If you have multiple Python environments on your computer, it is possible that you did `pip install` in one environment and tried to import the library in another. On a unix system, you could check whether the terminal commands `which pip`, `which python`, and (if applicable) `which jupyter` point to the same `bin/` directory. If not, you'll need to sort out the definition of your `$PATH` variable. + +Two alternate patterns for installing with `pip` may also be more robust to this problem: + +- Invoke `pip` on the command line with `python -m pip install ` rather than `pip install ` +- Use `%pip install ` in a Jupyter notebook to install it in the same place as the kernel + +.. _faq_import_fails: + +I can't import seaborn, even though it's definitely installed! +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You've definitely installed seaborn in the right place, but importing it produces a long traceback and a confusing error message, perhaps something like* `ImportError: DLL load failed: The specified module could not be found`. + +Such errors usually indicate a problem with the way Python libraries are using compiled resources. Because seaborn is pure Python, it won't directly encounter these problems, but its dependencies (numpy, scipy, matplotlib, and pandas) might. To fix the issue, you'll first need to read through the traceback and figure out which dependency was being imported at the time of the error. Then consult the installation documentation for the relevant package, which might have advice for getting an installation working on your specific system. + +The most common culprit of these issues is scipy, which has many compiled components. Starting in seaborn version 0.12, scipy is an optional dependency, which should help to reduce the frequency of these issues. + +.. _faq_no_plots: + +Why aren't my plots showing up? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You're calling seaborn functions — maybe in a terminal or IDE with an integrated IPython console — but not seeing any plots.)* + +In matplotlib, there is a distinction between *creating* a figure and *showing* it, and in some cases it's necessary to explicitly call :func:`matplotlib.pyplot.show` at the point when you want to see the plot. Because that command blocks by default and is not always desired (for instance, you may be executing a script that saves files to disk) seaborn does not deviate from standard matplotlib practice here. + +Yet most of the examples in the seaborn docs do not have this line, because there are multiple ways to avoid needing it. In a Jupyter notebook with the `"inline" `_ (default) or `"widget" `_ backends, :func:`matplotlib.pyplot.show` is automatically called after executing a cell, so any figures will appear in the cell's outputs. You can also activate a more interactive experience by executing `%matplotlib` in any Jupyter or IPython interface or by calling :func:`matplotlib.pyplot.ion` anywhere in Python. Both methods will configure matplotlib to show or update the figure after every plotting command. + +.. _faq_repl_output: + +Why is something printed after every notebook cell? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You're using seaborn in a Jupyter notebook, and every cell prints something like or before showing the plot.* + +Jupyter notebooks will show the result of the final statement in the cell as part of its output, and each of seaborn's plotting functions return a reference to the matplotlib or seaborn object that contain the plot. If this is bothersome, you can suppress this output in a few ways: + +- Always assign the result of the final statement to a variable (e.g. `ax = sns.histplot(...)`) +- Add a semicolon to the end of the final statement (e.g. `sns.histplot(...);`) +- End every cell with a function that has no return value (e.g. `plt.show()`, which isn't needed but also causes no problems) +- Add `cell metadata tags `_, if you're converting the notebook to a different representation + +.. _faq_inline_dpi: + +Why do the plots look fuzzy in a Jupyter notebook? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The default "inline" backend (defined by `IPython `_) uses an unusually low dpi (`"dots per inch" `_) for figure output. This is a space-saving measure: lower dpi figures take up less disk space. (Also, lower dpi inline graphics appear *physically* smaller because they are represented as `PNGs `_, which do not exactly have a concept of resolution.) So one faces an economy/quality tradeoff. + +You can increase the DPI by resetting the rc parameters through the matplotlib API, using + +:: + + plt.rcParams.update({"figure.dpi": 96}) + +Or do it as you activate the seaborn theme:: + + sns.set_theme(rc={"figure.dpi": 96}) + +If you have a high pixel-density monitor, you can make your plots sharper using "retina mode":: + + %config InlineBackend.figure_format = "retina" + +This won't change the apparent size of your plots in a Jupyter interface, but they might appear very large in other contexts (i.e. on GitHub). And they will take up 4x the disk space. Alternatively, you can make SVG plots:: + + %config InlineBackend.figure_format = "svg" + +This will configure matplotlib to emit `vector graphics `_ with "infinite resolution". The downside is that file size will now scale with the number and complexity of the artists in your plot, and in some cases (e.g., a large scatterplot matrix) the load will impact browser responsiveness. + +Tricky concepts +--------------- + +.. _faq_function_levels: + +What do "figure-level" and "axes-level" mean? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You've encountered the term "figure-level" or "axes-level", maybe in the seaborn docs, StackOverflow answer, or GitHub thread, but you don't understand what it means.* + +In brief, all plotting functions in seaborn fall into one of two categories: + +- "axes-level" functions, which plot onto a single subplot that may or may not exist at the time the function is called +- "figure-level" functions, which internally create a matplotlib figure, potentially including multiple subplots + +This design is intended to satisfy two objectives: + +- seaborn should offer functions that are "drop-in" replacements for matplotlib methods +- seaborn should be able to produce figures that show "facets" or marginal distributions on distinct subplots + +The figure-level functions always combine one or more axes-level functions with an object that manages the layout. So, for example, :func:`relplot` is a figure-level function that combines either :func:`scatterplot` or :func:`lineplot` with a :class:`FacetGrid`. In contrast, :func:`jointplot` is a figure-level function that can combine multiple different axes-level functions — :func:`scatterplot` and :func:`histplot` by default — with a :class:`JointGrid`. + +If all you're doing is creating a plot with a single seaborn function call, this is not something you need to worry too much about. But it becomes relevant when you want to customize at a level beyond what the API of each function offers. It is also the source of various other points of confusion, so it is an important distinction understand (at least broadly) and keep in mind. + +This is explained in more detail in the :doc:`tutorial ` and in `this blog post `_. + +.. _faq_categorical_plots: + +What is a "categorical plot" or "categorical function"? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Next to the figure-level/axes-level distinction, this concept is probably the second biggest source of confusing behavior. + +Several :ref:`seaborn functions ` are referred to as "categorical" because they are designed to support a use-case where either the x or y variable in a plot is categorical (that is, the variable takes a finite number of potentially non-numeric values). + +At the time these functions were written, matplotlib did not have any direct support for non-numeric data types. So seaborn internally builds a mapping from unique values in the data to 0-based integer indexes, which is what it passes to matplotlib. If your data are strings, that's great, and it more-or-less matches how `matplotlib now handles `_ string-typed data. + +But a potential gotcha is that these functions *always do this*, even if both the x and y variables are numeric. This gives rise to a number of confusing behaviors, especially when mixing categorical and non-categorical plots (e.g., a combo bar-and-line plot). + +The v0.12 release added a `native_scale` parameter to :func:`stripplot` and :func:`swarmplot`, which provides control over this behavior. It will be rolled out to other categorical functions in future releases. But the current behavior will almost certainly remain the default, so this is an important API wrinkle to understand. + +Specifying data +--------------- + +.. _faq_data_format: + +How does my data need to be organized? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To get the most out of seaborn, your data should have a "long-form" or "tidy" representation. In a dataframe, `this means that `_ each variable has its own column, each observation has its own row, and each value has its own cell. With long-form data, you can succinctly and exactly specify a visualization by assigning variables in the dataset (columns) to roles in the plot. + +Data organization is a common stumbling block for beginners, in part because data are often not collected or stored in a long-form representation. Therefore, it is often necessary to `reshape `_ the data using pandas before plotting. Data reshaping can be a complex undertaking, requiring both a solid grasp of dataframe structure and knowledge of the pandas API. Investing some time in developing this skill can pay large dividends. + +But while seaborn is *most* powerful when provided with long-form data, nearly every seaborn function will accept and plot "wide-form" data too. You can trigger this by passing an object to seaborn's `data=` parameter without specifying other plot variables (`x`, `y`, ...). You'll be limited when using wide-form data: each function can make only one kind of wide-form plot. In most cases, seaborn tries to match what matplotlib or pandas would do with a dataset of the same structure. Reshaping your data into long-form will give you substantially more flexibility, but it can be helpful to take a quick look at your data very early in the process, and seaborn tries to make this possible. + +Understanding how your data should be represented — and how to get it that way if it starts out messy — is very important for making efficient and complete use of seaborn, and it is elaborated on at length in the :doc:`user-guide `. + +.. _faq_pandas_requirement: + +Does seaborn only work with pandas? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Generally speaking, no: seaborn is `quite flexible `_ about how your dataset needs to be represented. + +In most cases, :ref:`long-form data ` represented by multiple vector-like types can be passed directly to `x`, `y`, or other plotting parameters. Or you can pass a dictionary of vector types to `data` rather than a DataFrame. And when plotting with wide-form data, you can use a 2D numpy array or even nested lists to plot in wide-form mode. + +There are a couple older functions (namely, :func:`catplot` and :func:`lmplot`) that do require you to pass a :class:`pandas.DataFrame`. But at this point, they are the exception, and they will gain more flexibility over the next few release cycles. + +Layout problems +--------------- + +.. _faq_figure_size: + +How do I change the figure size? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is going to be more complicated than you might hope, in part because there are multiple ways to change the figure size in matplotlib, and in part because of the :ref:`figure-level/axes-level ` distinction in seaborn. + +In matplotlib, you can usually set the default size for all figures through the `rc parameters `_, specifically `figure.figsize`. And you can set the size of an individual figure when you create it (e.g. `plt.subplots(figsize=(w, h))`). If you're using an axes-level seaborn function, both of these will work as expected. + +Figure-level functions both ignore the default figure size and :ref:`parameterize the figure size differently `. When calling a figure-level function, you can pass values to `height=` and `aspect=` to set (roughly) the size of each *subplot*. The advantage here is that the size of the figure automatically adapts when you add faceting variables. But it can be confusing. + +Fortunately, there's a consistent way to set the exact figure size in a function-independent manner. Instead of setting the figure size when the figure is created, modify it after you plot by calling `obj.figure.set_size_inches(...)`, where `obj` is either a matplotlib axes (usually assigned to `ax`) or a seaborn `FacetGrid` (usually assigned to `g`). + +Note that :attr:`FacetGrid.figure` exists only on seaborn >= 0.11.2; before that you'll have to access :attr:`FacetGrid.fig`. + +Also, if you're making pngs (or in a Jupyter notebook), you can — perhaps surprisingly — scale all your plots up or down by :ref:`changing the dpi `. + +.. _faq_plot_misplaced: + +Why isn't seaborn drawing the plot where I tell it to? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You've explicitly created a matplotlib figure with one or more subplots and tried to draw a seaborn plot on it, but you end up with an extra figure and a blank subplot. Perhaps your code looks something like* + +:: + + f, ax = plt.subplots() + sns.catplot(..., ax=ax) + +This is a :ref:`figure-level/axes-level ` gotcha. Figure-level functions always create their own figure, so you can't direct them towards an existing axes the way you can with axes-level functions. Most functions will warn you when this happens, suggest the appropriate axes-level function, and ignore the `ax=` parameter. A few older functions might put the plot where you want it (because they internally pass `ax` to their axes-level function) while still creating an extra figure. This latter behavior should be considered a bug, and it is not to be relied on. + +The way things currently work, you can either set up the matplotlib figure yourself, or you can use a figure-level function, but you can't do both at the same time. + +.. _faq_categorical_line: + +Why can't I draw a line over a bar/box/strip/violin plot? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You're trying to create a single plot using multiple seaborn functions, perhaps by drawing a lineplot or regplot over a barplot or violinplot. You expect the line to go through the mean value for each box (etc.), but it looks to be misalgined, or maybe it's all the way off to the side.* + +You are trying to combine a :ref:`"categorical plot" ` with another plot type. If your `x` variable has numeric values, it seems like this should work. But recall: seaborn's categorical plots map unique values on the categorical axis to integer indexes. So if your data have unique `x` values of 1, 6, 20, 94, the corresponding plot elements will get drawn at 0, 1, 2, 3 (and the tick labels will be changed to represent the actual value). + +The line or regression plot doesn't know that this has happened, so it will use the actual numeric values, and the plots won't line up at all. + +As of now, there are two ways to work around this. In situations where you want to draw a line, you could use the (somewhat misleadingly named) :func:`pointplot` function, which is also a "categorical" function and will use the same rules for drawing the plot. If this doesn't solve the problem (for one, it's not as visually flexible as :func:`lineplot`, you could implement the mapping from actual values to integer indexes yourself and draw the plot that way:: + + unique_xs = sorted(df["x"].unique()) + sns.violinplot(data=df, x="x", y="y") + sns.lineplot(data=df, x=df["x"].map(unique_xs.index), y="y") + +This is something that will be easier in a planned future release, as it will become possible to make the categorical functions treat numeric data as numeric. (As of v0.12, it's possible only in :func:`stripplot` and :func:`swarmplot`, using `native_scale=True`). + +How do I move the legend? +~~~~~~~~~~~~~~~~~~~~~~~~~ + +*When applying a semantic mapping to a plot, seaborn will automatically create a legend and add it to the figure. But the automatic choice of legend position is not always ideal.* + +With seaborn v0.11.2 or later, use the :func:`move_legend` function. + +On older versions, a common pattern was to call `ax.legend(loc=...)` after plotting. While this appears to move the legend, it actually *replaces* it with a new one, using any labeled artists that happen to be attached to the axes. This does `not consistently work `_ across plot types. And it does not propagate the legend title or positioning tweaks that are used to format a multi-variable legend. + +The :func:`move_legend` function is actually more powerful than its name suggests, and it can also be used to modify other `legend parameters `_ (font size, handle length, etc.) after plotting. + +Other customizations +-------------------- + +.. _faq_figure_customization: + +How can I can I change something about the figure? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You want to make a very specific plot, and seaborn's defaults aren't doing it for you.* + +There's basically a four-layer hierarchy to customizing a seaborn figure: + +1. Explicit seaborn function parameters +2. Passed-through matplotlib keyword arguments +3. Matplotlib axes methods +4. Matplotlib artist methods + +First, read through the API docs for the relevant seaborn function. Each has a lot of parameters (probably too many), and you may be able to accomplish your desired customization using seaborn's own API. + +But seaborn does delegate a lot of customization to matplotlib. Most functions have `**kwargs` in their signature, which will catch extra keyword arguments and pass them through to the underlying matplotlib function. For example, :func:`scatterplot` has a number of parameters, but you can also use any valid keyword argument for :meth:`matplotlib.axes.Axes.scatter`, which it calls internally. + +Passing through keyword arguments lets you customize the artists that represent data, but often you will want to customize other aspects of the figure, such as labels, ticks, and titles. You can do this by calling methods on the object that seaborn's plotting functions return. Depending on whether you're calling an :ref:`axes-level or figure-level function `, this may be a :class:`matplotlib.axes.Axes` object or a seaborn wrapper (such as :class:`seaborn.FacetGrid`). Both kinds of objects have numerous methods that you can call to customize nearly anything about the figure. The easiest thing is usually to call :meth:`matplotlib.axes.Axes.set` or :meth:`seaborn.FacetGrid.set`, which let you modify multiple attributes at once, e.g.:: + + ax = sns.scatterplot(...) + ax.set( + xlabel="The x label", + ylabel="The y label", + title="The title" + xlim=(xmin, xmax), + xticks=[...], + xticklabels=[...], + ) + +Finally, the deepest customization may require you to reach "into" the matplotlib axes and tweak the artists that are stored on it. These will be in artist lists, such as `ax.lines`, `ax.collections`, `ax.patches`, etc. + +*Warning:* Neither matplotlib nor seaborn consider the specific artists produced by their plotting functions to be part of stable API. Because it's not possible to gracefully warn about upcoming changes to the artist types or the order in which they are stored, code that interacts with these attributes could break unexpectedly. With that said, seaborn does try hard to avoid making this kind of change. + +.. _faq_matplotlib_requirement: + +Wait, I need to learn how to use matplotlib too? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It really depends on how much customization you need. You can certainly perform a lot of exploratory data analysis while primarily or exclusively interacting with the seaborn API. But, if you're polishing a figure for a presentation or publication, you'll likely find yourself needing to understand at least a little bit about how matplotlib works. Matplotlib is extremely flexible, and it lets you control literally everything about a figure if you drill down far enough. + +Seaborn was originally designed with the idea that it would handle a specific set of well-defined operations through a very high-level API, while letting users "drop down" to matplotlib when they desired additional customization. This can be a pretty powerful combination, and it works reasonably well if you already know how to use matplotlib. But as seaborn as gained more features, it has become more feasible to learn seaborn *first*. In that situation, the need to switch APIs tends to be a bit more confusing / frustrating. This has motivated the development of seaborn's new :doc:`objects interface `, which aims to provide a more cohesive API for both high-level and low-level figure specification. Hopefully, it will alleviate the "two-library problem" as it matures. + +With that said, the level of deep control that matplotlib affords really can't be beat, so if you care about doing very specific things, it really is worth learning. + +.. _faq_object_oriented: + +How do I use seaborn with matplotlib's object-oriented interface? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You prefer to use matplotlib's explicit or* `"object-oriented" `_ *interface, because it makes your code easier to reason about and maintain. But the object-orient interface consists of methods on matplotlib objects, whereas seaborn offers you independent functions.* + +This is another case where it will be helpful to keep the :ref:`figure-level/axes-level ` distinction in mind. + +Axes-level functions can be used like any matplotlib axes method, but instead of calling `ax.func(...)`, you call `func(..., ax=ax)`. They also return the axes object (which they may have created, if no figure was currently active in matplotlib's global state). You can use the methods on that object to further customize the plot even if you didn't start with :func:`matplotlib.pyplot.figure` or :func:`matplotlib.pyplot.subplots`:: + + ax = sns.histplot(...) + ax.set(...) + +Figure-level functions :ref:`can't be directed towards an existing figure `, but they do store the matplotlib objects on the :class:`FacetGrid` object that they return (which seaborn docs always assign to a variable named `g`). + +If your figure-level function created only one subplot, you can access it directly:: + + g = sns.displot(...) + g.ax.set(...) + +For multiple subplots, you can either use :attr:`FacetGrid.axes` (which is always a 2D array of axes) or :attr:`FacetGrid.axes_dict` (which maps the row/col keys to the corresponding matplotlib object):: + + g = sns.displot(..., col=...) + for col, ax in g.axes_dict.items(): + ax.set(...) + +But if you're batch-setting attributes on all subplots, use the :meth:`FacetGrid.set` method rather than iterating over the individual axes:: + + g = sns.displot(...) + g.set(...) + +To access the underlying matplotlib *figure*, use :attr:`FacetGrid.figure` on seaborn >= 0.11.2 (or :attr:`FacetGrid.fig` on any other version). + +.. _faq_bar_annotations: + +Can I annotate bar plots with the bar values? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Nothing like this is built into seaborn, but matplotlib v3.4.0 added a convenience function (:meth:`matplotlib.axes.Axes.bar_label`) that makes it relatively easy. Here are a couple of recipes; note that you'll need to use a different approach depending on whether your bars come from a :ref:`figure-level or axes-level function `:: + + # Axes-level + ax = sns.histplot(df, x="x_var") + for bars in ax.containers: + ax.bar_label(bars) + + # Figure-level, one subplot + g = sns.displot(df, x="x_var") + for bars in g.ax.containers: + g.ax.bar_label(bars) + + # Figure-level, multiple subplots + g = sns.displot(df, x="x_var", col="col_var) + for ax in g.axes.flat: + for bars in ax.containers: + ax.bar_label(bars) + +.. _faq_dar_mode: + +Can I use seaborn in dark mode? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There's no direct support for this in seaborn, but matplotlib has a `"dark_background" `_ style-sheet that you could use, e.g.:: + + sns.set_theme(style="ticks", rc=plt.style.library["dark_background"]) + +Note that "dark_background" changes the default color palette to "Set2", and that will override any palette you define in :func:`set_theme`. If you'd rather use a different color palette, you'll have to call :func:`sns.set_palette` separately. The default :doc:`seaborn palette ` ("deep") has poor contrast against a dark background, so you'd be better off using "muted", "bright", or "pastel". + +Statistical inquiries +--------------------- + +.. _faq_stat_results: + +Can I access the results of seaborn's statistical transformations? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Because seaborn performs some statistical operations as it builds plots (aggregating, bootstrapping, fitting regression models), some users would like access to the statistics that it computes. This is not possible: it's explicitly considered out of scope for seaborn (a visualization library) to offer an API for interrogating statistical models. + +If you simply want to be diligent and verify that seaborn is doing things correctly (or that it matches your own code), it's open-source, so feel free to read the code. Or, because it's Python, you can call into the private methods that calculate the stats (just don't do this in production code). But don't expect seaborn to offer features that are more at home in `scipy `_ or `statsmodels `_. + +.. _faq_standard_error: + +Can I show standard error instead of a confidence interval? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As of v0.12, this is possible in most places, using the new `errorbar` API (see the :doc:`tutorial ` for more details). + +.. _faq_kde_value: + +Why does the y axis for a KDE plot go above 1? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*You've estimated a probability distribution for your data using* :func:`kdeplot`, *but the y axis goes above 1. Aren't probabilities bounded by 1? Is this a bug?* + +This is not a bug, but it is a common confusion (about kernel density plots and probability distributions more broadly). A continuous probability distribution is defined by a `probability density function `_, which :func:`kdeplot` estimates. The probability density function does **not** output *a probability*: a continuous random variable can take an infinite number of values, so the probability of observing any *specific* value is infinitely small. You can only talk meaningfully about the probability of observing a value that falls within some *range*. The probability of observing a value that falls within the complete range of possible values is 1. Likewise, the probability density function is normalized so that the area under it (that is, the integral of the function across its domain) equals 1. If the range of likely values is small, the curve will have to go above 1 to make this possible. + +Common curiosities +------------------ + +.. _faq_import_convention: + +Why is seaborn imported as `sns`? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is an obscure reference to the `namesake `_ of the library, but you can also think of it as "seaborn name space". + +.. _faq_seaborn_sucks: + +Why is ggplot so much better than seaborn? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Good question. Probably because you get to use the word "geom" a lot, and it's fun to say. "Geom". "Geeeeeooom". diff --git a/testbed/mwaskom__seaborn/doc/index.rst b/testbed/mwaskom__seaborn/doc/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..995fc04d1f8ea9654afd0e430a476a6e02d23cac --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/index.rst @@ -0,0 +1,90 @@ +:html_theme.sidebar_secondary.remove: + +seaborn: statistical data visualization +======================================= + +.. grid:: 6 + :gutter: 1 + + .. grid-item:: + + .. image:: example_thumbs/scatterplot_matrix_thumb.png + :target: ./examples/scatterplot_matrix.html + + .. grid-item:: + + .. image:: example_thumbs/errorband_lineplots_thumb.png + :target: examples/errorband_lineplots.html + + .. grid-item:: + + .. image:: example_thumbs/scatterplot_sizes_thumb.png + :target: examples/scatterplot_sizes.html + + .. grid-item:: + + .. image:: example_thumbs/timeseries_facets_thumb.png + :target: examples/timeseries_facets.html + + .. grid-item:: + + .. image:: example_thumbs/horizontal_boxplot_thumb.png + :target: examples/horizontal_boxplot.html + + .. grid-item:: + + .. image:: example_thumbs/regression_marginals_thumb.png + :target: examples/regression_marginals.html + +.. grid:: 1 1 3 3 + + .. grid-item:: + :columns: 12 12 6 6 + + Seaborn is a Python data visualization library based on `matplotlib + `_. It provides a high-level interface for drawing + attractive and informative statistical graphics. + + For a brief introduction to the ideas behind the library, you can read the + :doc:`introductory notes ` or the `paper + `_. Visit the + :doc:`installation page ` to see how you can download the package + and get started with it. You can browse the :doc:`example gallery + ` to see some of the things that you can do with seaborn, + and then check out the :doc:`tutorials ` or :doc:`API reference ` + to find out how. + + To see the code or report a bug, please visit the `GitHub repository + `_. General support questions are most at home + on `stackoverflow `_, which + has a dedicated channel for seaborn. + + .. grid-item-card:: Contents + :columns: 12 12 2 2 + :class-title: sd-fs-5 + :class-body: sd-pl-4 + + .. toctree:: + :maxdepth: 1 + + Installing + Gallery + Tutorial + API + Releases + Citing + FAQ + + .. grid-item-card:: Features + :columns: 12 12 4 4 + :class-title: sd-fs-5 + :class-body: sd-pl-3 + + * :bdg-secondary:`New` Objects: :ref:`API ` | :doc:`Tutorial ` + * Relational plots: :ref:`API ` | :doc:`Tutorial ` + * Distribution plots: :ref:`API ` | :doc:`Tutorial ` + * Categorical plots: :ref:`API ` | :doc:`Tutorial ` + * Regression plots: :ref:`API ` | :doc:`Tutorial ` + * Multi-plot grids: :ref:`API ` | :doc:`Tutorial ` + * Figure theming: :ref:`API ` | :doc:`Tutorial ` + * Color palettes: :ref:`API ` | :doc:`Tutorial ` diff --git a/testbed/mwaskom__seaborn/doc/installing.rst b/testbed/mwaskom__seaborn/doc/installing.rst new file mode 100644 index 0000000000000000000000000000000000000000..e1449d32ec73f7b0bd6b772c337bcd73f50f042f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/installing.rst @@ -0,0 +1,138 @@ +.. _installing: + +.. currentmodule:: seaborn + +Installing and getting started +------------------------------ + +Official releases of seaborn can be installed from `PyPI `_:: + + pip install seaborn + +The basic invocation of `pip` will install seaborn and, if necessary, its mandatory dependencies. +It is possible to include optional dependencies that give access to a few advanced features:: + + pip install seaborn[stats] + +The library is also included as part of the `Anaconda `_ distribution, +and it can be installed with `conda`:: + + conda install seaborn + +As the main Anaconda repository can be slow to add new releases, you may prefer using the +`conda-forge `_ channel:: + + conda install seaborn -c conda-forge + +Dependencies +~~~~~~~~~~~~ + +Supported Python versions +^^^^^^^^^^^^^^^^^^^^^^^^^ + +- Python 3.8+ + +Mandatory dependencies +^^^^^^^^^^^^^^^^^^^^^^ + +- `numpy `__ + +- `pandas `__ + +- `matplotlib `__ + +Optional dependencies +^^^^^^^^^^^^^^^^^^^^^ + +- `statsmodels `__, for advanced regression plots + +- `scipy `__, for clustering matrices and some advanced options + +- `fastcluster `__, faster clustering of large matrices + +Quickstart +~~~~~~~~~~ + +Once you have seaborn installed, you're ready to get started. +To test it out, you could load and plot one of the example datasets:: + + import seaborn as sns + df = sns.load_dataset("penguins") + sns.pairplot(df, hue="species") + +If you're working in a Jupyter notebook or an IPython terminal with +`matplotlib mode `_ +enabled, you should immediately see :ref:`the plot `. +Otherwise, you may need to explicitly call :func:`matplotlib.pyplot.show`:: + + import matplotlib.pyplot as plt + plt.show() + +While you can get pretty far with only seaborn imported, having access to +matplotlib functions is often useful. The tutorials and API documentation +typically assume the following imports:: + + import numpy as np + import pandas as pd + + import matplotlib as mpl + import matplotlib.pyplot as plt + + import seaborn as sns + import seaborn.objects as so + +Debugging install issues +~~~~~~~~~~~~~~~~~~~~~~~~ + +The seaborn codebase is pure Python, and the library should generally install +without issue. Occasionally, difficulties will arise because the dependencies +include compiled code and link to system libraries. These difficulties +typically manifest as errors on import with messages such as ``"DLL load +failed"``. To debug such problems, read through the exception trace to +figure out which specific library failed to import, and then consult the +installation docs for that package to see if they have tips for your particular +system. + +In some cases, an installation of seaborn will appear to succeed, but trying +to import it will raise an error with the message ``"No module named +seaborn"``. This usually means that you have multiple Python installations on +your system and that your ``pip`` or ``conda`` points towards a different +installation than where your interpreter lives. Resolving this issue +will involve sorting out the paths on your system, but it can sometimes be +avoided by invoking ``pip`` with ``python -m pip install seaborn``. + +Getting help +~~~~~~~~~~~~ + +If you think you've encountered a bug in seaborn, please report it on the +`GitHub issue tracker `_. +To be useful, bug reports must include the following information: + +- A reproducible code example that demonstrates the problem +- The output that you are seeing (an image of a plot, or the error message) +- A clear explanation of why you think something is wrong +- The specific versions of seaborn and matplotlib that you are working with + +Bug reports are easiest to address if they can be demonstrated using one of the +example datasets from the seaborn docs (i.e. with :func:`load_dataset`). +Otherwise, it is preferable that your example generate synthetic data to +reproduce the problem. If you can only demonstrate the issue with your +actual dataset, you will need to share it, ideally as a csv. + +If you've encountered an error, searching the specific text of the message +before opening a new issue can often help you solve the problem quickly and +avoid making a duplicate report. + +Because matplotlib handles the actual rendering, errors or incorrect outputs +may be due to a problem in matplotlib rather than one in seaborn. It can save time +if you try to reproduce the issue in an example that uses only matplotlib, +so that you can report it in the right place. But it is alright to skip this +step if it's not obvious how to do it. + +General support questions are more at home on either `stackoverflow +`_, where there is a +larger audience of people who will see your post and may be able to offer +assistance. Your chance of getting a quick answer will be higher if you include +`runnable code `_, +a precise statement of what you are hoping to achieve, and a clear explanation +of the problems that you have encountered. diff --git a/testbed/mwaskom__seaborn/doc/make.bat b/testbed/mwaskom__seaborn/doc/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..32bb24529f92346af26219baed295b7488b77534 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/testbed/mwaskom__seaborn/doc/matplotlibrc b/testbed/mwaskom__seaborn/doc/matplotlibrc new file mode 100644 index 0000000000000000000000000000000000000000..67a95bbfd01f567ca68511bf627a627dc56d7843 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/matplotlibrc @@ -0,0 +1 @@ +savefig.bbox : tight diff --git a/testbed/mwaskom__seaborn/doc/sphinxext/gallery_generator.py b/testbed/mwaskom__seaborn/doc/sphinxext/gallery_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8e08b014e312aa0f9ba5fa87d2d2efa06168eb --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/sphinxext/gallery_generator.py @@ -0,0 +1,393 @@ +""" +Sphinx plugin to run example scripts and create a gallery page. + +Lightly modified from the mpld3 project. + +""" +import os +import os.path as op +import re +import glob +import token +import tokenize +import shutil +import warnings + +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt # noqa: E402 + + +# Python 3 has no execfile +def execfile(filename, globals=None, locals=None): + with open(filename, "rb") as fp: + exec(compile(fp.read(), filename, 'exec'), globals, locals) + + +RST_TEMPLATE = """ + +.. currentmodule:: seaborn + +.. _{sphinx_tag}: + +{docstring} + +.. image:: {img_file} + +**seaborn components used:** {components} + +.. literalinclude:: {fname} + :lines: {end_line}- + +""" + + +INDEX_TEMPLATE = """ +:html_theme.sidebar_secondary.remove: + +.. raw:: html + + + +.. _{sphinx_tag}: + +Example gallery +=============== + +{toctree} + +{contents} + +.. raw:: html + +
+""" + + +def create_thumbnail(infile, thumbfile, + width=275, height=275, + cx=0.5, cy=0.5, border=4): + baseout, extout = op.splitext(thumbfile) + + im = matplotlib.image.imread(infile) + rows, cols = im.shape[:2] + x0 = int(cx * cols - .5 * width) + y0 = int(cy * rows - .5 * height) + xslice = slice(x0, x0 + width) + yslice = slice(y0, y0 + height) + thumb = im[yslice, xslice] + thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 + thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 + + dpi = 100 + fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) + + ax = fig.add_axes([0, 0, 1, 1], aspect='auto', + frameon=False, xticks=[], yticks=[]) + if all(thumb.shape): + ax.imshow(thumb, aspect='auto', resample=True, + interpolation='bilinear') + else: + warnings.warn( + f"Bad thumbnail crop. {thumbfile} will be empty." + ) + fig.savefig(thumbfile, dpi=dpi) + return fig + + +def indent(s, N=4): + """indent a string""" + return s.replace('\n', '\n' + N * ' ') + + +class ExampleGenerator: + """Tools for generating an example page from a file""" + def __init__(self, filename, target_dir): + self.filename = filename + self.target_dir = target_dir + self.thumbloc = .5, .5 + self.extract_docstring() + with open(filename) as fid: + self.filetext = fid.read() + + outfilename = op.join(target_dir, self.rstfilename) + + # Only actually run it if the output RST file doesn't + # exist or it was modified less recently than the example + file_mtime = op.getmtime(filename) + if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime: + self.exec_file() + else: + print(f"skipping {self.filename}") + + @property + def dirname(self): + return op.split(self.filename)[0] + + @property + def fname(self): + return op.split(self.filename)[1] + + @property + def modulename(self): + return op.splitext(self.fname)[0] + + @property + def pyfilename(self): + return self.modulename + '.py' + + @property + def rstfilename(self): + return self.modulename + ".rst" + + @property + def htmlfilename(self): + return self.modulename + '.html' + + @property + def pngfilename(self): + pngfile = self.modulename + '.png' + return "_images/" + pngfile + + @property + def thumbfilename(self): + pngfile = self.modulename + '_thumb.png' + return pngfile + + @property + def sphinxtag(self): + return self.modulename + + @property + def pagetitle(self): + return self.docstring.strip().split('\n')[0].strip() + + @property + def plotfunc(self): + match = re.search(r"sns\.(.+plot)\(", self.filetext) + if match: + return match.group(1) + match = re.search(r"sns\.(.+map)\(", self.filetext) + if match: + return match.group(1) + match = re.search(r"sns\.(.+Grid)\(", self.filetext) + if match: + return match.group(1) + return "" + + @property + def components(self): + + objects = re.findall(r"sns\.(\w+)\(", self.filetext) + + refs = [] + for obj in objects: + if obj[0].isupper(): + refs.append(f":class:`{obj}`") + else: + refs.append(f":func:`{obj}`") + return ", ".join(refs) + + def extract_docstring(self): + """ Extract a module-level docstring + """ + lines = open(self.filename).readlines() + start_row = 0 + if lines[0].startswith('#!'): + lines.pop(0) + start_row = 1 + + docstring = '' + first_par = '' + line_iter = lines.__iter__() + tokens = tokenize.generate_tokens(lambda: next(line_iter)) + for tok_type, tok_content, _, (erow, _), _ in tokens: + tok_type = token.tok_name[tok_type] + if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): + continue + elif tok_type == 'STRING': + docstring = eval(tok_content) + # If the docstring is formatted with several paragraphs, + # extract the first one: + paragraphs = '\n'.join(line.rstrip() + for line in docstring.split('\n') + ).split('\n\n') + if len(paragraphs) > 0: + first_par = paragraphs[0] + break + + thumbloc = None + for i, line in enumerate(docstring.split("\n")): + m = re.match(r"^_thumb: (\.\d+),\s*(\.\d+)", line) + if m: + thumbloc = float(m.group(1)), float(m.group(2)) + break + if thumbloc is not None: + self.thumbloc = thumbloc + docstring = "\n".join([l for l in docstring.split("\n") + if not l.startswith("_thumb")]) + + self.docstring = docstring + self.short_desc = first_par + self.end_line = erow + 1 + start_row + + def exec_file(self): + print(f"running {self.filename}") + + plt.close('all') + my_globals = {'pl': plt, + 'plt': plt} + execfile(self.filename, my_globals) + + fig = plt.gcf() + fig.canvas.draw() + pngfile = op.join(self.target_dir, self.pngfilename) + thumbfile = op.join("example_thumbs", self.thumbfilename) + self.html = f"" + fig.savefig(pngfile, dpi=75, bbox_inches="tight") + + cx, cy = self.thumbloc + create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy) + + def toctree_entry(self): + return f" ./{op.splitext(self.htmlfilename)[0]}\n\n" + + def contents_entry(self): + return (".. raw:: html\n\n" + " \n\n" + "\n\n" + "".format(self.htmlfilename, + self.thumbfilename, + self.plotfunc)) + + +def main(app): + static_dir = op.join(app.builder.srcdir, '_static') + target_dir = op.join(app.builder.srcdir, 'examples') + image_dir = op.join(app.builder.srcdir, 'examples/_images') + thumb_dir = op.join(app.builder.srcdir, "example_thumbs") + source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples')) + if not op.exists(static_dir): + os.makedirs(static_dir) + + if not op.exists(target_dir): + os.makedirs(target_dir) + + if not op.exists(image_dir): + os.makedirs(image_dir) + + if not op.exists(thumb_dir): + os.makedirs(thumb_dir) + + if not op.exists(source_dir): + os.makedirs(source_dir) + + banner_data = [] + + toctree = ("\n\n" + ".. toctree::\n" + " :hidden:\n\n") + contents = "\n\n" + + # Write individual example files + for filename in sorted(glob.glob(op.join(source_dir, "*.py"))): + + ex = ExampleGenerator(filename, target_dir) + + banner_data.append({"title": ex.pagetitle, + "url": op.join('examples', ex.htmlfilename), + "thumb": op.join(ex.thumbfilename)}) + shutil.copyfile(filename, op.join(target_dir, ex.pyfilename)) + output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag, + docstring=ex.docstring, + end_line=ex.end_line, + components=ex.components, + fname=ex.pyfilename, + img_file=ex.pngfilename) + with open(op.join(target_dir, ex.rstfilename), 'w') as f: + f.write(output) + + toctree += ex.toctree_entry() + contents += ex.contents_entry() + + if len(banner_data) < 10: + banner_data = (4 * banner_data)[:10] + + # write index file + index_file = op.join(target_dir, 'index.rst') + with open(index_file, 'w') as index: + index.write(INDEX_TEMPLATE.format(sphinx_tag="example_gallery", + toctree=toctree, + contents=contents)) + + +def setup(app): + app.connect('builder-inited', main) diff --git a/testbed/mwaskom__seaborn/doc/sphinxext/tutorial_builder.py b/testbed/mwaskom__seaborn/doc/sphinxext/tutorial_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..cec5425e6fb4ca1d836b96de6e1c7f3527cea79f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/sphinxext/tutorial_builder.py @@ -0,0 +1,366 @@ +from pathlib import Path +import warnings + +from jinja2 import Environment +import yaml + +import numpy as np +import matplotlib as mpl +import seaborn as sns +import seaborn.objects as so + + +TEMPLATE = """ +:notoc: + +.. _tutorial: + +User guide and tutorial +======================= +{% for section in sections %} +{{ section.header }} +{% for page in section.pages %} +.. grid:: 1 + :gutter: 2 + + .. grid-item-card:: + + .. grid:: 2 + + .. grid-item:: + :columns: 3 + + .. image:: ./tutorial/{{ page }}.svg + :target: ./tutorial/{{ page }}.html + + .. grid-item:: + :columns: 9 + :margin: auto + + .. toctree:: + :maxdepth: 2 + + tutorial/{{ page }} +{% endfor %} +{% endfor %} +""" + + +def main(app): + + content_yaml = Path(app.builder.srcdir) / "tutorial.yaml" + tutorial_rst = Path(app.builder.srcdir) / "tutorial.rst" + + tutorial_dir = Path(app.builder.srcdir) / "tutorial" + tutorial_dir.mkdir(exist_ok=True) + + with open(content_yaml) as fid: + sections = yaml.load(fid, yaml.BaseLoader) + + for section in sections: + title = section["title"] + section["header"] = "\n".join([title, "-" * len(title)]) if title else "" + + env = Environment().from_string(TEMPLATE) + content = env.render(sections=sections) + + with open(tutorial_rst, "w") as fid: + fid.write(content) + + for section in sections: + for page in section["pages"]: + if ( + not (svg_path := tutorial_dir / f"{page}.svg").exists() + or svg_path.stat().st_mtime < Path(__file__).stat().st_mtime + ): + write_thumbnail(svg_path, page) + + +def write_thumbnail(svg_path, page): + + with ( + sns.axes_style("dark"), + sns.plotting_context("notebook"), + sns.color_palette("deep") + ): + fig = globals()[page]() + for ax in fig.axes: + ax.set(xticklabels=[], yticklabels=[], xlabel="", ylabel="", title="") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fig.tight_layout() + fig.savefig(svg_path, format="svg") + + +def introduction(): + + tips = sns.load_dataset("tips") + fmri = sns.load_dataset("fmri").query("region == 'parietal'") + penguins = sns.load_dataset("penguins") + + f = mpl.figure.Figure(figsize=(5, 5)) + with sns.axes_style("whitegrid"): + f.subplots(2, 2) + + sns.scatterplot( + tips, x="total_bill", y="tip", hue="sex", size="size", + alpha=.75, palette=["C0", ".5"], legend=False, ax=f.axes[0], + ) + sns.kdeplot( + tips.query("size != 5"), x="total_bill", hue="size", + palette="blend:C0,.5", fill=True, linewidth=.5, + legend=False, common_norm=False, ax=f.axes[1], + ) + sns.lineplot( + fmri, x="timepoint", y="signal", hue="event", + errorbar=("se", 2), legend=False, palette=["C0", ".5"], ax=f.axes[2], + ) + sns.boxplot( + penguins, x="bill_depth_mm", y="species", hue="sex", + whiskerprops=dict(linewidth=1.5), medianprops=dict(linewidth=1.5), + boxprops=dict(linewidth=1.5), capprops=dict(linewidth=0), + width=.5, palette=["C0", ".8"], whis=5, ax=f.axes[3], + ) + f.axes[3].legend_ = None + for ax in f.axes: + ax.set(xticks=[], yticks=[]) + return f + + +def function_overview(): + + from matplotlib.patches import FancyBboxPatch + + f = mpl.figure.Figure(figsize=(7, 5)) + with sns.axes_style("white"): + ax = f.subplots() + f.subplots_adjust(0, 0, 1, 1) + ax.set_axis_off() + ax.set(xlim=(0, 1), ylim=(0, 1)) + + deep = sns.color_palette("deep") + colors = dict(relational=deep[0], distributions=deep[1], categorical=deep[2]) + dark = sns.color_palette("dark") + text_colors = dict(relational=dark[0], distributions=dark[1], categorical=dark[2]) + + functions = dict( + relational=["scatterplot", "lineplot"], + distributions=["histplot", "kdeplot", "ecdfplot", "rugplot"], + categorical=[ + "stripplot", "swarmplot", "boxplot", "violinplot", "pointplot", "barplot" + ], + ) + pad, w, h = .06, .2, .15 + xs, y = np.arange(0, 1, 1 / 3) + pad * 1.05, .7 + for x, mod in zip(xs, functions): + color = colors[mod] + (.2,) + text_color = text_colors[mod] + ax.add_artist(FancyBboxPatch((x, y), w, h, f"round,pad={pad}", color="white")) + ax.add_artist(FancyBboxPatch( + (x, y), w, h, f"round,pad={pad}", + linewidth=1, edgecolor=text_color, facecolor=color, + )) + ax.text( + x + w / 2, y + h / 2, f"{mod[:3]}plot\n({mod})", + ha="center", va="center", size=20, color=text_color + ) + for i, func in enumerate(functions[mod]): + x_i, y_i = x + w / 2, y - i * .1 - h / 2 - pad + xy = x_i - w / 2, y_i - pad / 3 + ax.add_artist( + FancyBboxPatch(xy, w, h / 4, f"round,pad={pad / 3}", color="white") + ) + ax.add_artist(FancyBboxPatch( + xy, w, h / 4, f"round,pad={pad / 3}", + linewidth=1, edgecolor=text_color, facecolor=color + )) + ax.text(x_i, y_i, func, ha="center", va="center", size=16, color=text_color) + ax.plot([x_i, x_i], [y, y_i], zorder=-100, color=text_color, lw=1) + return f + + +def data_structure(): + + f = mpl.figure.Figure(figsize=(7, 5)) + gs = mpl.gridspec.GridSpec( + figure=f, ncols=6, nrows=2, height_ratios=(1, 20), + left=0, right=.35, bottom=0, top=.9, wspace=.1, hspace=.01 + ) + colors = [c + (.5,) for c in sns.color_palette("deep")] + f.add_subplot(gs[0, :], facecolor=".8") + for i in range(gs.ncols): + f.add_subplot(gs[1:, i], facecolor=colors[i]) + + gs = mpl.gridspec.GridSpec( + figure=f, ncols=2, nrows=2, height_ratios=(1, 8), width_ratios=(1, 11), + left=.4, right=1, bottom=.2, top=.8, wspace=.015, hspace=.02 + ) + f.add_subplot(gs[0, 1:], facecolor=colors[2]) + f.add_subplot(gs[1:, 0], facecolor=colors[1]) + f.add_subplot(gs[1, 1], facecolor=colors[0]) + return f + + +def error_bars(): + + diamonds = sns.load_dataset("diamonds") + with sns.axes_style("whitegrid"): + g = sns.catplot( + diamonds, x="carat", y="clarity", hue="clarity", kind="point", + errorbar=("sd", .5), join=False, legend=False, facet_kws={"despine": False}, + palette="ch:s=-.2,r=-.2,d=.4,l=.6_r", scale=.75, capsize=.3, + ) + g.ax.yaxis.set_inverted(False) + return g.figure + + +def properties(): + + f = mpl.figure.Figure(figsize=(5, 5)) + + x = np.arange(1, 11) + y = np.zeros_like(x) + + p = so.Plot(x, y) + ps = 14 + plots = [ + p.add(so.Dot(pointsize=ps), color=map(str, x)), + p.add(so.Dot(color=".3", pointsize=ps), alpha=x), + p.add(so.Dot(color=".9", pointsize=ps, edgewidth=2), edgecolor=x), + p.add(so.Dot(color=".3"), pointsize=x).scale(pointsize=(4, 18)), + p.add(so.Dot(pointsize=ps, color=".9", edgecolor=".2"), edgewidth=x), + p.add(so.Dot(pointsize=ps, color=".3"), marker=map(str, x)), + p.add(so.Dot(pointsize=ps, color=".3", marker="x"), stroke=x), + ] + + with sns.axes_style("ticks"): + axs = f.subplots(len(plots)) + for p, ax in zip(plots, axs): + p.on(ax).plot() + ax.set(xticks=x, yticks=[], xticklabels=[], ylim=(-.2, .3)) + sns.despine(ax=ax, left=True) + f.legends = [] + return f + + +def objects_interface(): + + f = mpl.figure.Figure(figsize=(5, 4)) + C = sns.color_palette("deep") + ax = f.subplots() + fontsize = 22 + rects = [((.135, .50), .69), ((.275, .38), .26), ((.59, .38), .40)] + for i, (xy, w) in enumerate(rects): + ax.add_artist(mpl.patches.Rectangle(xy, w, .09, color=C[i], alpha=.2, lw=0)) + ax.text(0, .52, "Plot(data, 'x', 'y', color='var1')", size=fontsize, color=".2") + ax.text(0, .40, ".add(Dot(alpha=.5), marker='var2')", size=fontsize, color=".2") + annots = [ + ("Mapped\nin all layers", (.48, .62), (0, 55)), + ("Set directly", (.41, .35), (0, -55)), + ("Mapped\nin this layer", (.80, .35), (0, -55)), + ] + for i, (text, xy, xytext) in enumerate(annots): + ax.annotate( + text, xy, xytext, + textcoords="offset points", fontsize=18, ha="center", va="center", + arrowprops=dict(arrowstyle="->", linewidth=1.5, color=C[i]), color=C[i], + ) + ax.set_axis_off() + f.subplots_adjust(0, 0, 1, 1) + + return f + + +def relational(): + + mpg = sns.load_dataset("mpg") + with sns.axes_style("ticks"): + g = sns.relplot( + data=mpg, x="horsepower", y="mpg", size="displacement", hue="weight", + sizes=(50, 500), hue_norm=(2000, 4500), alpha=.75, legend=False, + palette="ch:start=-.5,rot=.7,dark=.3,light=.7_r", + ) + g.figure.set_size_inches(5, 5) + return g.figure + + +def distributions(): + + penguins = sns.load_dataset("penguins").dropna() + with sns.axes_style("white"): + g = sns.displot( + penguins, x="flipper_length_mm", row="island", + binwidth=4, kde=True, line_kws=dict(linewidth=2), legend=False, + ) + sns.despine(left=True) + g.figure.set_size_inches(5, 5) + return g.figure + + +def categorical(): + + penguins = sns.load_dataset("penguins").dropna() + with sns.axes_style("whitegrid"): + g = sns.catplot( + penguins, x="sex", y="body_mass_g", hue="island", col="sex", + kind="box", whis=np.inf, legend=False, sharex=False, + ) + sns.despine(left=True) + g.figure.set_size_inches(5, 5) + return g.figure + + +def regression(): + + anscombe = sns.load_dataset("anscombe") + with sns.axes_style("white"): + g = sns.lmplot( + anscombe, x="x", y="y", hue="dataset", col="dataset", col_wrap=2, + scatter_kws=dict(edgecolor=".2", facecolor=".7", s=80), + line_kws=dict(lw=4), ci=None, + ) + g.set(xlim=(2, None), ylim=(2, None)) + g.figure.set_size_inches(5, 5) + return g.figure + + +def axis_grids(): + + penguins = sns.load_dataset("penguins").sample(200, random_state=0) + with sns.axes_style("ticks"): + g = sns.pairplot( + penguins.drop("flipper_length_mm", axis=1), + diag_kind="kde", diag_kws=dict(fill=False), + plot_kws=dict(s=40, fc="none", ec="C0", alpha=.75, linewidth=.75), + ) + g.figure.set_size_inches(5, 5) + return g.figure + + +def aesthetics(): + + f = mpl.figure.Figure(figsize=(5, 5)) + for i, style in enumerate(["darkgrid", "white", "ticks", "whitegrid"], 1): + with sns.axes_style(style): + ax = f.add_subplot(2, 2, i) + ax.set(xticks=[0, .25, .5, .75, 1], yticks=[0, .25, .5, .75, 1]) + sns.despine(ax=f.axes[1]) + sns.despine(ax=f.axes[2]) + return f + + +def color_palettes(): + + f = mpl.figure.Figure(figsize=(5, 5)) + palettes = ["deep", "husl", "gray", "ch:", "mako", "vlag", "icefire"] + axs = f.subplots(len(palettes)) + x = np.arange(10) + for ax, name in zip(axs, palettes): + cmap = mpl.colors.ListedColormap(sns.color_palette(name, x.size)) + ax.pcolormesh(x[None, :], linewidth=.5, edgecolor="w", alpha=.8, cmap=cmap) + ax.set_axis_off() + return f + + +def setup(app): + app.connect("builder-inited", main) diff --git a/testbed/mwaskom__seaborn/doc/tools/extract_examples.py b/testbed/mwaskom__seaborn/doc/tools/extract_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..36b0eff6265c4be2f0084098dfd9625d03d6cf74 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/tools/extract_examples.py @@ -0,0 +1,73 @@ +"""Turn the examples section of a function docstring into a notebook.""" +import re +import sys +import pydoc +import seaborn +from seaborn.external.docscrape import NumpyDocString +import nbformat + + +def line_type(line): + + if line.startswith(" "): + return "code" + else: + return "markdown" + + +def add_cell(nb, lines, cell_type): + + cell_objs = { + "code": nbformat.v4.new_code_cell, + "markdown": nbformat.v4.new_markdown_cell, + } + text = "\n".join(lines) + cell = cell_objs[cell_type](text) + nb["cells"].append(cell) + + +if __name__ == "__main__": + + _, name = sys.argv + + # Parse the docstring and get the examples section + obj = getattr(seaborn, name) + if obj.__class__.__name__ != "function": + obj = obj.__init__ + lines = NumpyDocString(pydoc.getdoc(obj))["Examples"] + + # Remove code indentation, the prompt, and mpl return variable + pat = re.compile(r"\s{4}[>\.]{3} (ax = ){0,1}(g = ){0,1}") + + nb = nbformat.v4.new_notebook() + + # We always start with at least one line of text + cell_type = "markdown" + cell = [] + + for line in lines: + + # Ignore matplotlib plot directive + if ".. plot" in line or ":context:" in line: + continue + + # Ignore blank lines + if not line: + continue + + if line_type(line) != cell_type: + # We are on the first line of the next cell, + # so package up the last cell + add_cell(nb, cell, cell_type) + cell_type = line_type(line) + cell = [] + + if line_type(line) == "code": + line = re.sub(pat, "", line) + + cell.append(line) + + # Package the final cell + add_cell(nb, cell, cell_type) + + nbformat.write(nb, f"docstrings/{name}.ipynb") diff --git a/testbed/mwaskom__seaborn/doc/tools/generate_logos.py b/testbed/mwaskom__seaborn/doc/tools/generate_logos.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1477a9bbec1cdc96709059f59a7a729bf21309 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/tools/generate_logos.py @@ -0,0 +1,224 @@ +import numpy as np +import seaborn as sns +from matplotlib import patches +import matplotlib.pyplot as plt +from scipy.signal import gaussian +from scipy.spatial import distance + + +XY_CACHE = {} + +STATIC_DIR = "_static" +plt.rcParams["savefig.dpi"] = 300 + + +def poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None): + """Find positions using poisson-disc sampling.""" + # See http://bost.ocks.org/mike/algorithms/ + rng = np.random.default_rng(seed) + uniform = rng.uniform + randint = rng.integers + + # Cache the results + key = array_radius, pad_radius, seed + if key in XY_CACHE: + return XY_CACHE[key] + + # Start at a fixed point we know will work + start = np.zeros(d) + samples = [start] + queue = [start] + + while queue: + + # Pick a sample to expand from + s_idx = randint(len(queue)) + s = queue[s_idx] + + for i in range(candidates): + # Generate a candidate from this sample + coords = uniform(s - 2 * pad_radius, s + 2 * pad_radius, d) + + # Check the three conditions to accept the candidate + in_array = np.sqrt(np.sum(coords ** 2)) < array_radius + in_ring = np.all(distance.cdist(samples, [coords]) > pad_radius) + + if in_array and in_ring: + # Accept the candidate + samples.append(coords) + queue.append(coords) + break + + if (i + 1) == candidates: + # We've exhausted the particular sample + queue.pop(s_idx) + + samples = np.array(samples) + XY_CACHE[key] = samples + return samples + + +def logo( + ax, + color_kws, ring, ring_idx, edge, + pdf_means, pdf_sigma, dy, y0, w, h, + hist_mean, hist_sigma, hist_y0, lw, skip, + scatter, pad, scale, +): + + # Square, invisible axes with specified limits to center the logo + ax.set(xlim=(35 + w, 95 - w), ylim=(-3, 53)) + ax.set_axis_off() + ax.set_aspect('equal') + + # Magic numbers for the logo circle + radius = 27 + center = 65, 25 + + # Full x and y grids for a gaussian curve + x = np.arange(101) + y = gaussian(x.size, pdf_sigma) + + x0 = 30 # Magic number + xx = x[x0:] + + # Vertical distances between the PDF curves + n = len(pdf_means) + dys = np.linspace(0, (n - 1) * dy, n) - (n * dy / 2) + dys -= dys.mean() + + # Compute the PDF curves with vertical offsets + pdfs = [h * (y[x0 - m:-m] + y0 + dy) for m, dy in zip(pdf_means, dys)] + + # Add in constants to fill from bottom and to top + pdfs.insert(0, np.full(xx.shape, -h)) + pdfs.append(np.full(xx.shape, 50 + h)) + + # Color gradient + colors = sns.cubehelix_palette(n + 1 + bool(hist_mean), **color_kws) + + # White fill between curves and around edges + bg = patches.Circle( + center, radius=radius - 1 + ring, color="white", + transform=ax.transData, zorder=0, + ) + ax.add_artist(bg) + + # Clipping artist (not shown) for the interior elements + fg = patches.Circle(center, radius=radius - edge, transform=ax.transData) + + # Ring artist to surround the circle (optional) + if ring: + wedge = patches.Wedge( + center, r=radius + edge / 2, theta1=0, theta2=360, width=edge / 2, + transform=ax.transData, color=colors[ring_idx], alpha=1 + ) + ax.add_artist(wedge) + + # Add histogram bars + if hist_mean: + hist_color = colors.pop(0) + hist_y = gaussian(x.size, hist_sigma) + hist = 1.1 * h * (hist_y[x0 - hist_mean:-hist_mean] + hist_y0) + dx = x[skip] - x[0] + hist_x = xx[::skip] + hist_h = h + hist[::skip] + # Magic number to avoid tiny sliver of bar on edge + use = hist_x < center[0] + radius * .5 + bars = ax.bar( + hist_x[use], hist_h[use], bottom=-h, width=dx, + align="edge", color=hist_color, ec="w", lw=lw, + zorder=3, + ) + for bar in bars: + bar.set_clip_path(fg) + + # Add each smooth PDF "wave" + for i, pdf in enumerate(pdfs[1:], 1): + u = ax.fill_between(xx, pdfs[i - 1] + w, pdf, color=colors[i - 1], lw=0) + u.set_clip_path(fg) + + # Add scatterplot in top wave area + if scatter: + seed = sum(map(ord, "seaborn logo")) + xy = poisson_disc_sample(radius - edge - ring, pad, seed=seed) + clearance = distance.cdist(xy + center, np.c_[xx, pdfs[-2]]) + use = clearance.min(axis=1) > pad / 1.8 + x, y = xy[use].T + sizes = (x - y) % 9 + + points = ax.scatter( + x + center[0], y + center[1], s=scale * (10 + sizes * 5), + zorder=5, color=colors[-1], ec="w", lw=scale / 2, + ) + path = u.get_paths()[0] + points.set_clip_path(path, transform=u.get_transform()) + u.set_visible(False) + + +def savefig(fig, shape, variant): + + fig.subplots_adjust(0, 0, 1, 1, 0, 0) + + facecolor = (1, 1, 1, 1) if bg == "white" else (1, 1, 1, 0) + + for ext in ["png", "svg"]: + fig.savefig(f"{STATIC_DIR}/logo-{shape}-{variant}bg.{ext}", facecolor=facecolor) + + +if __name__ == "__main__": + + for bg in ["white", "light", "dark"]: + + color_idx = -1 if bg == "dark" else 0 + + kwargs = dict( + color_kws=dict(start=.3, rot=-.4, light=.8, dark=.3, reverse=True), + ring=True, ring_idx=color_idx, edge=1, + pdf_means=[8, 24], pdf_sigma=16, + dy=1, y0=1.8, w=.5, h=12, + hist_mean=2, hist_sigma=10, hist_y0=.6, lw=1, skip=6, + scatter=True, pad=1.8, scale=.5, + ) + color = sns.cubehelix_palette(**kwargs["color_kws"])[color_idx] + + # ------------------------------------------------------------------------ # + + fig, ax = plt.subplots(figsize=(2, 2), facecolor="w", dpi=100) + logo(ax, **kwargs) + savefig(fig, "mark", bg) + + # ------------------------------------------------------------------------ # + + fig, axs = plt.subplots(1, 2, figsize=(8, 2), dpi=100, + gridspec_kw=dict(width_ratios=[1, 3])) + logo(axs[0], **kwargs) + + font = { + "family": "avenir", + "color": color, + "weight": "regular", + "size": 120, + } + axs[1].text(.01, .35, "seaborn", ha="left", va="center", + fontdict=font, transform=axs[1].transAxes) + axs[1].set_axis_off() + savefig(fig, "wide", bg) + + # ------------------------------------------------------------------------ # + + fig, axs = plt.subplots(2, 1, figsize=(2, 2.5), dpi=100, + gridspec_kw=dict(height_ratios=[4, 1])) + + logo(axs[0], **kwargs) + + font = { + "family": "avenir", + "color": color, + "weight": "regular", + "size": 34, + } + axs[1].text(.5, 1, "seaborn", ha="center", va="top", + fontdict=font, transform=axs[1].transAxes) + axs[1].set_axis_off() + savefig(fig, "tall", bg) diff --git a/testbed/mwaskom__seaborn/doc/tools/nb_to_doc.py b/testbed/mwaskom__seaborn/doc/tools/nb_to_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..cdcd5d0705d1c6f5e0e14fa8d8d5281341e0c1dd --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/tools/nb_to_doc.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python +"""Execute a .ipynb file, write out a processed .rst and clean .ipynb. + +Some functions in this script were copied from the nbstripout tool: + +Copyright (c) 2015 Min RK, Florian Rathgeber, Michael McNeil Forbes +2019 Casper da Costa-Luis + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +""" +import os +import sys +import nbformat +from nbconvert import RSTExporter +from nbconvert.preprocessors import ( + ExecutePreprocessor, + TagRemovePreprocessor, + ExtractOutputPreprocessor +) +from traitlets.config import Config + + +class MetadataError(Exception): + pass + + +def pop_recursive(d, key, default=None): + """dict.pop(key) where `key` is a `.`-delimited list of nested keys. + >>> d = {'a': {'b': 1, 'c': 2}} + >>> pop_recursive(d, 'a.c') + 2 + >>> d + {'a': {'b': 1}} + """ + nested = key.split('.') + current = d + for k in nested[:-1]: + if hasattr(current, 'get'): + current = current.get(k, {}) + else: + return default + if not hasattr(current, 'pop'): + return default + return current.pop(nested[-1], default) + + +def strip_output(nb): + """ + Strip the outputs, execution count/prompt number and miscellaneous + metadata from a notebook object, unless specified to keep either the + outputs or counts. + """ + keys = {'metadata': [], 'cell': {'metadata': ["execution"]}} + + nb.metadata.pop('signature', None) + nb.metadata.pop('widgets', None) + + for field in keys['metadata']: + pop_recursive(nb.metadata, field) + + if 'NB_KERNEL' in os.environ: + nb.metadata['kernelspec']['name'] = os.environ['NB_KERNEL'] + nb.metadata['kernelspec']['display_name'] = os.environ['NB_KERNEL'] + + for cell in nb.cells: + + if 'outputs' in cell: + cell['outputs'] = [] + if 'prompt_number' in cell: + cell['prompt_number'] = None + if 'execution_count' in cell: + cell['execution_count'] = None + + # Always remove this metadata + for output_style in ['collapsed', 'scrolled']: + if output_style in cell.metadata: + cell.metadata[output_style] = False + if 'metadata' in cell: + for field in ['collapsed', 'scrolled', 'ExecuteTime']: + cell.metadata.pop(field, None) + for (extra, fields) in keys['cell'].items(): + if extra in cell: + for field in fields: + pop_recursive(getattr(cell, extra), field) + return nb + + +if __name__ == "__main__": + + # Get the desired ipynb file path and parse into components + _, fpath, outdir = sys.argv + basedir, fname = os.path.split(fpath) + fstem = fname[:-6] + + # Read the notebook + with open(fpath) as f: + nb = nbformat.read(f, as_version=4) + + # Run the notebook + kernel = os.environ.get("NB_KERNEL", None) + if kernel is None: + kernel = nb["metadata"]["kernelspec"]["name"] + ep = ExecutePreprocessor( + timeout=600, + kernel_name=kernel, + extra_arguments=["--InlineBackend.rc=figure.dpi=88"] + ) + ep.preprocess(nb, {"metadata": {"path": basedir}}) + + # Remove plain text execution result outputs + for cell in nb.get("cells", {}): + if "show-output" in cell["metadata"].get("tags", []): + continue + fields = cell.get("outputs", []) + for field in fields: + if field["output_type"] == "execute_result": + data_keys = field["data"].keys() + for key in list(data_keys): + if key == "text/plain": + field["data"].pop(key) + if not field["data"]: + fields.remove(field) + + # Convert to .rst formats + exp = RSTExporter() + + c = Config() + c.TagRemovePreprocessor.remove_cell_tags = {"hide"} + c.TagRemovePreprocessor.remove_input_tags = {"hide-input"} + c.TagRemovePreprocessor.remove_all_outputs_tags = {"hide-output"} + c.ExtractOutputPreprocessor.output_filename_template = \ + f"{fstem}_files/{fstem}_" + "{cell_index}_{index}{extension}" + + exp.register_preprocessor(TagRemovePreprocessor(config=c), True) + exp.register_preprocessor(ExtractOutputPreprocessor(config=c), True) + + body, resources = exp.from_notebook_node(nb) + + # Clean the output on the notebook and save a .ipynb back to disk + nb = strip_output(nb) + with open(fpath, "wt") as f: + nbformat.write(nb, f) + + # Write the .rst file + rst_path = os.path.join(outdir, f"{fstem}.rst") + with open(rst_path, "w") as f: + f.write(body) + + # Write the individual image outputs + imdir = os.path.join(outdir, f"{fstem}_files") + if not os.path.exists(imdir): + os.mkdir(imdir) + + for imname, imdata in resources["outputs"].items(): + if imname.startswith(fstem): + impath = os.path.join(outdir, f"{imname}") + with open(impath, "wb") as f: + f.write(imdata) diff --git a/testbed/mwaskom__seaborn/doc/tools/set_nb_kernels.py b/testbed/mwaskom__seaborn/doc/tools/set_nb_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..b4546d271f5029018ce07ffd4b70cfd42c806d71 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/tools/set_nb_kernels.py @@ -0,0 +1,22 @@ +"""Recursively set the kernel name for all jupyter notebook files.""" +import sys +from glob import glob + +import nbformat + + +if __name__ == "__main__": + + _, kernel_name = sys.argv + + nb_paths = glob("./**/*.ipynb", recursive=True) + for path in nb_paths: + + with open(path) as f: + nb = nbformat.read(f, as_version=4) + + nb["metadata"]["kernelspec"]["name"] = kernel_name + nb["metadata"]["kernelspec"]["display_name"] = kernel_name + + with open(path, "w") as f: + nbformat.write(nb, f) diff --git a/testbed/mwaskom__seaborn/doc/tutorial.yaml b/testbed/mwaskom__seaborn/doc/tutorial.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d66406ceb572f298b6991c534f82814f426aa1c4 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/tutorial.yaml @@ -0,0 +1,27 @@ +- title: + pages: + - introduction +- title: API Overview + pages: + - function_overview + - data_structure +- title: Objects interface + pages: + - objects_interface + - properties +- title: Plotting functions + pages: + - relational + - distributions + - categorical +- title: Statistical operations + pages: + - error_bars + - regression +- title: Multi-plot grids + pages: + - axis_grids +- title: Figure aesthetics + pages: + - aesthetics + - color_palettes diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/index.rst b/testbed/mwaskom__seaborn/doc/whatsnew/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..8fb4e3ff973235a6ea452b07e3aee1bc7a8edf7b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/index.rst @@ -0,0 +1,92 @@ +.. _whatsnew: + +What's new in each version +========================== + +v0.12 +----- +.. toctree:: + :maxdepth: 2 + + v0.12.2 + v0.12.1 + v0.12.0 + +v0.11 +----- +.. toctree:: + :maxdepth: 2 + + v0.11.2 + v0.11.1 + v0.11.0 + +v0.10 +----- +.. toctree:: + :maxdepth: 2 + + v0.10.1 + v0.10.0 + +v0.9 +---- +.. toctree:: + :maxdepth: 2 + + v0.9.1 + v0.9.0 + +v0.8 +---- +.. toctree:: + :maxdepth: 2 + + v0.8.1 + v0.8.0 + +v0.7 +---- +.. toctree:: + :maxdepth: 2 + + v0.7.1 + v0.7.0 + +v0.6 +---- +.. toctree:: + :maxdepth: 2 + + v0.6.0 + +v0.5 +---- +.. toctree:: + :maxdepth: 2 + + v0.5.1 + v0.5.0 + +v0.4 +---- +.. toctree:: + :maxdepth: 2 + + v0.4.0 + +v0.3 +---- +.. toctree:: + :maxdepth: 2 + + v0.3.1 + v0.3.0 + +v0.2 +---- +.. toctree:: + :maxdepth: 2 + + v0.2.1 + v0.2.0 diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..8a6536285bbf8ad0b7a9eaca26f1fb76b2d4b9c4 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.0.rst @@ -0,0 +1,17 @@ + +v0.10.0 (January 2020) +---------------------- + +This is a major update that is being released simultaneously with version 0.9.1. It has all of the same features (and bugs!) as 0.9.1, but there are important changes to the dependencies. + +Most notably, all support for Python 2 has now been dropped. Support for Python 3.5 has also been dropped. Seaborn is now strictly compatible with Python 3.6+. + +Minimally supported versions of the dependent PyData libraries have also been increased, in some cases substantially. While seaborn has tended to be very conservative about maintaining compatibility with older dependencies, this was causing increasing pain during development. At the same time, these libraries are now much easier to install. Going forward, seaborn will likely stay close to the `Numpy community guidelines `_ for version support. + +This release also removes a few previously-deprecated features: + +- The ``tsplot`` function and ``seaborn.timeseries`` module have been removed. Recall that ``tsplot`` was replaced with :func:`lineplot`. + +- The ``seaborn.apionly`` entry-point has been removed. + +- The ``seaborn.linearmodels`` module (previously renamed to ``seaborn.regression``) has been removed. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc7622446d96d8ceb86b60e068679fcafe6aa81c --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.10.1.rst @@ -0,0 +1,25 @@ + +v0.10.1 (April 2020) +-------------------- + +This is minor release with bug fixes for issues identified since 0.10.0. + +- Fixed a bug that appeared within the bootstrapping algorithm on 32-bit systems. + +- Fixed a bug where :func:`regplot` would crash on singleton inputs. Now a crash is avoided and regression estimation/plotting is skipped. + +- Fixed a bug where :func:`heatmap` would ignore user-specified under/over/bad values when recentering a colormap. + +- Fixed a bug where :func:`heatmap` would use values from masked cells when computing default colormap limits. + +- Fixed a bug where :func:`despine` would cause an error when trying to trim spines on a matplotlib categorical axis. + +- Adapted to a change in matplotlib that caused problems with single swarm plots. + +- Added the ``showfliers`` parameter to :func:`boxenplot` to suppress plotting of outlier data points, matching the API of :func:`boxplot`. + +- Avoided seeing an error from statmodels when data with an IQR of 0 is passed to :func:`kdeplot`. + +- Added the ``legend.title_fontsize`` to the :func:`plotting_context` definition. + +- Deprecated several utility functions that are no longer used internally (``percentiles``, ``sig_stars``, ``pmf_hist``, and ``sort_df``). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..955efdae0a076098c8c387a374dfbb16ea3f46e7 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.0.rst @@ -0,0 +1,212 @@ + +v0.11.0 (September 2020) +------------------------ + +This is a major release with several important new features, enhancements to existing functions, and changes to the library. Highlights include an overhaul and modernization of the distributions plotting functions, more flexible data specification, new colormaps, and better narrative documentation. + +For an overview of the new features and a guide to updating, see `this Medium post `_. + +Required keyword arguments +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|API| + +Most plotting functions now require all of their parameters to be specified using keyword arguments. To ease adaptation, code without keyword arguments will trigger a ``FutureWarning`` in v0.11. In a future release (v0.12 or v0.13, depending on release cadence), this will become an error. Once keyword arguments are fully enforced, the signature of the plotting functions will be reorganized to accept ``data`` as the first and only positional argument (:pr:`2052,2081`). + +Modernization of distribution functions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The distribution module has been completely overhauled, modernizing the API and introducing several new functions and features within existing functions. Some new features are explained here; the :doc:`tutorial documentation
` has also been rewritten and serves as a good introduction to the functions. + +New plotting functions +^^^^^^^^^^^^^^^^^^^^^^ + +|Feature| |Enhancement| + +First, three new functions, :func:`displot`, :func:`histplot` and :func:`ecdfplot` have been added (:pr:`2157`, :pr:`2125`, :pr:`2141`). + +The figure-level :func:`displot` function is an interface to the various distribution plots (analogous to :func:`relplot` or :func:`catplot`). It can draw univariate or bivariate histograms, density curves, ECDFs, and rug plots on a :class:`FacetGrid`. + +The axes-level :func:`histplot` function draws univariate or bivariate histograms with a number of features, including: + +- mapping multiple distributions with a ``hue`` semantic +- normalization to show density, probability, or frequency statistics +- flexible parameterization of bin size, including proper bins for discrete variables +- adding a KDE fit to show a smoothed distribution over all bin statistics +- experimental support for histograms over categorical and datetime variables. + +The axes-level :func:`ecdfplot` function draws univariate empirical cumulative distribution functions, using a similar interface. + +Changes to existing functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +|API| |Feature| |Enhancement| |Defaults| + +Second, the existing functions :func:`kdeplot` and :func:`rugplot` have been completely overhauled (:pr:`2060,2104`). + +The overhauled functions now share a common API with the rest of seaborn, they can show conditional distributions by mapping a third variable with a ``hue`` semantic, and they have been improved in numerous other ways. The github pull request (:pr:`2104`) has a longer explanation of the changes and the motivation behind them. + +This is a necessarily API-breaking change. The parameter names for the positional variables are now ``x`` and ``y``, and the old names have been deprecated. Efforts were made to handle and warn when using the deprecated API, but it is strongly suggested to check your plots carefully. + +Additionally, the statsmodels-based computation of the KDE has been removed. Because there were some inconsistencies between the way different parameters (specifically, ``bw``, ``clip``, and ``cut``) were implemented by each backend, this may cause plots to look different with non-default parameters. Support for using non-Gaussian kernels, which was available only in the statsmodels backend, has been removed. + +Other new features include: + +- several options for representing multiple densities (using the ``multiple`` and ``common_norm`` parameters) +- weighted density estimation (using the new ``weights`` parameter) +- better control over the smoothing bandwidth (using the new ``bw_adjust`` parameter) +- more meaningful parameterization of the contours that represent a bivariate density (using the ``thresh`` and ``levels`` parameters) +- log-space density estimation (using the new ``log_scale`` parameter, or by scaling the data axis before plotting) +- "bivariate" rug plots with a single function call (by assigning both ``x`` and ``y``) + +Deprecations +^^^^^^^^^^^^ + +|API| + +Finally, the :func:`distplot` function is now formally deprecated. Its features have been subsumed by :func:`displot` and :func:`histplot`. Some effort was made to gradually transition :func:`distplot` by adding the features in :func:`displot` and handling backwards compatibility, but this proved to be too difficult. The similarity in the names will likely cause some confusion during the transition, which is regrettable. + +Related enhancements and changes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +|API| |Feature| |Enhancement| |Defaults| + +These additions facilitated new features (and forced changes) in :func:`jointplot` and :class:`JointGrid` (:pr:`2210`) and in :func:`pairplot` and :class:`PairGrid` (:pr:`2234`). + +- Added support for the ``hue`` semantic in :func:`jointplot`/:class:`JointGrid`. This support is lightweight and simply delegates the mapping to the underlying axes-level functions. + +- Delegated the handling of ``hue`` in :class:`PairGrid`/:func:`pairplot` to the plotting function when it understands ``hue``, meaning that (1) the zorder of scatterplot points will be determined by row in dataframe, (2) additional options for resolving hue (e.g. the ``multiple`` parameter) can be used, and (3) numeric hue variables can be naturally mapped when using :func:`scatterplot`. + +- Added ``kind="hist"`` to :func:`jointplot`, which draws a bivariate histogram on the joint axes and univariate histograms on the marginal axes, as well as both ``kind="hist"`` and ``kind="kde"`` to :func:`pairplot`, which behaves likewise. + +- The various modes of :func:`jointplot` that plot marginal histograms now use :func:`histplot` rather than :func:`distplot`. This slightly changes the default appearance and affects the valid keyword arguments that can be passed to customize the plot. Likewise, the marginal histogram plots in :func:`pairplot` now use :func:`histplot`. + +Standardization and enhancements of data ingest +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|Feature| |Enhancement| |Docs| + +The code that processes input data has been refactored and enhanced. In v0.11, this new code takes effect for the relational and distribution modules; other modules will be refactored to use it in future releases (:pr:`2071`). + +These changes should be transparent for most use-cases, although they allow a few new features: + +- Named variables for long-form data can refer to the named index of a :class:`pandas.DataFrame` or to levels in the case of a multi-index. Previously, it was necessary to call :meth:`pandas.DataFrame.reset_index` before using index variables (e.g., after a groupby operation). +- :func:`relplot` now has the same flexibility as the axes-level functions to accept data in long- or wide-format and to accept data vectors (rather than named variables) in long-form mode. +- The data parameter can now be a Python ``dict`` or an object that implements that interface. This is a new feature for wide-form data. For long-form data, it was previously supported but not documented. +- A wide-form data object can have a mixture of types; the non-numeric types will be removed before plotting. Previously, this caused an error. +- There are better error messages for other instances of data mis-specification. + +See the new user guide chapter on :doc:`data formats
` for more information about what is supported. + +Other changes +~~~~~~~~~~~~~ + +Documentation improvements +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- |Docs| Added two new chapters to the user guide, one giving an overview of the :doc:`types of functions in seaborn
`, and one discussing the different :doc:`data formats
` that seaborn understands. + +- |Docs| Expanded the :doc:`color palette tutorial
` to give more background on color theory and better motivate the use of color in statistical graphics. + +- |Docs| Added more information to the :doc:`installation guidelines
` and streamlined the :doc:`introduction
` page. + +- |Docs| Improved cross-linking within the seaborn docs and between the seaborn and matplotlib docs. + +Theming +^^^^^^^ + +- |API| The :func:`set` function has been renamed to :func:`set_theme` for more clarity about what it does. For the foreseeable future, :func:`set` will remain as an alias, but it is recommended to update your code. + +Relational plots +^^^^^^^^^^^^^^^^ + +- |Enhancement| |Defaults| Reduced some of the surprising behavior of relational plot legends when using a numeric hue or size mapping (:pr:`2229`): + + - Added an "auto" mode (the new default) that chooses between "brief" and "full" legends based on the number of unique levels of each variable. + - Modified the ticking algorithm for a "brief" legend to show up to 6 values and not to show values outside the limits of the data. + - Changed the approach to the legend title: the normal matplotlib legend title is used when only one variable is assigned a semantic mapping, whereas the old approach of adding an invisible legend artist with a subtitle label is used only when multiple semantic variables are defined. + - Modified legend subtitles to be left-aligned and to be drawn in the default legend title font size. + +- |Enhancement| |Defaults| Changed how functions that use different representations for numeric and categorical data handle vectors with an ``object`` data type. Previously, data was considered numeric if it could be coerced to a float representation without error. Now, object-typed vectors are considered numeric only when their contents are themselves numeric. As a consequence, numbers that are encoded as strings will now be treated as categorical data (:pr:`2084`). + +- |Enhancement| |Defaults| Plots with a ``style`` semantic can now generate an infinite number of unique dashes and/or markers by default. Previously, an error would be raised if the ``style`` variable had more levels than could be mapped using the default lists. The existing defaults were slightly modified as part of this change; if you need to exactly reproduce plots from earlier versions, refer to the `old defaults `_ (:pr:`2075`). + +- |Defaults| Changed how :func:`scatterplot` sets the default linewidth for the edges of the scatter points. New behavior is to scale with the point sizes themselves (on a plot-wise, not point-wise basis). This change also slightly reduces the default width when point sizes are not varied. Set ``linewidth=0.75`` to reproduce the previous behavior. (:pr:`2708`). + +- |Enhancement| Improved support for datetime variables in :func:`scatterplot` and :func:`lineplot` (:pr:`2138`). + +- |Fix| Fixed a bug where :func:`lineplot` did not pass the ``linestyle`` parameter down to matplotlib (:pr:`2095`). + +- |Fix| Adapted to a change in matplotlib that prevented passing vectors of literal values to ``c`` and ``s`` in :func:`scatterplot` (:pr:`2079`). + +Categorical plots +^^^^^^^^^^^^^^^^^ + +- |Enhancement| |Defaults| |Fix| Fixed a few computational issues in :func:`boxenplot` and improved its visual appearance (:pr:`2086`): + + - Changed the default method for computing the number of boxes to``k_depth="tukey"``, as the previous default (``k_depth="proportion"``) is based on a heuristic that produces too many boxes for small datasets. + - Added the option to specify the specific number of boxes (e.g. ``k_depth=6``) or to plot boxes that will cover most of the data points (``k_depth="full"``). + - Added a new parameter, ``trust_alpha``, to control the number of boxes when ``k_depth="trustworthy"``. + - Changed the visual appearance of :func:`boxenplot` to more closely resemble :func:`boxplot`. Notably, thin boxes will remain visible when the edges are white. + +- |Enhancement| Allowed :func:`catplot` to use different values on the categorical axis of each facet when axis sharing is turned off (e.g. by specifying ``sharex=False``) (:pr:`2196`). + +- |Enhancement| Improved the error messages produced when categorical plots process the orientation parameter. + +- |Enhancement| Added an explicit warning in :func:`swarmplot` when more than 5% of the points overlap in the "gutters" of the swarm (:pr:`2045`). + +Multi-plot grids +^^^^^^^^^^^^^^^^ + +- |Feature| |Enhancement| |Defaults| A few small changes to make life easier when using :class:`PairGrid` (:pr:`2234`): + + - Added public access to the legend object through the ``legend`` attribute (also affects :class:`FacetGrid`). + - The ``color`` and ``label`` parameters are no longer passed to the plotting functions when ``hue`` is not used. + - The data is no longer converted to a numpy object before plotting on the marginal axes. + - It is possible to specify only one of ``x_vars`` or ``y_vars``, using all variables for the unspecified dimension. + - The ``layout_pad`` parameter is stored and used every time you call the :meth:`PairGrid.tight_layout` method. + +- |Feature| Added a ``tight_layout`` method to :class:`FacetGrid` and :class:`PairGrid`, which runs the :func:`matplotlib.pyplot.tight_layout` algorithm without interference from the external legend (:pr:`2073`). + +- |Feature| Added the ``axes_dict`` attribute to :class:`FacetGrid` for named access to the component axes (:pr:`2046`). + +- |Enhancement| Made :meth:`FacetGrid.set_axis_labels` clear labels from "interior" axes (:pr:`2046`). + +- |Feature| Added the ``marginal_ticks`` parameter to :class:`JointGrid` which, if set to ``True``, will show ticks on the count/density axis of the marginal plots (:pr:`2210`). + +- |Enhancement| Improved :meth:`FacetGrid.set_titles` with ``margin_titles=True``, such that texts representing the original row titles are removed before adding new ones (:pr:`2083`). + +- |Defaults| Changed the default value for ``dropna`` to ``False`` in :class:`FacetGrid`, :class:`PairGrid`, :class:`JointGrid`, and corresponding functions. As all or nearly all seaborn and matplotlib plotting functions handle missing data well, this option is no longer useful, but it causes problems in some edge cases. It may be deprecated in the future. (:pr:`2204`). + +- |Fix| Fixed a bug in :class:`PairGrid` that appeared when setting ``corner=True`` and ``despine=False`` (:pr:`2203`). + +Color palettes +~~~~~~~~~~~~~~ + +- |Docs| Improved and modernized the :doc:`color palettes chapter
` of the seaborn tutorial. + +- |Feature| Added two new perceptually-uniform colormaps: "flare" and "crest". The new colormaps are similar to "rocket" and "mako", but their luminance range is reduced. This makes them well suited to numeric mappings of line or scatter plots, which need contrast with the axes background at the extremes (:pr:`2237`). + +- |Enhancement| |Defaults| Enhanced numeric colormap functionality in several ways (:pr:`2237`): + + - Added string-based access within the :func:`color_palette` interface to :func:`dark_palette`, :func:`light_palette`, and :func:`blend_palette`. This means that anywhere you specify a palette in seaborn, a name like ``"dark:blue"`` will use :func:`dark_palette` with the input ``"blue"``. + - Added the ``as_cmap`` parameter to :func:`color_palette` and changed internal code that uses a continuous colormap to take this route. + - Tweaked the :func:`light_palette` and :func:`dark_palette` functions to use an endpoint that is a very desaturated version of the input color, rather than a pure gray. This produces smoother ramps. To exactly reproduce previous plots, use :func:`blend_palette` with ``".13"`` for dark or ``".95"`` for light. + - Changed :func:`diverging_palette` to have a default value of ``sep=1``, which gives better results. + +- |Enhancement| Added a rich HTML representation to the object returned by :func:`color_palette` (:pr:`2225`). + +- |Fix| Fixed the ``"{palette}_d"`` logic to modify reversed colormaps and to use the correct direction of the luminance ramp in both cases. + +Deprecations and removals +^^^^^^^^^^^^^^^^^^^^^^^^^ + +- |Enhancement| Removed an optional (and undocumented) dependency on BeautifulSoup (:pr:`2190`) in :func:`get_dataset_names`. + +- |API| Deprecated the ``axlabel`` function; use ``ax.set(xlabel=, ylabel=)`` instead. + +- |API| Deprecated the ``iqr`` function; use :func:`scipy.stats.iqr` instead. + +- |API| Final removal of the previously-deprecated ``annotate`` method on :class:`JointGrid`, along with related parameters. + +- |API| Final removal of the ``lvplot`` function (the previously-deprecated name for :func:`boxenplot`). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..208206b86664f749596436cfd08f557dee136b7f --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.1.rst @@ -0,0 +1,37 @@ + +v0.11.1 (December 2020) +----------------------- + +This a bug fix release and is a recommended upgrade for all users on v0.11.0. + +- |Enhancement| Reduced the use of matplotlib global state in the :ref:`multi-grid classes ` (:pr:`2388`). + +- |Fix| Restored support for using tuples or numeric keys to reference fields in a long-form `data` object (:pr:`2386`). + +- |Fix| Fixed a bug in :func:`lineplot` where NAs were propagating into the confidence interval, sometimes erasing it from the plot (:pr:`2273`). + +- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` where diagonal axes would be empty when the grid was not square and the diagonal axes did not contain the marginal plots (:pr:`2270`). + +- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` where off-diagonal plots would not appear when column names in `data` had non-string type (:pr:`2368`). + +- |Fix| Fixed a bug where categorical dtype information was ignored when data consisted of boolean or boolean-like values (:pr:`2379`). + +- |Fix| Fixed a bug in :class:`FacetGrid` where interior tick labels would be hidden when only the orthogonal axis was shared (:pr:`2347`). + +- |Fix| Fixed a bug in :class:`FacetGrid` that caused an error when `legend_out=False` was set (:pr:`2304`). + +- |Fix| Fixed a bug in :func:`kdeplot` where ``common_norm=True`` was ignored if ``hue`` was not assigned (:pr:`2378`). + +- |Fix| Fixed a bug in :func:`displot` where the ``row_order`` and ``col_order`` parameters were not used (:pr:`2262`). + +- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` that caused an exception when using `corner=True` and `diag_kind=None` (:pr:`2382`). + +- |Fix| Fixed a bug in :func:`clustermap` where `annot=False` was ignored (:pr:`2323`). + +- |Fix| Fixed a bug in :func:`clustermap` where row/col color annotations could not have a categorical dtype (:pr:`2389`). + +- |Fix| Fixed a bug in :func:`boxenplot` where the `linewidth` parameter was ignored (:pr:`2287`). + +- |Fix| Raise a more informative error in :class:`PairGrid`/:func:`pairplot` when no variables can be found to define the rows/columns of the grid (:pr:`2382`). + +- |Fix| Raise a more informative error from :func:`clustermap` if row/col color objects have semantic index but data object does not (:pr:`2313`). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.2.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.2.rst new file mode 100644 index 0000000000000000000000000000000000000000..97d5e642423883a7f36b5bf36dec7d679405b5d7 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.11.2.rst @@ -0,0 +1,63 @@ + +v0.11.2 (August 2021) +--------------------- + +This is a minor release that addresses issues in the v0.11 series and adds a small number of targeted enhancements. It is a recommended upgrade for all users. + +- |API| |Enhancement| In :func:`lmplot`, added a new `facet_kws` parameter and deprecated the `sharex`, `sharey`, and `legend_out` parameters from the function signature; pass them in a `facet_kws` dictionary instead (:pr:`2576`). + +- |Feature| Added a :func:`move_legend` convenience function for repositioning the legend on an existing axes or figure, along with updating its properties. This function should be preferred over calling `ax.legend` with no legend data, which does not reliably work across seaborn plot types (:pr:`2643`). + +- |Feature| In :func:`histplot`, added `stat="percent"` as an option for normalization such that bar heights sum to 100 and `stat="proportion"` as an alias for the existing `stat="probability"` (:pr:`2461`, :pr:`2634`). + +- |Feature| Added :meth:`FacetGrid.refline` and :meth:`JointGrid.refline` methods for plotting horizontal and/or vertical reference lines on every subplot in one step (:pr:`2620`). + +- |Feature| In :func:`kdeplot`, added a `warn_singular` parameter to silence the warning about data with zero variance (:pr:`2566`). + +- |Enhancement| In :func:`histplot`, improved performance with large datasets and many groupings/facets (:pr:`2559`, :pr:`2570`). + +- |Enhancement| The :class:`FacetGrid`, :class:`PairGrid`, and :class:`JointGrid` objects now reference the underlying matplotlib figure with a `.figure` attribute. The existing `.fig` attribute still exists but is discouraged and may eventually be deprecated. The effect is that you can now call `obj.figure` on the return value from any seaborn function to access the matplotlib object (:pr:`2639`). + +- |Enhancement| In :class:`FacetGrid` and functions that use it, visibility of the interior axis labels is now disabled, and exterior axis labels are no longer erased when adding additional layers. This produces the same results for plots made by seaborn functions, but it may produce different (better, in most cases) results for customized facet plots (:pr:`2583`). + +- |Enhancement| In :class:`FacetGrid`, :class:`PairGrid`, and functions that use them, the matplotlib `figure.autolayout` parameter is disabled to avoid having the legend overlap the plot (:pr:`2571`). + +- |Enhancement| The :func:`load_dataset` helper now produces a more informative error when fed a dataframe, easing a common beginner mistake (:pr:`2604`). + +- |Fix| |Enhancement| Improved robustness to missing data, including some additional support for the `pd.NA` type (:pr:`2417`, :pr:`2435`). + +- |Fix| In :func:`ecdfplot` and :func:`rugplot`, fixed a bug where results were incorrect if the data axis had a log scale before plotting (:pr:`2504`). + +- |Fix| In :func:`histplot`, fixed a bug where using `shrink` with non-discrete bins shifted bar positions inaccurately (:pr:`2477`). + +- |Fix| In :func:`displot`, fixed a bug where `common_norm=False` was ignored when faceting was used without assigning `hue` (:pr:`2468`). + +- |Fix| In :func:`histplot`, fixed two bugs where automatically computed edge widths were too thick for log-scaled histograms and for categorical histograms on the y axis (:pr:`2522`). + +- |Fix| In :func:`histplot` and :func:`kdeplot`, fixed a bug where the `alpha` parameter was ignored when `fill=False` (:pr:`2460`). + +- |Fix| In :func:`histplot` and :func:`kdeplot`, fixed a bug where the `multiple` parameter was ignored when `hue` was provided as a vector without a name (:pr:`2462`). + +- |Fix| In :func:`displot`, the default alpha value now adjusts to a provided `multiple` parameter even when `hue` is not assigned (:pr:`2462`). + +- |Fix| In :func:`displot`, fixed a bug that caused faceted 2D histograms to error out with `common_bins=False` (:pr:`2640`). + +- |Fix| In :func:`rugplot`, fixed a bug that prevented the use of datetime data (:pr:`2458`). + +- |Fix| In :func:`relplot` and :func:`displot`, fixed a bug where the dataframe attached to the returned `FacetGrid` object dropped columns that were not used in the plot (:pr:`2623`). + +- |Fix| In :func:`relplot`, fixed an error that would be raised when one of the column names in the dataframe shared a name with one of the plot variables (:pr:`2581`). + +- |Fix| In the relational plots, fixed a bug where legend entries for the `size` semantic were incorrect when `size_norm` extrapolated beyond the range of the data (:pr:`2580`). + +- |Fix| In :func:`lmplot` and :func:`regplot`, fixed a bug where the x axis was clamped to the data limits with `truncate=True` (:pr:`2576`). + +- |Fix| In :func:`lmplot`, fixed a bug where `sharey=False` did not always work as expected (:pr:`2576`). + +- |Fix| In :func:`heatmap`, fixed a bug where vertically-rotated y-axis tick labels would be misaligned with their rows (:pr:`2574`). + +- |Fix| Fixed an issue that prevented Python from running in `-OO` mode while using seaborn (:pr:`2473`). + +- |Docs| Improved the API documentation for theme-related functions (:pr:`2573`). + +- |Docs| Added docstring pages for all methods on documented classes (:pr:`2644`). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e7b77fbcf1b4368a6194e2ea2b9d29ce4d74cd1 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.0.rst @@ -0,0 +1,127 @@ +v0.12.0 (September 2022) +------------------------ + +Introduction of the objects interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This release debuts the `seaborn.objects` interface, an entirely new approach to making plots with seaborn. It is the product of several years of design and 16 months of implementation work. The interface aims to provide a more declarative, composable, and extensible API for making statistical graphics. It is inspired by Wilkinson's grammar of graphics, offering a Pythonic API that is informed by the design of libraries such as `ggplot2` and `vega-lite` along with lessons from the past 10 years of seaborn's development. + +For more information and numerous examples, see the :doc:`tutorial chapter ` and :ref:`API reference ` + +This initial release should be considered "experimental". While it is stable enough for serious use, there are definitely some rough edges, and some key features remain to be implemented. It is possible that breaking changes may occur over the next few minor releases. Please be patient with any limitations that you encounter and help the development by reporting issues when you find behavior surprising. + +Keyword-only arguments +~~~~~~~~~~~~~~~~~~~~~~ + +|API| + +Seaborn's plotting functions now require explicit keywords for most arguments, following the deprecation of positional arguments in v0.11.0. With this enforcement, most functions have also had their parameter lists rearranged so that `data` is the first and only positional argument. This adds consistency across the various functions in the library. It also means that calling `func(data)` will do something for nearly all functions (those that support wide-form data) and that :class:`pandas.DataFrame` can be piped directly into a plot. It is possible that the signatures will be loosened a bit in future releases so that `x` and `y` can be positional, but minimal support for positional arguments after this change will reduce the chance of inadvertent mis-specification (:pr:`2804`). + +Modernization of categorical scatterplots +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This release begins the process of modernizing the :ref:`categorical plots `, beginning with :func:`stripplot` and :func:`swarmplot`. These functions are sporting some enhancements that alleviate a few long-running frustrations (:pr:`2413`, :pr:`2447`): + +- |Feature| The new `native_scale` parameter allows numeric or datetime categories to be plotted with their original scale rather than converted to strings and plotted at fixed intervals. + +- |Feature| The new `formatter` parameter allows more control over the string representation of values on the categorical axis. There should also be improved defaults for some types, such as dates. + +- |Enhancement| It is now possible to assign `hue` when using only one coordinate variable (i.e. only `x` or `y`). + +- |Enhancement| It is now possible to disable the legend. + +The updates also harmonize behavior with functions that have been more recently introduced. This should be relatively non-disruptive, although a few defaults will change: + +- |Defaults| The functions now hook into matplotlib's unit system for plotting categorical data. (Seaborn's categorical functions actually predate support for categorical data in matplotlib.) This should mostly be transparent to the user, but it may resolve a few edge cases. For example, matplotlib interactivity should work better (e.g., for showing the data value under the cursor). + +- |Defaults| A color palette is no longer applied to levels of the categorical variable by default. It is now necessary to explicitly assign `hue` to see multiple colors (i.e., assign the same variable to `x`/`y` and `hue`). Passing `palette` without `hue` will continue to be honored for one release cycle. + +- |Defaults| Numeric `hue` variables now receive a continuous mapping by default, using the same rules as :func:`scatterplot`. Pass `palette="deep"` to reproduce previous defaults. + +- |Defaults| The plots now follow the default property cycle; i.e. calling an axes-level function multiple times with the same active axes will produce different-colored artists. + +- |API| Currently, assigning `hue` and then passing a `color` will produce a gradient palette. This is now deprecated, as it is easy to request a gradient with, e.g. `palette="light:blue"`. + +Similar enhancements / updates should be expected to roll out to other categorical plotting functions in future releases. There are also several function-specific enhancements: + +- |Enhancement| In :func:`stripplot`, a "strip" with a single observation will be plotted without jitter (:pr:`2413`) + +- |Enhancement| In :func:`swarmplot`, the points are now swarmed at draw time, meaning that the plot will adapt to further changes in axis scaling or tweaks to the plot layout (:pr:`2443`). + +- |Feature| In :func:`swarmplot`, the proportion of points that must overlap before issuing a warning can now be controlled with the `warn_thresh` parameter (:pr:`2447`). + +- |Fix| In :func:`swarmplot`, the order of the points in each swarm now matches the order in the original dataset; previously they were sorted. This affects only the underlying data stored in the matplotlib artist, not the visual representation (:pr:`2443`). + +More flexible errorbars +~~~~~~~~~~~~~~~~~~~~~~~ + +|API| |Feature| + +Increased the flexibility of what can be shown by the internally-calculated errorbars for :func:`lineplot`, :func:`barplot`, and :func:`pointplot`. + +With the new `errorbar` parameter, it is now possible to select bootstrap confidence intervals, percentile / predictive intervals, or intervals formed by scaled standard deviations or standard errors. The parameter also accepts an arbitrary function that maps from a vector to an interval. There is a new :doc:`user guide chapter ` demonstrating these options and explaining when you might want to use each one. + +As a consequence of this change, the `ci` parameter has been deprecated. Note that :func:`regplot` retains the previous API, but it will likely be updated in a future release (:pr:`2407`, :pr:`2866`). + +Other updates +~~~~~~~~~~~~~ + +- |Feature| It is now possible to aggregate / sort a :func:`lineplot` along the y axis using `orient="y"` (:pr:`2854`). + +- |Feature| Made it easier to customize :class:`FacetGrid` / :class:`PairGrid` / :class:`JointGrid` with a fluent (method-chained) style by adding `apply`/ `pipe` methods. Additionally, fixed the `tight_layout` and `refline` methods so that they return `self` (:pr:`2926`). + +- |Feature| Added :meth:`FacetGrid.tick_params` and :meth:`PairGrid.tick_params` to customize the appearance of the ticks, tick labels, and gridlines of all subplots at once (:pr:`2944`). + +- |Enhancement| Added a `width` parameter to :func:`barplot` (:pr:`2860`). + +- |Enhancement| It is now possible to specify `estimator` as a string in :func:`barplot` and :func:`pointplot`, in addition to a callable (:pr:`2866`). + +- |Enhancement| Error bars in :func:`regplot` now inherit the alpha value of the points they correspond to (:pr:`2540`). + +- |Enhancement| When using :func:`pairplot` with `corner=True` and `diag_kind=None`, the top left y axis label is no longer hidden (:pr:`2850`). + +- |Enhancement| It is now possible to plot a discrete :func:`histplot` as a step function or polygon (:pr:`2859`). + +- |Enhancement| It is now possible to customize the appearance of elements in a :func:`boxenplot` with `box_kws`/`line_kws`/`flier_kws` (:pr:`2909`). + +- |Fix| Improved integration with the matplotlib color cycle in most axes-level functions (:pr:`2449`). + +- |Fix| Fixed a regression in 0.11.2 that caused some functions to stall indefinitely or raise when the input data had a duplicate index (:pr:`2776`). + +- |Fix| Fixed a bug in :func:`histplot` and :func:`kdeplot` where weights were not factored into the normalization (:pr:`2812`). + +- |Fix| Fixed two edgecases in :func:`histplot` when only `binwidth` was provided (:pr:`2813`). + +- |Fix| Fixed a bug in :func:`violinplot` where inner boxes/points could be missing with unpaired split violins (:pr:`2814`). + +- |Fix| Fixed a bug in :class:`PairGrid` where an error would be raised when defining `hue` only in the mapping methods (:pr:`2847`). + +- |Fix| Fixed a bug in :func:`scatterplot` where an error would be raised when `hue_order` was a subset of the hue levels (:pr:`2848`). + +- |Fix| Fixed a bug in :func:`histplot` where dodged bars would have different widths on a log scale (:pr:`2849`). + +- |Fix| In :func:`lineplot`, allowed the `dashes` keyword to set the style of a line without mapping a `style` variable (:pr:`2449`). + +- |Fix| Improved support in :func:`relplot` for "wide" data and for faceting variables passed as non-pandas objects (:pr:`2846`). + +- |Fix| Subplot titles will no longer be reset when calling :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe` (:pr:`2705`). + +- |Fix| Added a workaround for a matplotlib issue that caused figure-level functions to freeze when `plt.show` was called (:pr:`2925`). + +- |Fix| Improved robustness to numerical errors in :func:`kdeplot` (:pr:`2862`). + +- |Fix| Fixed a bug where :func:`rugplot` was ignoring expand_margins=False (:pr:`2953`). + +- |Defaults| The `patch.facecolor` rc param is no longer set by :func:`set_palette` (or :func:`set_theme`). This should have no general effect, because the matplotlib default is now `"C0"` (:pr:`2906`). + +- |Build| Made `scipy` an optional dependency and added `pip install seaborn[stats]` as a method for ensuring the availability of compatible `scipy` and `statsmodels` libraries at install time. This has a few minor implications for existing code, which are explained in the Github pull request (:pr:`2398`). + +- |Build| Example datasets are now stored in an OS-specific cache location (as determined by `appdirs`) rather than in the user's home directory. Users should feel free to remove `~/seaborn-data` if desired (:pr:`2773`). + +- |Build| The unit test suite is no longer part of the source or wheel distribution. Seaborn has never had a runtime API for exercising the tests, so this should not have workflow implications (:pr:`2833`). + +- |Build| Following `NEP29 `_, dropped support for Python 3.6 and bumped the minimally-supported versions of the library dependencies. + +- |API| Removed the previously-deprecated `factorplot` along with several previously-deprecated utility functions (`iqr`, `percentiles`, `pmf_hist`, and `sort_df`). + +- |API| Removed the (previously-unused) option to pass additional keyword arguments to :func:`pointplot`. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..3ab6c3172b9d194c719468780e060c9dc9e18674 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.1.rst @@ -0,0 +1,37 @@ + +v0.12.1 (October 2022) +---------------------- + +This is an incremental release that is a recommended upgrade for all users. It addresses a handful of bugs / regressions in v0.12.0 and adds several features and enhancements to the new :doc:`objects interface `. + +- |Feature| Added the :class:`objects.Text` mark (:pr:`3051`). + +- |Feature| Added the :class:`objects.Dash` mark (:pr:`3074`). + +- |Feature| Added the :class:`objects.Perc` stat (:pr:`3063`). + +- |Feature| Added the :class:`objects.Count` stat (:pr:`3086`). + +- |Feature| The :class:`objects.Band` and :class:`objects.Range` marks will now cover the full extent of the data if `min` / `max` variables are not explicitly assigned or added in a transform (:pr:`3056`). + +- |Enhancement| |Defaults| The :class:`objects.Jitter` move now applies a small amount of jitter by default (:pr:`3066`). + +- |Enhancement| |Defaults| Axes with a :class:`objects.Nominal` scale now appear like categorical axes in classic seaborn, with fixed margins, no grid, and an inverted y axis (:pr:`3069`). + +- |Enhancement| |API| The :meth:`objects.Continuous.label` method now accepts `base=None` to override the default formatter with a log transform (:pr:`3087`). + +- |Enhancement| |Fix| Marks that sort along the orient axis (e.g. :class:`objects.Line`) now use a stable algorithm (:pr:`3064`). + +- |Enhancement| |Fix| Added a `label` parameter to :func:`pointplot`, which addresses a regression in 0.12.0 when :func:`pointplot` is passed to :class:`FacetGrid` (:pr:`3016`). + +- |Fix| Fixed a bug that caused an exception when more than two layers with the same mappings were added to :class:`objects.Plot` (:pr:`3055`). + +- |Fix| Made :class:`objects.PolyFit` robust to missing data (:pr:`3010`). + +- |Fix| Fixed a bug in :class:`objects.Plot` that occurred when data assigned to the orient coordinate had zero variance (:pr:`3084`). + +- |Fix| Fixed a regression in :func:`kdeplot` where passing `cmap` for an unfilled bivariate plot would raise an exception (:pr:`3065`). + +- |Fix| Addressed a performance regression in :func:`lineplot` with a large number of unique x values (:pr:`3081`). + +- |Build| Seaborn no longer contains doctest-style examples, simplifying the testing infrastructure (:pr:`3034`). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.2.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.2.rst new file mode 100644 index 0000000000000000000000000000000000000000..75bd4e7e611c3c3821d1849a3d4df1e78ba01ed5 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.12.2.rst @@ -0,0 +1,25 @@ + +v0.12.2 (December 2022) +----------------------- + +This is an incremental release that is a recommended upgrade for all users. It is very likely the final release of the 0.12 series and the last version to support Python 3.7. + +- |Feature| Added the :class:`objects.KDE` stat (:pr:`3111`). + +- |Feature| Added the :class:`objects.Boolean` scale (:pr:`3205`). + +- |Enhancement| Improved user feedback for failures during plot compilation by catching exceptions and re-raising with a `PlotSpecError` that provides additional context. (:pr:`3203`). + +- |Fix| Improved calculation of automatic mark widths with unshared facet axes (:pr:`3119`). + +- |Fix| Improved robustness to empty data in several components of the objects interface (:pr:`3202`). + +- |Fix| Fixed a bug where legends for numeric variables with large values would be incorrectly shown (i.e. with a missing offset or exponent; :pr:`3187`). + +- |Fix| Fixed a regression in v0.12.0 where manually-added labels could have duplicate legend entries (:pr:`3116`). + +- |Fix| Fixed a bug in :func:`histplot` with `kde=True` and `log_scale=True` where the curve was not scaled properly (:pr:`3173`). + +- |Fix| Fixed a bug in :func:`relplot` where inner axis labels would be shown when axis sharing was disabled (:pr:`3180`). + +- |Fix| Fixed a bug in :class:`objects.Continuous` to avoid an exception with boolean data (:pr:`3189`). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..b472f5d108e0195cd6f092797559888e7afd0650 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.0.rst @@ -0,0 +1,152 @@ + +v0.2.0 (December 2013) +---------------------- + +This is a major release from 0.1 with a number of API changes, enhancements, +and bug fixes. + +Highlights include an overhaul of timeseries plotting to work intelligently +with dataframes, the new function ``interactplot()`` for visualizing continuous +interactions, bivariate kernel density estimates in ``kdeplot()``, and +significant improvements to color palette handling. + +Version 0.2 also introduces experimental support for Python 3. + +In addition to the library enhancements, the documentation has been +substantially rewritten to reflect the new features and improve the +presentation of the ideas behind the package. + +API changes +~~~~~~~~~~~ + +- The ``tsplot()`` function was rewritten to accept data in a long-form + ``DataFrame`` and to plot different traces by condition. This introduced a + relatively minor but unavoidable API change, where instead of doing + ``sns.tsplot(time, heights)``, you now must do ``sns.tsplot(heights, + time=time)`` (the ``time`` parameter is now optional, for quicker + specification of simple plots). Additionally, the ``"obs_traces"`` and + ``"obs_points"`` error styles in ``tsplot()`` have been renamed to + ``"unit_traces"`` and ``"unit_points"``, respectively. + +- Functions that fit kernel density estimates (``kdeplot()`` and + ``violinplot()``) now use ``statsmodels`` instead of ``scipy``, and the + parameters that influence the density estimate have changed accordingly. This + allows for increased flexibility in specifying the bandwidth and kernel, and + smarter choices for defining the range of the support. Default options should + produce plots that are very close to the old defaults. + +- The ``kdeplot()`` function now takes a second positional argument of data for + drawing bivariate densities. + +- The ``violin()`` function has been changed to ``violinplot()``, for consistency. + In 0.2, ``violin`` will still work, but it will fire a ``UserWarning``. + +New plotting functions +~~~~~~~~~~~~~~~~~~~~~~ + +- The ``interactplot()`` function draws a contour plot for an interactive + linear model (i.e., the contour shows ``y-hat`` from the model ``y ~ x1 * + x2``) over a scatterplot between the two predictor variables. This plot + should aid the understanding of an interaction between two continuous + variables. + +- The ``kdeplot()`` function can now draw a bivariate density estimate as a + contour plot if provided with two-dimensional input data. + +- The ``palplot()`` function provides a simple grid-based visualization of a + color palette. + +Other changes +~~~~~~~~~~~~~ + +Plotting functions +^^^^^^^^^^^^^^^^^^ + +- The ``corrplot()`` function can be drawn without the correlation coefficient + annotation and with variable names on the side of the plot to work with large + datasets. + +- Additionally, ``corrplot()`` sets the color palette intelligently based on + the direction of the specified test. + +- The ``distplot()`` histogram uses a reference rule to choose the bin size if it + is not provided. + +- Added the ``x_bins`` option in ``lmplot()`` for binning a continuous + predictor variable, allowing for clearer trends with many datapoints. + +- Enhanced support for labeling plot elements and axes based on ``name`` + attributes in several distribution plot functions and ``tsplot()`` for + smarter Pandas integration. + +- Scatter points in ``lmplot()`` are slightly transparent so it is easy to see + where observations overlap. + +- Added the ``order`` parameter to ``boxplot()`` and ``violinplot()`` to + control the order of the bins when using a Pandas object. + +- When an ``ax`` argument is not provided to a plotting function, it grabs the + currently active axis instead of drawing a new one. + +Color palettes +^^^^^^^^^^^^^^ + +- Added the ``dark_palette()`` and ``blend_palette()`` for on-the-fly creation + of blended color palettes. + +- The color palette machinery is now intelligent about qualitative ColorBrewer + palettes (``Set1``, ``Paired``, etc.), which are properly treated as discrete. + +- Seaborn color palettes (``deep``, ``muted``, etc.) have been standardized in + terms of basic hue sequence, and all palettes now have 6 colors. + +- Introduced ``{mpl_palette}_d`` palettes, which make a palette with the basic + color scheme of the source palette, but with a sequential blend from dark + instead of light colors for use with line/scatter/contour plots. + +- Added the ``palette_context()`` function for blockwise color palettes + controlled by a ``with`` statement. + +Plot styling +^^^^^^^^^^^^ + +- Added the ``despine()`` function for easily removing plot spines. + +- A new plot style, ``"ticks"`` has been added. + +- Tick labels are padded a bit farther from the axis in all styles, avoiding + collisions at (0, 0). + +General package issues +^^^^^^^^^^^^^^^^^^^^^^ + +- Reorganized the package by breaking up the monolithic ``plotobjs`` module + into smaller modules grouped by general objective of the constituent plots. + +- Removed the ``scikits-learn`` dependency in ``moss``. + +- Installing with ``pip`` should automatically install most missing dependencies. + +- The example notebooks are now used as an automated test suite. + +Bug fixes +~~~~~~~~~ + +- Fixed a bug where labels did not match data for ``boxplot()`` and ``violinplot()`` + when using a groupby. + +- Fixed a bug in the ``desaturate()`` function. + +- Fixed a bug in the ``coefplot()`` figure size calculation. + +- Fixed a bug where ``regplot()`` choked on list input. + +- Fixed buggy behavior when drawing horizontal boxplots. + +- Specifying bins for the ``distplot()`` histogram now works. + +- Fixed a bug where ``kdeplot()`` would reset the axis height and cut off + existing data. + +- All axis styling has been moved out of the top-level ``seaborn.set()`` + function, so context or color palette can be cleanly changed. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..b12194b51b08ceea80d73888e40dacd0ac6f196b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.2.1.rst @@ -0,0 +1,24 @@ + +v0.2.1 (December 2013) +---------------------- + +This is a bugfix release, with no new features. + +Bug fixes +~~~~~~~~~ + +- Changed the mechanics of ``violinplot()`` and ``boxplot()`` when using a + ``Series`` object as data and performing a ``groupby`` to assign data to + bins to address a problem that arises in Pandas 0.13. + +- Additionally fixed the ``groupby`` code to work with all styles of group + specification (specifically, using a dictionary or a function now works). + +- Fixed a bug where artifacts from the kde fitting could undershoot and create + a plot where the density axis starts below 0. + +- Ensured that data used for kde fitting is double-typed to avoid a low-level + statsmodels error. + +- Changed the implementation of the histogram bin-width reference rule to + take a ceiling of the estimated number of bins. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..b729d4061847e546f0edecfd90b229806e359372 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.0.rst @@ -0,0 +1,58 @@ + +v0.3.0 (March 2014) +------------------- + +This is a major release from 0.2 with a number of enhancements to the plotting capabilities and styles. Highlights include :class:`FacetGrid`, ``factorplot``, :func:`jointplot`, and an overhaul to :ref:`style management `. There is also lots of new documentation, including an :ref:`example gallery ` and reorganized :ref:`tutorial `. + +New plotting functions +~~~~~~~~~~~~~~~~~~~~~~ + +- The :class:`FacetGrid` class adds a new form of functionality to seaborn, providing a way to abstractly structure a grid of plots corresponding to subsets of a dataset. It can be used with a wide variety of plotting functions (including most of the matplotlib and seaborn APIs. See the :ref:`tutorial ` for more information. + +- Version 0.3 introduces the ``factorplot`` function, which is similar in spirit to :func:`lmplot` but intended for use when the main independent variable is categorical instead of quantitative. ``factorplot`` can draw a plot in either a point or bar representation using the corresponding Axes-level functions :func:`pointplot` and :func:`barplot` (which are also new). Additionally, the ``factorplot`` function can be used to draw box plots on a faceted grid. For examples of how to use these functions, you can refer to the tutorial. + +- Another new function is :func:`jointplot`, which is built using the new :class:`JointGrid` object. :func:`jointplot` generalizes the behavior of :func:`regplot` in previous versions of seaborn (:func:`regplot` has changed somewhat in 0.3; see below for details) by drawing a bivariate plot of the relationship between two variables with their marginal distributions drawn on the side of the plot. With :func:`jointplot`, you can draw a scatterplot or regression plot as before, but you can now also draw bivariate kernel densities or hexbin plots with appropriate univariate graphs for the marginal distributions. Additionally, it's easy to use :class:`JointGrid` directly to build up more complex plots when the default methods offered by :func:`jointplot` are not suitable for your visualization problem. The tutorial for :class:`JointGrid` has more examples of how this object can be useful. + +- The :func:`residplot` function complements :func:`regplot` and can be quickly used to diagnose problems with a linear model by calculating and plotting the residuals of a simple regression. There is also a ``"resid"`` kind for :func:`jointplot`. + +API changes +~~~~~~~~~~~ + +- The most noticeable change will be that :func:`regplot` no longer produces a multi-component plot with distributions in marginal axes. Instead. :func:`regplot` is now an "Axes-level" function that can be plotted into any existing figure on a specific set of axes. :func:`regplot` and :func:`lmplot` have also been unified (the latter uses the former behind the scenes), so all options for how to fit and represent the regression model can be used for both functions. To get the old behavior of :func:`regplot`, use :func:`jointplot` with ``kind="reg"``. + +- As noted above, :func:`lmplot` has been rewritten to exploit the :class:`FacetGrid` machinery. This involves a few changes. The ``color`` keyword argument has been replaced with ``hue``, for better consistency across the package. The ``hue`` parameter will always take a variable *name*, while ``color`` will take a color name or (in some cases) a palette. The :func:`lmplot` function now returns the :class:`FacetGrid` used to draw the plot instance. + +- The functions that interact with matplotlib rc parameters have been updated and standardized. There are now three pairs of functions, :func:`axes_style` and :func:`set_style`, :func:`plotting_context` and :func:`set_context`, and :func:`color_palette` and :func:`set_palette`. In each case, the pairs take the exact same arguments. The first function defines and returns the parameters, and the second sets the matplotlib defaults. Additionally, the first function in each pair can be used in a ``with`` statement to temporarily change the defaults. Both the style and context functions also now accept a dictionary of matplotlib rc parameters to override the seaborn defaults, and :func:`set` now also takes a dictionary to update any of the matplotlib defaults. See the :ref:`tutorial ` for more information. + +- The ``nogrid`` style has been deprecated and changed to ``white`` for more uniformity (i.e. there are now ``darkgrid``, ``dark``, ``whitegrid``, and ``white`` styles). + + +Other changes +~~~~~~~~~~~~~ + +Using the package +^^^^^^^^^^^^^^^^^ + +- If you want to use plotting functions provided by the package without setting the matplotlib style to a seaborn theme, you can now do ``import seaborn.apionly as sns`` or ``from seaborn.apionly import lmplot``, etc. This is using the (also new) :func:`reset_orig` function, which returns the rc parameters to what they are at matplotlib import time — i.e. they will respect any custom `matplotlibrc` settings on top of the matplotlib defaults. + +- The dependency load of the package has been reduced. It can now be installed and used with only ``numpy``, ``scipy``, ``matplotlib``, and ``pandas``. Although ``statsmodels`` is still recommended for full functionality, it is not required. + +Plotting functions +^^^^^^^^^^^^^^^^^^ + +- :func:`lmplot` (and :func:`regplot`) have two new options for fitting regression models: ``lowess`` and ``robust``. The former fits a nonparametric smoother, while the latter fits a regression using methods that are less sensitive to outliers. + +- The regression uncertainty in :func:`lmplot` and :func:`regplot` is now estimated with fewer bootstrap iterations, so plotting should be faster. + +- The univariate :func:`kdeplot` can now be drawn as a *cumulative* density plot. + +- Changed :func:`interactplot` to use a robust calculation of the data range when finding default limits for the contour colormap to work better when there are outliers in the data. + +Style +^^^^^ + +- There is a new style, ``dark``, which shares most features with ``darkgrid`` but does not draw a grid by default. + +- There is a new function, :func:`offset_spines`, and a corresponding option in :func:`despine` called ``trim``. Together, these can be used to make plots where the axis spines are offset from the main part of the figure and limited within the range of the ticks. This is recommended for use with the ``ticks`` style. + +- Other aspects of the seaborn styles have been tweaked for more attractive plots. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..3875f70a636b312d9601de04e5805e14a2257d22 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.3.1.rst @@ -0,0 +1,23 @@ + +v0.3.1 (April 2014) +------------------- + +This is a minor release from 0.3 with fixes for several bugs. + +Plotting functions +~~~~~~~~~~~~~~~~~~ + +- The size of the points in :func:`pointplot` and ``factorplot`` are now scaled with the linewidth for better aesthetics across different plotting contexts. + +- The :func:`pointplot` glyphs for different levels of the hue variable are drawn at different z-orders so that they appear uniform. + +Bug Fixes +~~~~~~~~~ + +- Fixed a bug in :class:`FacetGrid` (and thus affecting lmplot and factorplot) that appeared when ``col_wrap`` was used with a number of facets that did not evenly divide into the column width. + +- Fixed an issue where the support for kernel density estimates was sometimes computed incorrectly. + +- Fixed a problem where ``hue`` variable levels that were not strings were missing in :class:`FacetGrid` legends. + +- When passing a color palette list in a ``with`` statement, the entire palette is now used instead of the first six colors. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.4.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.4.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..c75887fb792aba7e24f0e45d5a112a5bed311865 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.4.0.rst @@ -0,0 +1,45 @@ + +v0.4.0 (September 2014) +----------------------- + +This is a major release from 0.3. Highlights include new approaches for :ref:`quick, high-level dataset exploration ` (along with a more :ref:`flexible interface `) and easy creation of :ref:`perceptually-appropriate color palettes ` using the cubehelix system. Along with these additions, there are a number of smaller changes that make visualizing data with seaborn easier and more powerful. + +Plotting functions +~~~~~~~~~~~~~~~~~~ + +- A new object, :class:`PairGrid`, and a corresponding function :func:`pairplot`, for drawing grids of pairwise relationships in a dataset. This style of plot is sometimes called a "scatterplot matrix", but the representation of the data in :class:`PairGrid` is flexible and many styles other than scatterplots can be used. See the :ref:`docs ` for more information. **Note:** due to a bug in older versions of matplotlib, you will have best results if you use these functions with matplotlib 1.4 or later. + +- The rules for choosing default color palettes when variables are mapped to different colors have been unified (and thus changed in some cases). Now when no specific palette is requested, the current global color palette will be used, unless the number of variables to be mapped exceeds the number of unique colors in the palette, in which case the ``"husl"`` palette will be used to avoid cycling. + +- Added a keyword argument ``hist_norm`` to :func:`distplot`. When a :func:`distplot` is now drawn without a KDE or parametric density, the histogram is drawn as counts instead of a density. This can be overridden by by setting ``hist_norm`` to ``True``. + +- When using :class:`FacetGrid` with a ``hue`` variable, the legend is no longer drawn by default when you call :meth:`FacetGrid.map`. Instead, you have to call :meth:`FacetGrid.add_legend` manually. This should make it easier to layer multiple plots onto the grid without having duplicated legends. + +- Made some changes to ``factorplot`` so that it behaves better when not all levels of the ``x`` variable are represented in each facet. + +- Added the ``logx`` option to :func:`regplot` for fitting the regression in log space. + +- When :func:`violinplot` encounters a bin with only a single observation, it will now plot a horizontal line at that value instead of erroring out. + +Style and color palettes +~~~~~~~~~~~~~~~~~~~~~~~~ + +- Added the :func:`cubehelix_palette` function for generating sequential palettes from the cubehelix system. See the :ref:`palette docs ` for more information on how these palettes can be used. There is also the :func:`choose_cubehelix` which will launch an interactive app to select cubehelix parameters in the notebook. + +- Added the :func:`xkcd_palette` and the ``xkcd_rgb`` dictionary so that colors can be specified with names from the `xkcd color survey `_. + +- Added the ``font_scale`` option to :func:`plotting_context`, :func:`set_context`, and :func:`set`. ``font_scale`` can independently increase or decrease the size of the font elements in the plot. + +- Font-handling should work better on systems without Arial installed. This is accomplished by adding the ``font.sans-serif`` field to the ``axes_style`` definition with Arial and Liberation Sans prepended to matplotlib defaults. The font family can also be set through the ``font`` keyword argument in :func:`set`. Due to matplotlib bugs, this might not work as expected on matplotlib 1.3. + +- The :func:`despine` function gets a new keyword argument ``offset``, which replaces the deprecated :func:`offset_spines` function. You no longer need to offset the spines before plotting data. + +- Added a default value for ``pdf.fonttype`` so that text in PDFs is editable in Adobe Illustrator. + + +Other API Changes +~~~~~~~~~~~~~~~~~ + +- Removed the deprecated ``set_color_palette`` and ``palette_context`` functions. These were replaced in version 0.3 by the :func:`set_palette` function and ability to use :func:`color_palette` directly in a ``with`` statement. + +- Removed the ability to specify a ``nogrid`` style, which was renamed to ``white`` in 0.3. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..53af8c58a617b4a065ddb7281bb2a88c233f661b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.0.rst @@ -0,0 +1,45 @@ + +v0.5.0 (November 2014) +-------------------------- + +This is a major release from 0.4. Highlights include new functions for plotting heatmaps, possibly while applying clustering algorithms to discover structured relationships. These functions are complemented by new custom colormap functions and a full set of IPython widgets that allow interactive selection of colormap parameters. The palette tutorial has been rewritten to cover these new tools and more generally provide guidance on how to use color in visualizations. There are also a number of smaller changes and bugfixes. + +Plotting functions +~~~~~~~~~~~~~~~~~~ + +- Added the :func:`heatmap` function for visualizing a matrix of data by color-encoding the values. See the docs for more information. + +- Added the :func:`clustermap` function for clustering and visualizing a matrix of data, with options to label individual rows and columns by colors. See the docs for more information. This work was lead by Olga Botvinnik. + +- :func:`lmplot` and :func:`pairplot` get a new keyword argument, ``markers``. This can be a single kind of marker or a list of different markers for each level of the ``hue`` variable. Using different markers for different hues should let plots be more comprehensible when reproduced to black-and-white (i.e. when printed). See the `github pull request (#323) `_ for examples. + +- More generally, there is a new keyword argument in :class:`FacetGrid` and :class:`PairGrid`, ``hue_kws``. This similarly lets plot aesthetics vary across the levels of the hue variable, but more flexibly. ``hue_kws`` should be a dictionary that maps the name of keyword arguments to lists of values that are as long as the number of levels of the hue variable. + +- The argument ``subplot_kws`` has been added to ``FacetGrid``. This allows for faceted plots with custom projections, including `maps with Cartopy `_. + +Color palettes +~~~~~~~~~~~~~~ + +- Added two new functions to create custom color palettes. For sequential palettes, you can use the :func:`light_palette` function, which takes a seed color and creates a ramp from a very light, desaturated variant of it. For diverging palettes, you can use the :func:`diverging_palette` function to create a balanced ramp between two endpoints to a light or dark midpoint. See the :ref:`palette tutorial ` for more information. + +- Added the ability to specify the seed color for :func:`light_palette` and :func:`dark_palette` as a tuple of ``husl`` or ``hls`` space values or as a named ``xkcd`` color. The interpretation of the seed color is now provided by the new ``input`` parameter to these functions. + +- Added several new interactive palette widgets: :func:`choose_colorbrewer_palette`, :func:`choose_light_palette`, :func:`choose_dark_palette`, and :func:`choose_diverging_palette`. For consistency, renamed the cubehelix widget to :func:`choose_cubehelix_palette` (and fixed a bug where the cubehelix palette was reversed). These functions also now return either a color palette list or a matplotlib colormap when called, and that object will be live-updated as you play with the widget. This should make it easy to iterate over a plot until you find a good representation for the data. See the `Github pull request `_ or `this notebook (download it to use the widgets) `_ for more information. + +- Overhauled the color :ref:`palette tutorial ` to organize the discussion by class of color palette and provide more motivation behind the various choices one might make when choosing colors for their data. + +Bug fixes +~~~~~~~~~ +- Fixed a bug in :class:`PairGrid` that gave incorrect results (or a crash) when the input DataFrame has a non-default index. + +- Fixed a bug in :class:`PairGrid` where passing columns with a date-like datatype raised an exception. + +- Fixed a bug where :func:`lmplot` would show a legend when the hue variable was also used on either the rows or columns (making the legend redundant). + +- Worked around a matplotlib bug that was forcing outliers in :func:`boxplot` to appear as blue. + +- :func:`kdeplot` now accepts pandas Series for the ``data`` and ``data2`` arguments. + +- Using a non-default correlation method in :func:`corrplot` now implies ``sig_stars=False`` as the permutation test used to significance values for the correlations uses a pearson metric. + +- Removed ``pdf.fonttype`` from the style definitions, as the value used in version 0.4 resulted in very large PDF files. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3b581fd580db537f7399457fa1acbd0e2beae8b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.5.1.rst @@ -0,0 +1,11 @@ + +v0.5.1 (November 2014) +---------------------- + +This is a bugfix release that includes a workaround for an issue in matplotlib 1.4.2 and fixes for two bugs in functions that were new in 0.5.0. + +- Implemented a workaround for a bug in matplotlib 1.4.2 that prevented point markers from being drawn when the seaborn styles had been set. See this `github issue `_ for more information. + +- Fixed a bug in :func:`heatmap` where the mask was vertically reversed relative to the data. + +- Fixed a bug in :func:`clustermap` when using nested lists of side colors. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.6.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.6.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..a8d0da6634c4583de4efae90268ceb2f5de5c4b9 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.6.0.rst @@ -0,0 +1,103 @@ + +v0.6.0 (June 2015) +------------------ + +This is a major release from 0.5. The main objective of this release was to unify the API for categorical plots, which means that there are some relatively large API changes in some of the older functions. See below for details of those changes, which may break code written for older versions of seaborn. There are also some new functions (:func:`stripplot`, and :func:`countplot`), numerous enhancements to existing functions, and bug fixes. + +Additionally, the documentation has been completely revamped and expanded for the 0.6 release. Now, the API docs page for each function has multiple examples with embedded plots showing how to use the various options. These pages should be considered the most comprehensive resource for examples, and the tutorial pages are now streamlined and oriented towards a higher-level overview of the various features. + +Changes and updates to categorical plots +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In version 0.6, the "categorical" plots have been unified with a common API. This new category of functions groups together plots that show the relationship between one numeric variable and one or two categorical variables. This includes plots that show distribution of the numeric variable in each bin (:func:`boxplot`, :func:`violinplot`, and :func:`stripplot`) and plots that apply a statistical estimation within each bin (:func:`pointplot`, :func:`barplot`, and :func:`countplot`). There is a new :ref:`tutorial chapter ` that introduces these functions. + +The categorical functions now each accept the same formats of input data and can be invoked in the same way. They can plot using long- or wide-form data, and can be drawn vertically or horizontally. When long-form data is used, the orientation of the plots is inferred from the types of the input data. Additionally, all functions natively take a ``hue`` variable to add a second layer of categorization. + +With the (in some cases new) API, these functions can all be drawn correctly by :class:`FacetGrid`. However, ``factorplot`` can also now create faceted versions of any of these kinds of plots, so in most cases it will be unnecessary to use :class:`FacetGrid` directly. By default, ``factorplot`` draws a point plot, but this is controlled by the ``kind`` parameter. + +Here are details on what has changed in the process of unifying these APIs: + +- Changes to :func:`boxplot` and :func:`violinplot` will probably be the most disruptive. Both functions maintain backwards-compatibility in terms of the kind of data they can accept, but the syntax has changed to be more similar to other seaborn functions. These functions are now invoked with ``x`` and/or ``y`` parameters that are either vectors of data or names of variables in a long-form DataFrame passed to the new ``data`` parameter. You can still pass wide-form DataFrames or arrays to ``data``, but it is no longer the first positional argument. See the `github pull request (#410) `_ for more information on these changes and the logic behind them. + +- As :func:`pointplot` and :func:`barplot` can now plot with the major categorical variable on the y axis, the ``x_order`` parameter has been renamed to ``order``. + +- Added a ``hue`` argument to :func:`boxplot` and :func:`violinplot`, which allows for nested grouping the plot elements by a third categorical variable. For :func:`violinplot`, this nesting can also be accomplished by splitting the violins when there are two levels of the ``hue`` variable (using ``split=True``). To make this functionality feasible, the ability to specify where the plots will be draw in data coordinates has been removed. These plots now are drawn at set positions, like (and identical to) :func:`barplot` and :func:`pointplot`. + +- Added a ``palette`` parameter to :func:`boxplot`/:func:`violinplot`. The ``color`` parameter still exists, but no longer does double-duty in accepting the name of a seaborn palette. ``palette`` supersedes ``color`` so that it can be used with a :class:`FacetGrid`. + +Along with these API changes, the following changes/enhancements were made to the plotting functions: + +- The default rules for ordering the categories has changed. Instead of automatically sorting the category levels, the plots now show the levels in the order they appear in the input data (i.e., the order given by ``Series.unique()``). Order can be specified when plotting with the ``order`` and ``hue_order`` parameters. Additionally, when variables are pandas objects with a "categorical" dtype, the category order is inferred from the data object. This change also affects :class:`FacetGrid` and :class:`PairGrid`. + +- Added the ``scale`` and ``scale_hue`` parameters to :func:`violinplot`. These control how the width of the violins are scaled. The default is ``area``, which is different from how the violins used to be drawn. Use ``scale='width'`` to get the old behavior. + +- Used a different style for the ``box`` kind of interior plot in :func:`violinplot`, which shows the whisker range in addition to the quartiles. Use ``inner='quartile'`` to get the old style. + +New plotting functions +~~~~~~~~~~~~~~~~~~~~~~ + +- Added the :func:`stripplot` function, which draws a scatterplot where one of the variables is categorical. This plot has the same API as :func:`boxplot` and :func:`violinplot`. It is useful both on its own and when composed with one of these other plot kinds to show both the observations and underlying distribution. + +- Added the :func:`countplot` function, which uses a bar plot representation to show counts of variables in one or more categorical bins. This replaces the old approach of calling :func:`barplot` without a numeric variable. + +Other additions and changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- The :func:`corrplot` and underlying :func:`symmatplot` functions have been deprecated in favor of :func:`heatmap`, which is much more flexible and robust. These two functions are still available in version 0.6, but they will be removed in a future version. + +- Added the :func:`set_color_codes` function and the ``color_codes`` argument to :func:`set` and :func:`set_palette`. This changes the interpretation of shorthand color codes (i.e. "b", "g", k", etc.) within matplotlib to use the values from one of the named seaborn palettes (i.e. "deep", "muted", etc.). That makes it easier to have a more uniform look when using matplotlib functions directly with seaborn imported. This could be disruptive to existing plots, so it does not happen by default. It is possible this could change in the future. + +- The :func:`color_palette` function no longer trims palettes that are longer than 6 colors when passed into it. + +- Added the ``as_hex`` method to color palette objects, to return a list of hex codes rather than rgb tuples. + +- :func:`jointplot` now passes additional keyword arguments to the function used to draw the plot on the joint axes. + +- Changed the default ``linewidths`` in :func:`heatmap` and :func:`clustermap` to 0 so that larger matrices plot correctly. This parameter still exists and can be used to get the old effect of lines demarcating each cell in the heatmap (the old default ``linewidths`` was 0.5). + +- :func:`heatmap` and :func:`clustermap` now automatically use a mask for missing values, which previously were shown with the "under" value of the colormap per default `plt.pcolormesh` behavior. + +- Added the ``seaborn.crayons`` dictionary and the :func:`crayon_palette` function to define colors from the 120 box (!) of `Crayola crayons `_. + +- Added the ``line_kws`` parameter to :func:`residplot` to change the style of the lowess line, when used. + +- Added open-ended ``**kwargs`` to the ``add_legend`` method on :class:`FacetGrid` and :class:`PairGrid`, which will pass additional keyword arguments through when calling the legend function on the ``Figure`` or ``Axes``. + +- Added the ``gridspec_kws`` parameter to :class:`FacetGrid`, which allows for control over the size of individual facets in the grid to emphasize certain plots or account for differences in variable ranges. + +- The interactive palette widgets now show a continuous colorbar, rather than a discrete palette, when `as_cmap` is True. + +- The default Axes size for :func:`pairplot` and :class:`PairGrid` is now slightly smaller. + +- Added the ``shade_lowest`` parameter to :func:`kdeplot` which will set the alpha for the lowest contour level to 0, making it easier to plot multiple bivariate distributions on the same axes. + +- The ``height`` parameter of :func:`rugplot` is now interpreted as a function of the axis size and is invariant to changes in the data scale on that axis. The rug lines are also slightly narrower by default. + +- Added a catch in :func:`distplot` when calculating a default number of bins. For highly skewed data it will now use sqrt(n) bins, where previously the reference rule would return "infinite" bins and cause an exception in matplotlib. + +- Added a ceiling (50) to the default number of bins used for :func:`distplot` histograms. This will help avoid confusing errors with certain kinds of datasets that heavily violate the assumptions of the reference rule used to get a default number of bins. The ceiling is not applied when passing a specific number of bins. + +- The various property dictionaries that can be passed to ``plt.boxplot`` are now applied after the seaborn restyling to allow for full customizability. + +- Added a ``savefig`` method to :class:`JointGrid` that defaults to a tight bounding box to make it easier to save figures using this class, and set a tight bbox as the default for the ``savefig`` method on other Grid objects. + +- You can now pass an integer to the ``xticklabels`` and ``yticklabels`` parameter of :func:`heatmap` (and, by extension, :func:`clustermap`). This will make the plot use the ticklabels inferred from the data, but only plot every ``n`` label, where ``n`` is the number you pass. This can help when visualizing larger matrices with some sensible ordering to the rows or columns of the dataframe. + +- Added `"figure.facecolor"` to the style parameters and set the default to white. + +- The :func:`load_dataset` function now caches datasets locally after downloading them, and uses the local copy on subsequent calls. + +Bug fixes +~~~~~~~~~ + +- Fixed bugs in :func:`clustermap` where the mask and specified ticklabels were not being reorganized using the dendrograms. + +- Fixed a bug in :class:`FacetGrid` and :class:`PairGrid` that lead to incorrect legend labels when levels of the ``hue`` variable appeared in ``hue_order`` but not in the data. + +- Fixed a bug in :meth:`FacetGrid.set_xticklabels` or :meth:`FacetGrid.set_yticklabels` when ``col_wrap`` is being used. + +- Fixed a bug in :class:`PairGrid` where the ``hue_order`` parameter was ignored. + +- Fixed two bugs in :func:`despine` that caused errors when trying to trim the spines on plots that had inverted axes or no ticks. + +- Improved support for the ``margin_titles`` option in :class:`FacetGrid`, which can now be used with a legend. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..6013e4ea53952c12225461a01a24a5efa176050d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.0.rst @@ -0,0 +1,39 @@ + +v0.7.0 (January 2016) +--------------------- + +This is a major release from 0.6. The main new feature is :func:`swarmplot` which implements the beeswarm approach for drawing categorical scatterplots. There are also some performance improvements, bug fixes, and updates for compatibility with new versions of dependencies. + +- Added the :func:`swarmplot` function, which draws beeswarm plots. These are categorical scatterplots, similar to those produced by :func:`stripplot`, but position of the points on the categorical axis is chosen to avoid overlapping points. See the :ref:`categorical plot tutorial ` for more information. + +- Changed some of the :func:`stripplot` defaults to be closer to :func:`swarmplot`. Points are now somewhat smaller, have no outlines, and are not split by default when using ``hue``. These settings remain customizable through function parameters. + +- Added an additional rule when determining category order in categorical plots. Now, when numeric variables are used in a categorical role, the default behavior is to sort the unique levels of the variable (i.e they will be in proper numerical order). This can still be overridden by the appropriate ``{*_}order`` parameter, and variables with a ``category`` datatype will still follow the category order even if the levels are strictly numerical. + +- Changed how :func:`stripplot` draws points when using ``hue`` nesting with ``split=False`` so that the different ``hue`` levels are not drawn strictly on top of each other. + +- Improve performance for large dendrograms in :func:`clustermap`. + +- Added ``font.size`` to the plotting context definition so that the default output from ``plt.text`` will be scaled appropriately. + +- Fixed a bug in :func:`clustermap` when ``fastcluster`` is not installed. + +- Fixed a bug in the zscore calculation in :func:`clustermap`. + +- Fixed a bug in :func:`distplot` where sometimes the default number of bins would not be an integer. + +- Fixed a bug in :func:`stripplot` where a legend item would not appear for a ``hue`` level if there were no observations in the first group of points. + +- Heatmap colorbars are now rasterized for better performance in vector plots. + +- Added workarounds for some matplotlib boxplot issues, such as strange colors of outlier points. + +- Added workarounds for an issue where violinplot edges would be missing or have random colors. + +- Added a workaround for an issue where only one :func:`heatmap` cell would be annotated on some matplotlib backends. + +- Fixed a bug on newer versions of matplotlib where a colormap would be erroneously applied to scatterplots with only three observations. + +- Updated seaborn for compatibility with matplotlib 1.5. + +- Added compatibility for various IPython (and Jupyter) versions in functions that use widgets. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..809358e05b0a5add1e7bdb73289385489d1dfe15 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.7.1.rst @@ -0,0 +1,25 @@ + +v0.7.1 (June 2016) +------------------- + +- Added the ability to put "caps" on the error bars that are drawn by :func:`barplot` or :func:`pointplot` (and, by extension, ``factorplot``). Additionally, the line width of the error bars can now be controlled. These changes involve the new parameters ``capsize`` and ``errwidth``. See the `github pull request (#898) `_ for examples of usage. + +- Improved the row and column colors display in :func:`clustermap`. It is now possible to pass Pandas objects for these elements and, when possible, the semantic information in the Pandas objects will be used to add labels to the plot. When Pandas objects are used, the color data is matched against the main heatmap based on the index, not on position. This is more accurate, but it may lead to different results if current code assumed positional matching. + +- Improved the luminance calculation that determines the annotation color in :func:`heatmap`. + +- The ``annot`` parameter of :func:`heatmap` now accepts a rectangular dataset in addition to a boolean value. If a dataset is passed, its values will be used for the annotations, while the main dataset will be used for the heatmap cell colors. + +- Fixed a bug in :class:`FacetGrid` that appeared when using ``col_wrap`` with missing ``col`` levels. + +- Made it possible to pass a tick locator object to the :func:`heatmap` colorbar. + +- Made it possible to use different styles (e.g., step) for :class:`PairGrid` histograms when there are multiple hue levels. + +- Fixed a bug in scipy-based univariate kernel density bandwidth calculation. + +- The :func:`reset_orig` function (and, by extension, importing ``seaborn.apionly``) resets matplotlib rcParams to their values at the time seaborn itself was imported, which should work better with rcParams changed by the jupyter notebook backend. + +- Removed some objects from the top-level ``seaborn`` namespace. + +- Improved unicode compatibility in :class:`FacetGrid`. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..4de9bef67dc1004eb3a7c1a0cb82969179fa796d --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.0.rst @@ -0,0 +1,41 @@ + +v0.8.0 (July 2017) +------------------ + +- The default style is no longer applied when seaborn is imported. It is now necessary to explicitly call :func:`set` or one or more of :func:`set_style`, :func:`set_context`, and :func:`set_palette`. Correspondingly, the ``seaborn.apionly`` module has been deprecated. + +- Changed the behavior of :func:`heatmap` (and by extension :func:`clustermap`) when plotting divergent dataesets (i.e. when the ``center`` parameter is used). Instead of extending the lower and upper limits of the colormap to be symmetrical around the ``center`` value, the colormap is modified so that its middle color corresponds to ``center``. This means that the full range of the colormap will not be used (unless the data or specified ``vmin`` and ``vmax`` are symmetric), but the upper and lower limits of the colorbar will correspond to the range of the data. See the Github pull request `(#1184) `_ for examples of the behavior. + +- Removed automatic detection of diverging data in :func:`heatmap` (and by extension :func:`clustermap`). If you want the colormap to be treated as diverging (see above), it is now necessary to specify the ``center`` value. When no colormap is specified, specifying ``center`` will still change the default to be one that is more appropriate for displaying diverging data. + +- Added four new colormaps, created using `viscm `_ for perceptual uniformity. The new colormaps include two sequential colormaps ("rocket" and "mako") and two diverging colormaps ("icefire" and "vlag"). These colormaps are registered with matplotlib on seaborn import and the colormap objects can be accessed in the ``seaborn.cm`` namespace. + +- Changed the default :func:`heatmap` colormaps to be "rocket" (in the case of sequential data) or "icefire" (in the case of diverging data). Note that this change reverses the direction of the luminance ramp from the previous defaults. While potentially confusing and disruptive, this change better aligns the seaborn defaults with the new matplotlib default colormap ("viridis") and arguably better aligns the semantics of a "heat" map with the appearance of the colormap. + +- Added ``"auto"`` as a (default) option for tick labels in :func:`heatmap` and :func:`clustermap`. This will try to estimate how many ticks can be labeled without the text objects overlapping, which should improve performance for larger matrices. + +- Added the ``dodge`` parameter to :func:`boxplot`, :func:`violinplot`, and :func:`barplot` to allow use of ``hue`` without changing the position or width of the plot elements, as when the ``hue`` variable is not nested within the main categorical variable. + +- Correspondingly, the ``split`` parameter for :func:`stripplot` and :func:`swarmplot` has been renamed to ``dodge`` for consistency with the other categorical functions (and for differentiation from the meaning of ``split`` in :func:`violinplot`). + +- Added the ability to draw a colorbar for a bivariate :func:`kdeplot` with the ``cbar`` parameter (and related ``cbar_ax`` and ``cbar_kws`` parameters). + +- Added the ability to use error bars to show standard deviations rather than bootstrap confidence intervals in most statistical functions by putting ``ci="sd"``. + +- Allow side-specific offsets in :func:`despine`. + +- Figure size is no longer part of the seaborn plotting context parameters. + +- Put a cap on the number of bins used in :func:`jointplot` for ``type=="hex"`` to avoid hanging when the reference rule prescribes too many. + +- Changed the y axis in :func:`heatmap`. Instead of reversing the rows of the data internally, the y axis is now inverted. This may affect code that draws on top of the heatmap in data coordinates. + +- Turn off dendrogram axes in :func:`clustermap` rather than setting the background color to white. + +- New matplotlib qualitative palettes (e.g. "tab10") are now handled correctly. + +- Some modules and functions have been internally reorganized; there should be no effect on code that uses the ``seaborn`` namespace. + +- Added a deprecation warning to ``tsplot`` function to indicate that it will be removed or replaced with a substantially altered version in a future release. + +- The ``interactplot`` and ``coefplot`` functions are officially deprecated and will be removed in a future release. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..5c8a1b75ce8ac5f579499ebd3440306d071a7f72 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.8.1.rst @@ -0,0 +1,25 @@ + +v0.8.1 (September 2017) +----------------------- + +- Added a warning in :class:`FacetGrid` when passing a categorical plot function without specifying ``order`` (or ``hue_order`` when ``hue`` is used), which is likely to produce a plot that is incorrect. + +- Improved compatibility between :class:`FacetGrid` or :class:`PairGrid` and interactive matplotlib backends so that the legend no longer remains inside the figure when using ``legend_out=True``. + +- Changed categorical plot functions with small plot elements to use :func:`dark_palette` instead of :func:`light_palette` when generating a sequential palette from a specified color. + +- Improved robustness of :func:`kdeplot` and :func:`distplot` to data with fewer than two observations. + +- Fixed a bug in :func:`clustermap` when using ``yticklabels=False``. + +- Fixed a bug in :func:`pointplot` where colors were wrong if exactly three points were being drawn. + +- Fixed a bug in :func:`pointplot` where legend entries for missing data appeared with empty markers. + +- Fixed a bug in :func:`clustermap` where an error was raised when annotating the main heatmap and showing category colors. + +- Fixed a bug in :func:`clustermap` where row labels were not being properly rotated when they overlapped. + +- Fixed a bug in :func:`kdeplot` where the maximum limit on the density axes was not being updated when multiple densities were drawn. + +- Improved compatibility with future versions of pandas. diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.0.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.0.rst new file mode 100644 index 0000000000000000000000000000000000000000..83084859b9ed2ea6ed10da1b790eedd1be713186 --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.0.rst @@ -0,0 +1,88 @@ + +v0.9.0 (July 2018) +------------------ + +This is a major release with several substantial and long-desired new features. There are also updates/modifications to the themes and color palettes that give better consistency with matplotlib 2.0 and some notable API changes. + +New relational plots +~~~~~~~~~~~~~~~~~~~~ + +Three completely new plotting functions have been added: :func:`relplot`, :func:`scatterplot`, and :func:`lineplot`. The first is a figure-level interface to the latter two that combines them with a :class:`FacetGrid`. The functions bring the high-level, dataset-oriented API of the seaborn categorical plotting functions to more general plots (scatter plots and line plots). + +These functions can visualize a relationship between two numeric variables while mapping up to three additional variables by modifying ``hue``, ``size``, and/or ``style`` semantics. The common high-level API is implemented differently in the two functions. For example, the size semantic in :func:`scatterplot` scales the area of scatter plot points, but in :func:`lineplot` it scales width of the line plot lines. The API is dataset-oriented, meaning that in both cases you pass the variable in your dataset rather than directly specifying the matplotlib parameters to use for point area or line width. + +Another way the relational functions differ from existing seaborn functionality is that they have better support for using numeric variables for ``hue`` and ``size`` semantics. This functionality may be propagated to other functions that can add a ``hue`` semantic in future versions; it has not been in this release. + +The :func:`lineplot` function also has support for statistical estimation and is replacing the older ``tsplot`` function, which still exists but is marked for removal in a future release. :func:`lineplot` is better aligned with the API of the rest of the library and more flexible in showing relationships across additional variables by modifying the size and style semantics independently. It also has substantially improved support for date and time data, a major pain factor in ``tsplot``. The cost is that some of the more esoteric options in ``tsplot`` for representing uncertainty (e.g. a colormapped KDE of the bootstrap distribution) have not been implemented in the new function. + +There is quite a bit of new documentation that explains these new functions in more detail, including detailed examples of the various options in the :ref:`API reference ` and a more verbose :ref:`tutorial `. + +These functions should be considered in a "stable beta" state. They have been thoroughly tested, but some unknown corner cases may remain to be found. The main features are in place, but not all planned functionality has been implemented. There are planned improvements to some elements, particularly the default legend, that are a little rough around the edges in this release. Finally, some of the default behavior (e.g. the default range of point/line sizes) may change somewhat in future releases. + +Updates to themes and palettes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Several changes have been made to the seaborn style themes, context scaling, and color palettes. In general the aim of these changes was to make the seaborn styles more consistent with the `style updates in matplotlib 2.0 `_ and to leverage some of the new style parameters for better implementation of some aspects of the seaborn styles. Here is a list of the changes: + +- Reorganized and updated some :func:`axes_style`/:func:`plotting_context` parameters to take advantage of improvements in the matplotlib 2.0 update. The biggest change involves using several new parameters in the "style" spec while moving parameters that used to implement the corresponding aesthetics to the "context" spec. For example, axes spines and ticks are now off instead of having their width/length zeroed out for the darkgrid style. That means the width/length of these elements can now be scaled in different contexts. The effect is a more cohesive appearance of the plots, especially in larger contexts. These changes include only minimal support for the 1.x matplotlib series. Users who are stuck on matplotlib 1.5 but wish to use seaborn styling may want to use the seaborn parameters that can be accessed through the `matplotlib stylesheet interface `_. + +- Updated the seaborn palettes ("deep", "muted", "colorblind", etc.) to correspond with the new 10-color matplotlib default. The legacy palettes are now available at "deep6", "muted6", "colorblind6", etc. Additionally, a few individual colors were tweaked for better consistency, aesthetics, and accessibility. + +- Calling :func:`color_palette` (or :func:`set_palette`) with a named qualitative palettes (i.e. one of the seaborn palettes, the colorbrewer qualitative palettes, or the matplotlib matplotlib tableau-derived palettes) and no specified number of colors will return all of the colors in the palette. This means that for some palettes, the returned list will have a different length than it did in previous versions. + +- Enhanced :func:`color_palette` to accept a parameterized specification of a cubehelix palette in in a string, prefixed with ``"ch:"`` (e.g. ``"ch:-.1,.2,l=.7"``). Note that keyword arguments can be spelled out or referenced using only their first letter. Reversing the palette is accomplished by appending ``"_r"``, as with other matplotlib colormaps. This specification will be accepted by any seaborn function with a ``palette=`` parameter. + +- Slightly increased the base font sizes in :func:`plotting_context` and increased the scaling factors for ``"talk"`` and ``"poster"`` contexts. + +- Calling :func:`set` will now call :func:`set_color_codes` to re-assign the single letter color codes by default + +API changes +~~~~~~~~~~~ + +A few functions have been renamed or have had changes to their default parameters. + +- The ``factorplot`` function has been renamed to :func:`catplot`. The new name ditches the original R-inflected terminology to use a name that is more consistent with terminology in pandas and in seaborn itself. This change should hopefully make :func:`catplot` easier to discover, and it should make more clear what its role is. ``factorplot`` still exists and will pass its arguments through to :func:`catplot` with a warning. It may be removed eventually, but the transition will be as gradual as possible. + +- The other reason that the ``factorplot`` name was changed was to ease another alteration which is that the default ``kind`` in :func:`catplot` is now ``"strip"`` (corresponding to :func:`stripplot`). This plots a categorical scatter plot which is usually a much better place to start and is more consistent with the default in :func:`relplot`. The old default style in ``factorplot`` (``"point"``, corresponding to :func:`pointplot`) remains available if you want to show a statistical estimation. + +- The ``lvplot`` function has been renamed to :func:`boxenplot`. The "letter-value" terminology that was used to name the original kind of plot is obscure, and the abbreviation to ``lv`` did not help anything. The new name should make the plot more discoverable by describing its format (it plots multiple boxes, also known as "boxen"). As with ``factorplot``, the ``lvplot`` function still exists to provide a relatively smooth transition. + +- Renamed the ``size`` parameter to ``height`` in multi-plot grid objects (:class:`FacetGrid`, :class:`PairGrid`, and :class:`JointGrid`) along with functions that use them (``factorplot``, :func:`lmplot`, :func:`pairplot`, and :func:`jointplot`) to avoid conflicts with the ``size`` parameter that is used in ``scatterplot`` and ``lineplot`` (necessary to make :func:`relplot` work) and also makes the meaning of the parameter a bit more clear. + +- Changed the default diagonal plots in :func:`pairplot` to use func:`kdeplot` when a ``"hue"`` dimension is used. + +- Deprecated the statistical annotation component of :class:`JointGrid`. The method is still available but will be removed in a future version. + +- Two older functions that were deprecated in earlier versions, ``coefplot`` and ``interactplot``, have undergone final removal from the code base. + +Documentation improvements +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There has been some effort put into improving the documentation. The biggest change is that the :ref:`introduction to the library ` has been completely rewritten to provide much more information and, critically, examples. In addition to the high-level motivation, the introduction also covers some important topics that are often sources of confusion, like the distinction between figure-level and axes-level functions, how datasets should be formatted for use in seaborn, and how to customize the appearance of the plots. + +Other improvements have been made throughout, most notably a thorough re-write of the :ref:`categorical tutorial `. + +Other small enhancements and bug fixes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Changed :func:`rugplot` to plot a matplotlib ``LineCollection`` instead of many ``Line2D`` objects, providing a big speedup for large arrays. + +- Changed the default off-diagonal plots to use :func:`scatterplot`. (Note that the ``"hue"`` currently draws three separate scatterplots instead of using the hue semantic of the scatterplot function). + +- Changed color handling when using :func:`kdeplot` with two variables. The default colormap for the 2D density now follows the color cycle, and the function can use ``color`` and ``label`` kwargs, adding more flexibility and avoiding a warning when using with multi-plot grids. + +- Added the ``subplot_kws`` parameter to :class:`PairGrid` for more flexibility. + +- Removed a special case in :class:`PairGrid` that defaulted to drawing stacked histograms on the diagonal axes. + +- Fixed :func:`jointplot`/:class:`JointGrid` and :func:`regplot` so that they now accept list inputs. + +- Fixed a bug in :class:`FacetGrid` when using a single row/column level or using ``col_wrap=1``. + +- Fixed functions that set axis limits so that they preserve auto-scaling state on matplotlib 2.0. + +- Avoided an error when using matplotlib backends that cannot render a canvas (e.g. PDF). + +- Changed the install infrastructure to explicitly declare dependencies in a way that ``pip`` is aware of. This means that ``pip install seaborn`` will now work in an empty environment. Additionally, the dependencies are specified with strict minimal versions. + +- Updated the testing infrastructure to execute tests with `pytest `_ (although many individual tests still use nose assertion). diff --git a/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.1.rst b/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.1.rst new file mode 100644 index 0000000000000000000000000000000000000000..24efff3de84d7a53434f90108b58d6a6b8b4a28b --- /dev/null +++ b/testbed/mwaskom__seaborn/doc/whatsnew/v0.9.1.rst @@ -0,0 +1,81 @@ + +v0.9.1 (January 2020) +--------------------- + +This is a minor release with a number of bug fixes and adaptations to changes in seaborn's dependencies. There are also several new features. + +This is the final version of seaborn that will support Python 2.7 or 3.5. + +New features +~~~~~~~~~~~~ + +- Added more control over the arrangement of the elements drawn by :func:`clustermap` with the ``{dendrogram,colors}_ratio`` and ``cbar_pos`` parameters. Additionally, the default organization and scaling with different figure sizes has been improved. + +- Added the ``corner`` option to :class:`PairGrid` and :func:`pairplot` to make a grid without the upper triangle of bivariate axes. + +- Added the ability to seed the random number generator for the bootstrap used to define error bars in several plots. Relevant functions now have a ``seed`` parameter, which can take either fixed seed (typically an ``int``) or a numpy random number generator object (either the newer :class:`numpy.random.Generator` or the older :class:`numpy.random.mtrand.RandomState`). + +- Generalized the idea of "diagonal" axes in :class:`PairGrid` to any axes that share an x and y variable. + +- In :class:`PairGrid`, the ``hue`` variable is now excluded from the default list of variables that make up the rows and columns of the grid. + +- Exposed the ``layout_pad`` parameter in :class:`PairGrid` and set a smaller default than what matptlotlib sets for more efficient use of space in dense grids. + +- It is now possible to force a categorical interpretation of the ``hue`` variable in a relational plot by passing the name of a categorical palette (e.g. ``"deep"``, or ``"Set2"``). This complements the (previously supported) option of passing a list/dict of colors. + +- Added the ``tree_kws`` parameter to :func:`clustermap` to control the properties of the lines in the dendrogram. + +- Added the ability to pass hierarchical label names to the :class:`FacetGrid` legend, which also fixes a bug in :func:`relplot` when the same label appeared in different semantics. + +- Improved support for grouping observations based on pandas index information in categorical plots. + +Bug fixes and adaptations +~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Avoided an error when singular data is passed to :func:`kdeplot`, issuing a warning instead. This makes :func:`pairplot` more robust. + +- Fixed the behavior of ``dropna`` in :class:`PairGrid` to properly exclude null datapoints from each plot when set to ``True``. + +- Fixed an issue where :func:`regplot` could interfere with other axes in a multi-plot matplotlib figure. + +- Semantic variables with a ``category`` data type will always be treated as categorical in relational plots. + +- Avoided a warning about color specifications that arose from :func:`boxenplot` on newer matplotlibs. + +- Adapted to a change in how matplotlib scales axis margins, which caused multiple calls to :func:`regplot` with ``truncate=False`` to progressively expand the x axis limits. Because there are currently limitations on how autoscaling works in matplotlib, the default value for ``truncate`` in seaborn has also been changed to ``True``. + +- Relational plots no longer error when hue/size data are inferred to be numeric but stored with a string datatype. + +- Relational plots now consider semantics with only a single value that can be interpreted as boolean (0 or 1) to be categorical, not numeric. + +- Relational plots now handle list or dict specifications for ``sizes`` correctly. + +- Fixed an issue in :func:`pointplot` where missing levels of a hue variable would cause an exception after a recent update in matplotlib. + +- Fixed a bug when setting the rotation of x tick labels on a :class:`FacetGrid`. + +- Fixed a bug where values would be excluded from categorical plots when only one variable was a pandas ``Series`` with a non-default index. + +- Fixed a bug when using ``Series`` objects as arguments for ``x_partial`` or ``y_partial`` in :func:`regplot`. + +- Fixed a bug when passing a ``norm`` object and using color annotations in :func:`clustermap`. + +- Fixed a bug where annotations were not rearranged to match the clustering in :func:`clustermap`. + +- Fixed a bug when trying to call :func:`set` while specifying a list of colors for the palette. + +- Fixed a bug when resetting the color code short-hands to the matplotlib default. + +- Avoided errors from stricter type checking in upcoming ``numpy`` changes. + +- Avoided error/warning in :func:`lineplot` when plotting categoricals with empty levels. + +- Allowed ``colors`` to be passed through to a bivariate :func:`kdeplot`. + +- Standardized the output format of custom color palette functions. + +- Fixed a bug where legends for numerical variables in a relational plot could show a surprisingly large number of decimal places. + +- Improved robustness to missing values in distribution plots. + +- Made it possible to specify the location of the :class:`FacetGrid` legend using matplotlib keyword arguments. diff --git a/testbed/mwaskom__seaborn/examples/.gitignore b/testbed/mwaskom__seaborn/examples/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0a60a0663a72dec8d807aa17a78c0439058429a9 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/.gitignore @@ -0,0 +1,2 @@ +*.html +*_files/ diff --git a/testbed/mwaskom__seaborn/examples/anscombes_quartet.py b/testbed/mwaskom__seaborn/examples/anscombes_quartet.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2e3a2e46d0cbb19023d24fe27faee2b41774d1 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/anscombes_quartet.py @@ -0,0 +1,18 @@ +""" +Anscombe's quartet +================== + +_thumb: .4, .4 +""" +import seaborn as sns +sns.set_theme(style="ticks") + +# Load the example dataset for Anscombe's quartet +df = sns.load_dataset("anscombe") + +# Show the results of a linear regression within each dataset +sns.lmplot( + data=df, x="x", y="y", col="dataset", hue="dataset", + col_wrap=2, palette="muted", ci=None, + height=4, scatter_kws={"s": 50, "alpha": 1} +) diff --git a/testbed/mwaskom__seaborn/examples/different_scatter_variables.py b/testbed/mwaskom__seaborn/examples/different_scatter_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..710d00580836927a99045647981a85f5f89a2210 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/different_scatter_variables.py @@ -0,0 +1,25 @@ +""" +Scatterplot with multiple semantics +=================================== + +_thumb: .45, .5 + +""" +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="whitegrid") + +# Load the example diamonds dataset +diamonds = sns.load_dataset("diamonds") + +# Draw a scatter plot while assigning point colors and sizes to different +# variables in the dataset +f, ax = plt.subplots(figsize=(6.5, 6.5)) +sns.despine(f, left=True, bottom=True) +clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"] +sns.scatterplot(x="carat", y="price", + hue="clarity", size="depth", + palette="ch:r=-.2,d=.3_r", + hue_order=clarity_ranking, + sizes=(1, 8), linewidth=0, + data=diamonds, ax=ax) diff --git a/testbed/mwaskom__seaborn/examples/errorband_lineplots.py b/testbed/mwaskom__seaborn/examples/errorband_lineplots.py new file mode 100644 index 0000000000000000000000000000000000000000..13a8ab3f852f3dc3bfdcc5be7f9aa7bf9d19e6a4 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/errorband_lineplots.py @@ -0,0 +1,17 @@ +""" +Timeseries plot with error bands +================================ + +_thumb: .48, .45 + +""" +import seaborn as sns +sns.set_theme(style="darkgrid") + +# Load an example dataset with long-form data +fmri = sns.load_dataset("fmri") + +# Plot the responses for different events and regions +sns.lineplot(x="timepoint", y="signal", + hue="region", style="event", + data=fmri) diff --git a/testbed/mwaskom__seaborn/examples/faceted_histogram.py b/testbed/mwaskom__seaborn/examples/faceted_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..1c84b4ba10f9b9e9e1c07f29f32f92daf05915fe --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/faceted_histogram.py @@ -0,0 +1,14 @@ +""" +Facetting histograms by subsets of data +======================================= + +_thumb: .33, .57 +""" +import seaborn as sns + +sns.set_theme(style="darkgrid") +df = sns.load_dataset("penguins") +sns.displot( + df, x="flipper_length_mm", col="species", row="sex", + binwidth=3, height=3, facet_kws=dict(margin_titles=True), +) diff --git a/testbed/mwaskom__seaborn/examples/faceted_lineplot.py b/testbed/mwaskom__seaborn/examples/faceted_lineplot.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb4cd61f2e6f2a2803d05ba1a04f52b5a51d95e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/faceted_lineplot.py @@ -0,0 +1,23 @@ +""" +Line plots on multiple facets +============================= + +_thumb: .48, .42 + +""" +import seaborn as sns +sns.set_theme(style="ticks") + +dots = sns.load_dataset("dots") + +# Define the palette as a list to specify exact values +palette = sns.color_palette("rocket_r") + +# Plot the lines on two facets +sns.relplot( + data=dots, + x="time", y="firing_rate", + hue="coherence", size="choice", col="align", + kind="line", size_order=["T1", "T2"], palette=palette, + height=5, aspect=.75, facet_kws=dict(sharex=False), +) diff --git a/testbed/mwaskom__seaborn/examples/grouped_barplot.py b/testbed/mwaskom__seaborn/examples/grouped_barplot.py new file mode 100644 index 0000000000000000000000000000000000000000..23a217228ff4876695fed920f3b8e7e1feda620e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/grouped_barplot.py @@ -0,0 +1,20 @@ +""" +Grouped barplots +================ + +_thumb: .36, .5 +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +penguins = sns.load_dataset("penguins") + +# Draw a nested barplot by species and sex +g = sns.catplot( + data=penguins, kind="bar", + x="species", y="body_mass_g", hue="sex", + errorbar="sd", palette="dark", alpha=.6, height=6 +) +g.despine(left=True) +g.set_axis_labels("", "Body mass (g)") +g.legend.set_title("") diff --git a/testbed/mwaskom__seaborn/examples/grouped_boxplot.py b/testbed/mwaskom__seaborn/examples/grouped_boxplot.py new file mode 100644 index 0000000000000000000000000000000000000000..d10a9bbd8409b20dec09b7233da5d8d59161ed29 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/grouped_boxplot.py @@ -0,0 +1,18 @@ +""" +Grouped boxplots +================ + +_thumb: .66, .45 + +""" +import seaborn as sns +sns.set_theme(style="ticks", palette="pastel") + +# Load the example tips dataset +tips = sns.load_dataset("tips") + +# Draw a nested boxplot to show bills by day and time +sns.boxplot(x="day", y="total_bill", + hue="smoker", palette=["m", "g"], + data=tips) +sns.despine(offset=10, trim=True) diff --git a/testbed/mwaskom__seaborn/examples/grouped_violinplots.py b/testbed/mwaskom__seaborn/examples/grouped_violinplots.py new file mode 100644 index 0000000000000000000000000000000000000000..788885863cf9cf56e24d025008c37eeaf07c032d --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/grouped_violinplots.py @@ -0,0 +1,17 @@ +""" +Grouped violinplots with split violins +====================================== + +_thumb: .44, .47 +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the example tips dataset +tips = sns.load_dataset("tips") + +# Draw a nested violinplot and split the violins for easier comparison +sns.violinplot(data=tips, x="day", y="total_bill", hue="smoker", + split=True, inner="quart", linewidth=1, + palette={"Yes": "b", "No": ".85"}) +sns.despine(left=True) diff --git a/testbed/mwaskom__seaborn/examples/heat_scatter.py b/testbed/mwaskom__seaborn/examples/heat_scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..228e91c402e6f72c55d25a1691856478655e5bf6 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/heat_scatter.py @@ -0,0 +1,41 @@ +""" +Scatterplot heatmap +------------------- + +_thumb: .5, .5 + +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the brain networks dataset, select subset, and collapse the multi-index +df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) + +used_networks = [1, 5, 6, 7, 8, 12, 13, 17] +used_columns = (df.columns + .get_level_values("network") + .astype(int) + .isin(used_networks)) +df = df.loc[:, used_columns] + +df.columns = df.columns.map("-".join) + +# Compute a correlation matrix and convert to long-form +corr_mat = df.corr().stack().reset_index(name="correlation") + +# Draw each cell as a scatter point with varying size and color +g = sns.relplot( + data=corr_mat, + x="level_0", y="level_1", hue="correlation", size="correlation", + palette="vlag", hue_norm=(-1, 1), edgecolor=".7", + height=10, sizes=(50, 250), size_norm=(-.2, .8), +) + +# Tweak the figure to finalize +g.set(xlabel="", ylabel="", aspect="equal") +g.despine(left=True, bottom=True) +g.ax.margins(.02) +for label in g.ax.get_xticklabels(): + label.set_rotation(90) +for artist in g.legend.legendHandles: + artist.set_edgecolor(".7") diff --git a/testbed/mwaskom__seaborn/examples/hexbin_marginals.py b/testbed/mwaskom__seaborn/examples/hexbin_marginals.py new file mode 100644 index 0000000000000000000000000000000000000000..e59b65fe69885600a566d6b8a34641c588d7e303 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/hexbin_marginals.py @@ -0,0 +1,15 @@ +""" +Hexbin plot with marginal distributions +======================================= + +_thumb: .45, .4 +""" +import numpy as np +import seaborn as sns +sns.set_theme(style="ticks") + +rs = np.random.RandomState(11) +x = rs.gamma(2, size=1000) +y = -.5 * x + rs.normal(size=1000) + +sns.jointplot(x=x, y=y, kind="hex", color="#4CB391") diff --git a/testbed/mwaskom__seaborn/examples/histogram_stacked.py b/testbed/mwaskom__seaborn/examples/histogram_stacked.py new file mode 100644 index 0000000000000000000000000000000000000000..9efd80406c778c7a5cfceaf5f34fa68d31de6b86 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/histogram_stacked.py @@ -0,0 +1,29 @@ +""" +Stacked histogram on a log scale +================================ + +_thumb: .5, .45 + +""" +import seaborn as sns +import matplotlib as mpl +import matplotlib.pyplot as plt + +sns.set_theme(style="ticks") + +diamonds = sns.load_dataset("diamonds") + +f, ax = plt.subplots(figsize=(7, 5)) +sns.despine(f) + +sns.histplot( + diamonds, + x="price", hue="cut", + multiple="stack", + palette="light:m_r", + edgecolor=".3", + linewidth=.5, + log_scale=True, +) +ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter()) +ax.set_xticks([500, 1000, 2000, 5000, 10000]) diff --git a/testbed/mwaskom__seaborn/examples/horizontal_boxplot.py b/testbed/mwaskom__seaborn/examples/horizontal_boxplot.py new file mode 100644 index 0000000000000000000000000000000000000000..48e4991facc4d4cf3393b76ba0841583d114db5e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/horizontal_boxplot.py @@ -0,0 +1,30 @@ +""" +Horizontal boxplot with observations +==================================== + +_thumb: .7, .37 +""" +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="ticks") + +# Initialize the figure with a logarithmic x axis +f, ax = plt.subplots(figsize=(7, 6)) +ax.set_xscale("log") + +# Load the example planets dataset +planets = sns.load_dataset("planets") + +# Plot the orbital period with horizontal boxes +sns.boxplot(x="distance", y="method", data=planets, + whis=[0, 100], width=.6, palette="vlag") + +# Add in points to show each observation +sns.stripplot(x="distance", y="method", data=planets, + size=4, color=".3", linewidth=0) + +# Tweak the visual presentation +ax.xaxis.grid(True) +ax.set(ylabel="") +sns.despine(trim=True, left=True) diff --git a/testbed/mwaskom__seaborn/examples/jitter_stripplot.py b/testbed/mwaskom__seaborn/examples/jitter_stripplot.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8f6b694be58aa37dbc99ce6f5b1d8b13709f5e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/jitter_stripplot.py @@ -0,0 +1,38 @@ +""" +Conditional means with observations +=================================== + +""" +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="whitegrid") +iris = sns.load_dataset("iris") + +# "Melt" the dataset to "long-form" or "tidy" representation +iris = pd.melt(iris, "species", var_name="measurement") + +# Initialize the figure +f, ax = plt.subplots() +sns.despine(bottom=True, left=True) + +# Show each observation with a scatterplot +sns.stripplot( + data=iris, x="value", y="measurement", hue="species", + dodge=True, alpha=.25, zorder=1, legend=False +) + +# Show the conditional means, aligning each pointplot in the +# center of the strips by adjusting the width allotted to each +# category (.8 by default) by the number of hue levels +sns.pointplot( + data=iris, x="value", y="measurement", hue="species", + join=False, dodge=.8 - .8 / 3, palette="dark", + markers="d", scale=.75, errorbar=None +) + +# Improve the legend +sns.move_legend( + ax, loc="lower right", ncol=3, frameon=True, columnspacing=1, handletextpad=0 +) diff --git a/testbed/mwaskom__seaborn/examples/joint_histogram.py b/testbed/mwaskom__seaborn/examples/joint_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ae9ebe0cc45bc8a3dec25547721c70edcb49cb --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/joint_histogram.py @@ -0,0 +1,26 @@ +""" +Joint and marginal histograms +============================= + +_thumb: .52, .505 + +""" +import seaborn as sns +sns.set_theme(style="ticks") + +# Load the planets dataset and initialize the figure +planets = sns.load_dataset("planets") +g = sns.JointGrid(data=planets, x="year", y="distance", marginal_ticks=True) + +# Set a log scaling on the y axis +g.ax_joint.set(yscale="log") + +# Create an inset legend for the histogram colorbar +cax = g.figure.add_axes([.15, .55, .02, .2]) + +# Add the joint and marginal histogram plots +g.plot_joint( + sns.histplot, discrete=(True, False), + cmap="light:#03012d", pmax=.8, cbar=True, cbar_ax=cax +) +g.plot_marginals(sns.histplot, element="step", color="#03012d") diff --git a/testbed/mwaskom__seaborn/examples/joint_kde.py b/testbed/mwaskom__seaborn/examples/joint_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..2358228ba5a32a5f99a35b3f67b1159f0f226ca3 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/joint_kde.py @@ -0,0 +1,18 @@ +""" +Joint kernel density estimate +============================= + +_thumb: .6, .4 +""" +import seaborn as sns +sns.set_theme(style="ticks") + +# Load the penguins dataset +penguins = sns.load_dataset("penguins") + +# Show the joint distribution using kernel density estimation +g = sns.jointplot( + data=penguins, + x="bill_length_mm", y="bill_depth_mm", hue="species", + kind="kde", +) diff --git a/testbed/mwaskom__seaborn/examples/kde_ridgeplot.py b/testbed/mwaskom__seaborn/examples/kde_ridgeplot.py new file mode 100644 index 0000000000000000000000000000000000000000..684df77df96ca21275c76523987e00ba98893a08 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/kde_ridgeplot.py @@ -0,0 +1,50 @@ +""" +Overlapping densities ('ridge plot') +==================================== + + +""" +import numpy as np +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="white", rc={"axes.facecolor": (0, 0, 0, 0)}) + +# Create the data +rs = np.random.RandomState(1979) +x = rs.randn(500) +g = np.tile(list("ABCDEFGHIJ"), 50) +df = pd.DataFrame(dict(x=x, g=g)) +m = df.g.map(ord) +df["x"] += m + +# Initialize the FacetGrid object +pal = sns.cubehelix_palette(10, rot=-.25, light=.7) +g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal) + +# Draw the densities in a few steps +g.map(sns.kdeplot, "x", + bw_adjust=.5, clip_on=False, + fill=True, alpha=1, linewidth=1.5) +g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw_adjust=.5) + +# passing color=None to refline() uses the hue mapping +g.refline(y=0, linewidth=2, linestyle="-", color=None, clip_on=False) + + +# Define and use a simple function to label the plot in axes coordinates +def label(x, color, label): + ax = plt.gca() + ax.text(0, .2, label, fontweight="bold", color=color, + ha="left", va="center", transform=ax.transAxes) + + +g.map(label, "x") + +# Set the subplots to overlap +g.figure.subplots_adjust(hspace=-.25) + +# Remove axes details that don't play well with overlap +g.set_titles("") +g.set(yticks=[], ylabel="") +g.despine(bottom=True, left=True) diff --git a/testbed/mwaskom__seaborn/examples/large_distributions.py b/testbed/mwaskom__seaborn/examples/large_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..6dbfe63aae4bda3f986c9e1547e087d844573908 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/large_distributions.py @@ -0,0 +1,14 @@ +""" +Plotting large distributions +============================ + +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +diamonds = sns.load_dataset("diamonds") +clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"] + +sns.boxenplot(x="clarity", y="carat", + color="b", order=clarity_ranking, + scale="linear", data=diamonds) diff --git a/testbed/mwaskom__seaborn/examples/layered_bivariate_plot.py b/testbed/mwaskom__seaborn/examples/layered_bivariate_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..40c63e35f481bbddec2142fae8a59042e7d4711a --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/layered_bivariate_plot.py @@ -0,0 +1,23 @@ +""" +Bivariate plot with multiple elements +===================================== + + +""" +import numpy as np +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="dark") + +# Simulate data from a bivariate Gaussian +n = 10000 +mean = [0, 0] +cov = [(2, .4), (.4, .2)] +rng = np.random.RandomState(0) +x, y = rng.multivariate_normal(mean, cov, n).T + +# Draw a combo histogram and scatterplot with density contours +f, ax = plt.subplots(figsize=(6, 6)) +sns.scatterplot(x=x, y=y, s=5, color=".15") +sns.histplot(x=x, y=y, bins=50, pthresh=.1, cmap="mako") +sns.kdeplot(x=x, y=y, levels=5, color="w", linewidths=1) diff --git a/testbed/mwaskom__seaborn/examples/logistic_regression.py b/testbed/mwaskom__seaborn/examples/logistic_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..8e636956e088c62c4addbf6f98eeecf394850f2e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/logistic_regression.py @@ -0,0 +1,19 @@ +""" +Faceted logistic regression +=========================== + +_thumb: .58, .5 +""" +import seaborn as sns +sns.set_theme(style="darkgrid") + +# Load the example Titanic dataset +df = sns.load_dataset("titanic") + +# Make a custom palette with gendered colors +pal = dict(male="#6495ED", female="#F08080") + +# Show the survival probability as a function of age and sex +g = sns.lmplot(x="age", y="survived", col="sex", hue="sex", data=df, + palette=pal, y_jitter=.02, logistic=True, truncate=False) +g.set(xlim=(0, 80), ylim=(-.05, 1.05)) diff --git a/testbed/mwaskom__seaborn/examples/many_facets.py b/testbed/mwaskom__seaborn/examples/many_facets.py new file mode 100644 index 0000000000000000000000000000000000000000..61ab56981856d7e82820fac2e1ad67a0ee9a2c54 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/many_facets.py @@ -0,0 +1,39 @@ +""" +Plotting on a large number of facets +==================================== + +_thumb: .4, .3 + +""" +import numpy as np +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="ticks") + +# Create a dataset with many short random walks +rs = np.random.RandomState(4) +pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1) +pos -= pos[:, 0, np.newaxis] +step = np.tile(range(5), 20) +walk = np.repeat(range(20), 5) +df = pd.DataFrame(np.c_[pos.flat, step, walk], + columns=["position", "step", "walk"]) + +# Initialize a grid of plots with an Axes for each walk +grid = sns.FacetGrid(df, col="walk", hue="walk", palette="tab20c", + col_wrap=4, height=1.5) + +# Draw a horizontal line to show the starting point +grid.refline(y=0, linestyle=":") + +# Draw a line plot to show the trajectory of each random walk +grid.map(plt.plot, "step", "position", marker="o") + +# Adjust the tick positions and labels +grid.set(xticks=np.arange(5), yticks=[-3, 3], + xlim=(-.5, 4.5), ylim=(-3.5, 3.5)) + +# Adjust the arrangement of the plots +grid.fig.tight_layout(w_pad=1) diff --git a/testbed/mwaskom__seaborn/examples/many_pairwise_correlations.py b/testbed/mwaskom__seaborn/examples/many_pairwise_correlations.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae2315412958ae329f008c6b2fe10d98472d69f --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/many_pairwise_correlations.py @@ -0,0 +1,34 @@ +""" +Plotting a diagonal correlation matrix +====================================== + +_thumb: .3, .6 +""" +from string import ascii_letters +import numpy as np +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="white") + +# Generate a large random dataset +rs = np.random.RandomState(33) +d = pd.DataFrame(data=rs.normal(size=(100, 26)), + columns=list(ascii_letters[26:])) + +# Compute the correlation matrix +corr = d.corr() + +# Generate a mask for the upper triangle +mask = np.triu(np.ones_like(corr, dtype=bool)) + +# Set up the matplotlib figure +f, ax = plt.subplots(figsize=(11, 9)) + +# Generate a custom diverging colormap +cmap = sns.diverging_palette(230, 20, as_cmap=True) + +# Draw the heatmap with the mask and correct aspect ratio +sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, + square=True, linewidths=.5, cbar_kws={"shrink": .5}) diff --git a/testbed/mwaskom__seaborn/examples/marginal_ticks.py b/testbed/mwaskom__seaborn/examples/marginal_ticks.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a8d61518b5c9d4026a91a7292f87ff31d60e81 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/marginal_ticks.py @@ -0,0 +1,15 @@ +""" +Scatterplot with marginal ticks +=============================== + +_thumb: .66, .34 +""" +import seaborn as sns +sns.set_theme(style="white", color_codes=True) +mpg = sns.load_dataset("mpg") + +# Use JointGrid directly to draw a custom plot +g = sns.JointGrid(data=mpg, x="mpg", y="acceleration", space=0, ratio=17) +g.plot_joint(sns.scatterplot, size=mpg["horsepower"], sizes=(30, 120), + color="g", alpha=.6, legend=False) +g.plot_marginals(sns.rugplot, height=1, color="g", alpha=.6) diff --git a/testbed/mwaskom__seaborn/examples/multiple_bivariate_kde.py b/testbed/mwaskom__seaborn/examples/multiple_bivariate_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..217c8afa5d224a7fa072deae7c71914281a1ae2c --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/multiple_bivariate_kde.py @@ -0,0 +1,24 @@ +""" +Multiple bivariate KDE plots +============================ + +_thumb: .6, .45 +""" +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="darkgrid") +iris = sns.load_dataset("iris") + +# Set up the figure +f, ax = plt.subplots(figsize=(8, 8)) +ax.set_aspect("equal") + +# Draw a contour plot to represent each bivariate density +sns.kdeplot( + data=iris.query("species != 'versicolor'"), + x="sepal_width", + y="sepal_length", + hue="species", + thresh=.1, +) diff --git a/testbed/mwaskom__seaborn/examples/multiple_conditional_kde.py b/testbed/mwaskom__seaborn/examples/multiple_conditional_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6dfb10795e930f0f725d46e91fe9cd2db00b35 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/multiple_conditional_kde.py @@ -0,0 +1,20 @@ +""" +Conditional kernel density estimate +=================================== + +_thumb: .4, .5 +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the diamonds dataset +diamonds = sns.load_dataset("diamonds") + +# Plot the distribution of clarity ratings, conditional on carat +sns.displot( + data=diamonds, + x="carat", hue="cut", + kind="kde", height=6, + multiple="fill", clip=(0, None), + palette="ch:rot=-.25,hue=1,light=.75", +) diff --git a/testbed/mwaskom__seaborn/examples/multiple_ecdf.py b/testbed/mwaskom__seaborn/examples/multiple_ecdf.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae904590b700f78fde7d2809df9d013704fb263 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/multiple_ecdf.py @@ -0,0 +1,17 @@ +""" +Facetted ECDF plots +=================== + +_thumb: .30, .49 +""" +import seaborn as sns +sns.set_theme(style="ticks") +mpg = sns.load_dataset("mpg") + +colors = (250, 70, 50), (350, 70, 50) +cmap = sns.blend_palette(colors, input="husl", as_cmap=True) +sns.displot( + mpg, + x="displacement", col="origin", hue="model_year", + kind="ecdf", aspect=.75, linewidth=2, palette=cmap, +) diff --git a/testbed/mwaskom__seaborn/examples/multiple_regression.py b/testbed/mwaskom__seaborn/examples/multiple_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..cb72204fca61bf77981810d8c84d460d0e06adc1 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/multiple_regression.py @@ -0,0 +1,21 @@ +""" +Multiple linear regression +========================== + +_thumb: .45, .45 +""" +import seaborn as sns +sns.set_theme() + +# Load the penguins dataset +penguins = sns.load_dataset("penguins") + +# Plot sepal width as a function of sepal_length across days +g = sns.lmplot( + data=penguins, + x="bill_length_mm", y="bill_depth_mm", hue="species", + height=5 +) + +# Use more informative axis labels than are provided by default +g.set_axis_labels("Snoot length (mm)", "Snoot depth (mm)") diff --git a/testbed/mwaskom__seaborn/examples/pair_grid_with_kde.py b/testbed/mwaskom__seaborn/examples/pair_grid_with_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad74429cc3dcdda50c92036050fb0cd686010e6 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/pair_grid_with_kde.py @@ -0,0 +1,15 @@ +""" +Paired density and scatterplot matrix +===================================== + +_thumb: .5, .5 +""" +import seaborn as sns +sns.set_theme(style="white") + +df = sns.load_dataset("penguins") + +g = sns.PairGrid(df, diag_sharey=False) +g.map_upper(sns.scatterplot, s=15) +g.map_lower(sns.kdeplot) +g.map_diag(sns.kdeplot, lw=2) diff --git a/testbed/mwaskom__seaborn/examples/paired_pointplots.py b/testbed/mwaskom__seaborn/examples/paired_pointplots.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab79655b80d5ec7076b575d9f46ca2e42e63044 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/paired_pointplots.py @@ -0,0 +1,20 @@ +""" +Paired categorical plots +======================== + +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the example Titanic dataset +titanic = sns.load_dataset("titanic") + +# Set up a grid to plot survival probability against several variables +g = sns.PairGrid(titanic, y_vars="survived", + x_vars=["class", "sex", "who", "alone"], + height=5, aspect=.5) + +# Draw a seaborn pointplot onto each Axes +g.map(sns.pointplot, scale=1.3, errwidth=4, color="xkcd:plum") +g.set(ylim=(0, 1)) +sns.despine(fig=g.fig, left=True) diff --git a/testbed/mwaskom__seaborn/examples/pairgrid_dotplot.py b/testbed/mwaskom__seaborn/examples/pairgrid_dotplot.py new file mode 100644 index 0000000000000000000000000000000000000000..8509812d4a31d21eaa8a0fb918ac9cd166d983ce --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/pairgrid_dotplot.py @@ -0,0 +1,38 @@ +""" +Dot plot with several variables +=============================== + +_thumb: .3, .3 +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the dataset +crashes = sns.load_dataset("car_crashes") + +# Make the PairGrid +g = sns.PairGrid(crashes.sort_values("total", ascending=False), + x_vars=crashes.columns[:-3], y_vars=["abbrev"], + height=10, aspect=.25) + +# Draw a dot plot using the stripplot function +g.map(sns.stripplot, size=10, orient="h", jitter=False, + palette="flare_r", linewidth=1, edgecolor="w") + +# Use the same x axis limits on all columns and add better labels +g.set(xlim=(0, 25), xlabel="Crashes", ylabel="") + +# Use semantically meaningful titles for the columns +titles = ["Total crashes", "Speeding crashes", "Alcohol crashes", + "Not distracted crashes", "No previous crashes"] + +for ax, title in zip(g.axes.flat, titles): + + # Set a different title for each axes + ax.set(title=title) + + # Make the grid horizontal instead of vertical + ax.xaxis.grid(False) + ax.yaxis.grid(True) + +sns.despine(left=True, bottom=True) diff --git a/testbed/mwaskom__seaborn/examples/palette_choices.py b/testbed/mwaskom__seaborn/examples/palette_choices.py new file mode 100644 index 0000000000000000000000000000000000000000..141a02485421b5e8dfd078a2e21e0bc1cca95e22 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/palette_choices.py @@ -0,0 +1,37 @@ +""" +Color palette choices +===================== + +""" +import numpy as np +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="white", context="talk") +rs = np.random.RandomState(8) + +# Set up the matplotlib figure +f, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7, 5), sharex=True) + +# Generate some sequential data +x = np.array(list("ABCDEFGHIJ")) +y1 = np.arange(1, 11) +sns.barplot(x=x, y=y1, palette="rocket", ax=ax1) +ax1.axhline(0, color="k", clip_on=False) +ax1.set_ylabel("Sequential") + +# Center the data to make it diverging +y2 = y1 - 5.5 +sns.barplot(x=x, y=y2, palette="vlag", ax=ax2) +ax2.axhline(0, color="k", clip_on=False) +ax2.set_ylabel("Diverging") + +# Randomly reorder the data to make it qualitative +y3 = rs.choice(y1, len(y1), replace=False) +sns.barplot(x=x, y=y3, palette="deep", ax=ax3) +ax3.axhline(0, color="k", clip_on=False) +ax3.set_ylabel("Qualitative") + +# Finalize the plot +sns.despine(bottom=True) +plt.setp(f.axes, yticks=[]) +plt.tight_layout(h_pad=2) diff --git a/testbed/mwaskom__seaborn/examples/palette_generation.py b/testbed/mwaskom__seaborn/examples/palette_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..82ef6842f5c60cc7e32c242aac3e37ad38bd7b7b --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/palette_generation.py @@ -0,0 +1,35 @@ +""" +Different cubehelix palettes +============================ + +_thumb: .4, .65 +""" +import numpy as np +import seaborn as sns +import matplotlib.pyplot as plt + +sns.set_theme(style="white") +rs = np.random.RandomState(50) + +# Set up the matplotlib figure +f, axes = plt.subplots(3, 3, figsize=(9, 9), sharex=True, sharey=True) + +# Rotate the starting point around the cubehelix hue circle +for ax, s in zip(axes.flat, np.linspace(0, 3, 10)): + + # Create a cubehelix colormap to use with kdeplot + cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True) + + # Generate and plot a random bivariate dataset + x, y = rs.normal(size=(2, 50)) + sns.kdeplot( + x=x, y=y, + cmap=cmap, fill=True, + clip=(-5, 5), cut=10, + thresh=0, levels=15, + ax=ax, + ) + ax.set_axis_off() + +ax.set(xlim=(-3.5, 3.5), ylim=(-3.5, 3.5)) +f.subplots_adjust(0, 0, 1, 1, .08, .08) diff --git a/testbed/mwaskom__seaborn/examples/part_whole_bars.py b/testbed/mwaskom__seaborn/examples/part_whole_bars.py new file mode 100644 index 0000000000000000000000000000000000000000..d64ffbf74d134747595c6f9c2bc29523977d11b1 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/part_whole_bars.py @@ -0,0 +1,30 @@ +""" +Horizontal bar plots +==================== + +""" +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="whitegrid") + +# Initialize the matplotlib figure +f, ax = plt.subplots(figsize=(6, 15)) + +# Load the example car crash dataset +crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False) + +# Plot the total crashes +sns.set_color_codes("pastel") +sns.barplot(x="total", y="abbrev", data=crashes, + label="Total", color="b") + +# Plot the crashes where alcohol was involved +sns.set_color_codes("muted") +sns.barplot(x="alcohol", y="abbrev", data=crashes, + label="Alcohol-involved", color="b") + +# Add a legend and informative axis label +ax.legend(ncol=2, loc="lower right", frameon=True) +ax.set(xlim=(0, 24), ylabel="", + xlabel="Automobile collisions per billion miles") +sns.despine(left=True, bottom=True) diff --git a/testbed/mwaskom__seaborn/examples/pointplot_anova.py b/testbed/mwaskom__seaborn/examples/pointplot_anova.py new file mode 100644 index 0000000000000000000000000000000000000000..761d04c75c80f484b10e45b52a7d3388c44954ae --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/pointplot_anova.py @@ -0,0 +1,19 @@ +""" +Plotting a three-way ANOVA +========================== + +_thumb: .42, .5 +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the example exercise dataset +exercise = sns.load_dataset("exercise") + +# Draw a pointplot to show pulse as a function of three categorical factors +g = sns.catplot( + data=exercise, x="time", y="pulse", hue="kind", col="diet", + capsize=.2, palette="YlGnBu_d", errorbar="se", + kind="point", height=6, aspect=.75, +) +g.despine(left=True) diff --git a/testbed/mwaskom__seaborn/examples/radial_facets.py b/testbed/mwaskom__seaborn/examples/radial_facets.py new file mode 100644 index 0000000000000000000000000000000000000000..3d9571723965d84af19f99d8d5cf4aadf1427622 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/radial_facets.py @@ -0,0 +1,27 @@ +""" +FacetGrid with custom projection +================================ + +_thumb: .33, .5 + +""" +import numpy as np +import pandas as pd +import seaborn as sns + +sns.set_theme() + +# Generate an example radial datast +r = np.linspace(0, 10, num=100) +df = pd.DataFrame({'r': r, 'slow': r, 'medium': 2 * r, 'fast': 4 * r}) + +# Convert the dataframe to long-form or "tidy" format +df = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta') + +# Set up a grid of axes with a polar projection +g = sns.FacetGrid(df, col="speed", hue="speed", + subplot_kws=dict(projection='polar'), height=4.5, + sharex=False, sharey=False, despine=False) + +# Draw a scatterplot onto each axes in the grid +g.map(sns.scatterplot, "theta", "r") diff --git a/testbed/mwaskom__seaborn/examples/regression_marginals.py b/testbed/mwaskom__seaborn/examples/regression_marginals.py new file mode 100644 index 0000000000000000000000000000000000000000..a64bb91c2549676d8556a7520598b248450363b7 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/regression_marginals.py @@ -0,0 +1,14 @@ +""" +Linear regression with marginal distributions +============================================= + +_thumb: .65, .65 +""" +import seaborn as sns +sns.set_theme(style="darkgrid") + +tips = sns.load_dataset("tips") +g = sns.jointplot(x="total_bill", y="tip", data=tips, + kind="reg", truncate=False, + xlim=(0, 60), ylim=(0, 12), + color="m", height=7) diff --git a/testbed/mwaskom__seaborn/examples/residplot.py b/testbed/mwaskom__seaborn/examples/residplot.py new file mode 100644 index 0000000000000000000000000000000000000000..cfd9518df104855332b25e24745da2279de83faa --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/residplot.py @@ -0,0 +1,16 @@ +""" +Plotting model residuals +======================== + +""" +import numpy as np +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Make an example dataset with y ~ x +rs = np.random.RandomState(7) +x = rs.normal(2, 1, 75) +y = 2 + 1.5 * x + rs.normal(0, 2, 75) + +# Plot the residuals after fitting a linear model +sns.residplot(x=x, y=y, lowess=True, color="g") diff --git a/testbed/mwaskom__seaborn/examples/scatter_bubbles.py b/testbed/mwaskom__seaborn/examples/scatter_bubbles.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9c6577c12ceab1b3a0fc410e3f3016013338dc --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/scatter_bubbles.py @@ -0,0 +1,17 @@ +""" +Scatterplot with varying point sizes and hues +============================================== + +_thumb: .45, .5 + +""" +import seaborn as sns +sns.set_theme(style="white") + +# Load the example mpg dataset +mpg = sns.load_dataset("mpg") + +# Plot miles per gallon against horsepower with other semantics +sns.relplot(x="horsepower", y="mpg", hue="origin", size="weight", + sizes=(40, 400), alpha=.5, palette="muted", + height=6, data=mpg) diff --git a/testbed/mwaskom__seaborn/examples/scatterplot_categorical.py b/testbed/mwaskom__seaborn/examples/scatterplot_categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..cc22a611e119c9e41c6e60d3bd95bf12cca1d93e --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/scatterplot_categorical.py @@ -0,0 +1,16 @@ +""" +Scatterplot with categorical variables +====================================== + +_thumb: .45, .45 + +""" +import seaborn as sns +sns.set_theme(style="whitegrid", palette="muted") + +# Load the penguins dataset +df = sns.load_dataset("penguins") + +# Draw a categorical scatterplot to show each observation +ax = sns.swarmplot(data=df, x="body_mass_g", y="sex", hue="species") +ax.set(ylabel="") diff --git a/testbed/mwaskom__seaborn/examples/scatterplot_matrix.py b/testbed/mwaskom__seaborn/examples/scatterplot_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..61829ea1b15efdfaded61348d21d9c79bd350696 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/scatterplot_matrix.py @@ -0,0 +1,11 @@ +""" +Scatterplot Matrix +================== + +_thumb: .3, .2 +""" +import seaborn as sns +sns.set_theme(style="ticks") + +df = sns.load_dataset("penguins") +sns.pairplot(df, hue="species") diff --git a/testbed/mwaskom__seaborn/examples/scatterplot_sizes.py b/testbed/mwaskom__seaborn/examples/scatterplot_sizes.py new file mode 100644 index 0000000000000000000000000000000000000000..492f6a496ae6e2dd0572954968babcb4274886fc --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/scatterplot_sizes.py @@ -0,0 +1,24 @@ +""" +Scatterplot with continuous hues and sizes +========================================== + +_thumb: .51, .44 + +""" +import seaborn as sns +sns.set_theme(style="whitegrid") + +# Load the example planets dataset +planets = sns.load_dataset("planets") + +cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) +g = sns.relplot( + data=planets, + x="distance", y="orbital_period", + hue="year", size="mass", + palette=cmap, sizes=(10, 200), +) +g.set(xscale="log", yscale="log") +g.ax.xaxis.grid(True, "minor", linewidth=.25) +g.ax.yaxis.grid(True, "minor", linewidth=.25) +g.despine(left=True, bottom=True) diff --git a/testbed/mwaskom__seaborn/examples/simple_violinplots.py b/testbed/mwaskom__seaborn/examples/simple_violinplots.py new file mode 100644 index 0000000000000000000000000000000000000000..2d53ccbaf8a174346acb787d9578144a4c1322a8 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/simple_violinplots.py @@ -0,0 +1,18 @@ +""" +Violinplots with observations +============================= + +""" +import numpy as np +import seaborn as sns + +sns.set_theme() + +# Create a random dataset across several variables +rs = np.random.default_rng(0) +n, p = 40, 8 +d = rs.normal(0, 2, (n, p)) +d += np.log(np.arange(1, p + 1)) * -5 + 10 + +# Show each distribution with both violins and points +sns.violinplot(data=d, palette="light:g", inner="points", orient="h") diff --git a/testbed/mwaskom__seaborn/examples/smooth_bivariate_kde.py b/testbed/mwaskom__seaborn/examples/smooth_bivariate_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..a654e399f1c3cbbcf7dd77c60eb6753edffc0b5b --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/smooth_bivariate_kde.py @@ -0,0 +1,16 @@ +""" +Smooth kernel density with marginal histograms +============================================== + +_thumb: .48, .41 +""" +import seaborn as sns +sns.set_theme(style="white") + +df = sns.load_dataset("penguins") + +g = sns.JointGrid(data=df, x="body_mass_g", y="bill_depth_mm", space=0) +g.plot_joint(sns.kdeplot, + fill=True, clip=((2200, 6800), (10, 25)), + thresh=0, levels=100, cmap="rocket") +g.plot_marginals(sns.histplot, color="#03051A", alpha=1, bins=25) diff --git a/testbed/mwaskom__seaborn/examples/spreadsheet_heatmap.py b/testbed/mwaskom__seaborn/examples/spreadsheet_heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..6eeecd0d0524c0f768e4e39eae341b2597a19005 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/spreadsheet_heatmap.py @@ -0,0 +1,16 @@ +""" +Annotated heatmaps +================== + +""" +import matplotlib.pyplot as plt +import seaborn as sns +sns.set_theme() + +# Load the example flights dataset and convert to long-form +flights_long = sns.load_dataset("flights") +flights = flights_long.pivot("month", "year", "passengers") + +# Draw a heatmap with the numeric values in each cell +f, ax = plt.subplots(figsize=(9, 6)) +sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax) diff --git a/testbed/mwaskom__seaborn/examples/strip_regplot.py b/testbed/mwaskom__seaborn/examples/strip_regplot.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b4fe8a269dbd3f607975ef61980941b9c79877 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/strip_regplot.py @@ -0,0 +1,18 @@ +""" +Regression fit over a strip plot +================================ + +_thumb: .53, .5 +""" +import seaborn as sns +sns.set_theme() + +mpg = sns.load_dataset("mpg") +sns.catplot( + data=mpg, x="cylinders", y="acceleration", hue="weight", + native_scale=True, zorder=1 +) +sns.regplot( + data=mpg, x="cylinders", y="acceleration", + scatter=False, truncate=False, order=2, color=".2", +) diff --git a/testbed/mwaskom__seaborn/examples/structured_heatmap.py b/testbed/mwaskom__seaborn/examples/structured_heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..af675caa340222fff8af601f3fe369781f0f7334 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/structured_heatmap.py @@ -0,0 +1,36 @@ +""" +Discovering structure in heatmap data +===================================== + +_thumb: .3, .25 +""" +import pandas as pd +import seaborn as sns +sns.set_theme() + +# Load the brain networks example dataset +df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) + +# Select a subset of the networks +used_networks = [1, 5, 6, 7, 8, 12, 13, 17] +used_columns = (df.columns.get_level_values("network") + .astype(int) + .isin(used_networks)) +df = df.loc[:, used_columns] + +# Create a categorical palette to identify the networks +network_pal = sns.husl_palette(8, s=.45) +network_lut = dict(zip(map(str, used_networks), network_pal)) + +# Convert the palette to vectors that will be drawn on the side of the matrix +networks = df.columns.get_level_values("network") +network_colors = pd.Series(networks, index=df.columns).map(network_lut) + +# Draw the full plot +g = sns.clustermap(df.corr(), center=0, cmap="vlag", + row_colors=network_colors, col_colors=network_colors, + dendrogram_ratio=(.1, .2), + cbar_pos=(.02, .32, .03, .2), + linewidths=.75, figsize=(12, 13)) + +g.ax_row_dendrogram.remove() diff --git a/testbed/mwaskom__seaborn/examples/three_variable_histogram.py b/testbed/mwaskom__seaborn/examples/three_variable_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..d642b7d40a9d873ea8a4c82bdf336197fe12134b --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/three_variable_histogram.py @@ -0,0 +1,15 @@ +""" +Trivariate histogram with two categorical variables +=================================================== + +_thumb: .32, .55 + +""" +import seaborn as sns +sns.set_theme(style="dark") + +diamonds = sns.load_dataset("diamonds") +sns.displot( + data=diamonds, x="price", y="color", col="clarity", + log_scale=(True, False), col_wrap=4, height=4, aspect=.7, +) diff --git a/testbed/mwaskom__seaborn/examples/timeseries_facets.py b/testbed/mwaskom__seaborn/examples/timeseries_facets.py new file mode 100644 index 0000000000000000000000000000000000000000..b757c93c12a8e74c42519d9647184e43672d1255 --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/timeseries_facets.py @@ -0,0 +1,39 @@ +""" +Small multiple time series +-------------------------- + +_thumb: .42, .58 + +""" +import seaborn as sns + +sns.set_theme(style="dark") +flights = sns.load_dataset("flights") + +# Plot each year's time series in its own facet +g = sns.relplot( + data=flights, + x="month", y="passengers", col="year", hue="year", + kind="line", palette="crest", linewidth=4, zorder=5, + col_wrap=3, height=2, aspect=1.5, legend=False, +) + +# Iterate over each subplot to customize further +for year, ax in g.axes_dict.items(): + + # Add the title as an annotation within the plot + ax.text(.8, .85, year, transform=ax.transAxes, fontweight="bold") + + # Plot every year's time series in the background + sns.lineplot( + data=flights, x="month", y="passengers", units="year", + estimator=None, color=".7", linewidth=1, ax=ax, + ) + +# Reduce the frequency of the x axis ticks +ax.set_xticks(ax.get_xticks()[::2]) + +# Tweak the supporting aspects of the plot +g.set_titles("") +g.set_axis_labels("", "Passengers") +g.tight_layout() diff --git a/testbed/mwaskom__seaborn/examples/wide_data_lineplot.py b/testbed/mwaskom__seaborn/examples/wide_data_lineplot.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdf24960a2a76254853d1262d1e569f80eee3ce --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/wide_data_lineplot.py @@ -0,0 +1,19 @@ +""" +Lineplot from a wide-form dataset +================================= + +_thumb: .52, .5 + +""" +import numpy as np +import pandas as pd +import seaborn as sns +sns.set_theme(style="whitegrid") + +rs = np.random.RandomState(365) +values = rs.randn(365, 4).cumsum(axis=0) +dates = pd.date_range("1 1 2016", periods=365, freq="D") +data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"]) +data = data.rolling(7).mean() + +sns.lineplot(data=data, palette="tab10", linewidth=2.5) diff --git a/testbed/mwaskom__seaborn/examples/wide_form_violinplot.py b/testbed/mwaskom__seaborn/examples/wide_form_violinplot.py new file mode 100644 index 0000000000000000000000000000000000000000..77a90193f7bdaf646308e11ce9f8ce23ffd7ad5b --- /dev/null +++ b/testbed/mwaskom__seaborn/examples/wide_form_violinplot.py @@ -0,0 +1,34 @@ +""" +Violinplot from a wide-form dataset +=================================== + +_thumb: .6, .45 +""" +import seaborn as sns +import matplotlib.pyplot as plt +sns.set_theme(style="whitegrid") + +# Load the example dataset of brain network correlations +df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) + +# Pull out a specific subset of networks +used_networks = [1, 3, 4, 5, 6, 7, 8, 11, 12, 13, 16, 17] +used_columns = (df.columns.get_level_values("network") + .astype(int) + .isin(used_networks)) +df = df.loc[:, used_columns] + +# Compute the correlation matrix and average over networks +corr_df = df.corr().groupby(level="network").mean() +corr_df.index = corr_df.index.astype(int) +corr_df = corr_df.sort_index().T + +# Set up the matplotlib figure +f, ax = plt.subplots(figsize=(11, 6)) + +# Draw a violinplot with a narrower bandwidth than the default +sns.violinplot(data=corr_df, palette="Set3", bw=.2, cut=1, linewidth=1) + +# Finalize the figure +ax.set(ylim=(-.7, 1.05)) +sns.despine(left=True, bottom=True) diff --git a/testbed/mwaskom__seaborn/licences/APPDIRS_LICENSE b/testbed/mwaskom__seaborn/licences/APPDIRS_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1dd88e7c6eab2af7dcca6f73ee56da4fa22c116 --- /dev/null +++ b/testbed/mwaskom__seaborn/licences/APPDIRS_LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2005-2010 ActiveState Software Inc. +Copyright (c) 2013 Eddy Petrișor + +This file is directly from +https://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py + +The license of https://github.com/ActiveState/appdirs copied below: + + +# This is the MIT license + +Copyright (c) 2010 ActiveState Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/testbed/mwaskom__seaborn/licences/HUSL_LICENSE b/testbed/mwaskom__seaborn/licences/HUSL_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cb05964503b29d38aa484672bcf90da4e4597121 --- /dev/null +++ b/testbed/mwaskom__seaborn/licences/HUSL_LICENSE @@ -0,0 +1,7 @@ +Copyright (C) 2012 Alexei Boronine + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/testbed/mwaskom__seaborn/licences/NUMPYDOC_LICENSE b/testbed/mwaskom__seaborn/licences/NUMPYDOC_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..dcd45e69f28cc65d4473bbb3b648245e9c702d98 --- /dev/null +++ b/testbed/mwaskom__seaborn/licences/NUMPYDOC_LICENSE @@ -0,0 +1,24 @@ +Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/testbed/mwaskom__seaborn/licences/PACKAGING_LICENSE b/testbed/mwaskom__seaborn/licences/PACKAGING_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/testbed/mwaskom__seaborn/licences/PACKAGING_LICENSE @@ -0,0 +1,23 @@ +Copyright (c) Donald Stufft and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/testbed/mwaskom__seaborn/licences/SCIPY_LICENSE b/testbed/mwaskom__seaborn/licences/SCIPY_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5a0a660d8ed534870a490c034cd3f1446b48a0ac --- /dev/null +++ b/testbed/mwaskom__seaborn/licences/SCIPY_LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/testbed/mwaskom__seaborn/pyproject.toml b/testbed/mwaskom__seaborn/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..91e60dd90ac27b71728c05ab4c13413389400bdb --- /dev/null +++ b/testbed/mwaskom__seaborn/pyproject.toml @@ -0,0 +1,62 @@ +[build-system] +requires = ["flit_core >=3.2,<4"] +build-backend = "flit_core.buildapi" + +[project] +name = "seaborn" +description = "Statistical data visualization" +authors = [{name = "Michael Waskom", email = "mwaskom@gmail.com"}] +readme = "README.md" +license = {file = "LICENSE.md"} +dynamic = ["version"] +classifiers = [ + "Intended Audience :: Science/Research", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "License :: OSI Approved :: BSD License", + "Topic :: Scientific/Engineering :: Visualization", + "Topic :: Multimedia :: Graphics", + "Operating System :: OS Independent", + "Framework :: Matplotlib", +] +requires-python = ">=3.8" +dependencies = [ + "numpy>=1.20,!=1.24.0", + "pandas>=1.2", + "matplotlib>=3.3,!=3.6.1", +] + +[project.optional-dependencies] +stats = [ + "scipy>=1.7", + "statsmodels>=0.12", +] +dev = [ + "pytest", + "pytest-cov", + "pytest-xdist", + "flake8", + "mypy", + "pandas-stubs", + "pre-commit", + "flit", +] +docs = [ + "numpydoc", + "nbconvert", + "ipykernel", + "sphinx-copybutton", + "sphinx-issues", + "sphinx-design", + "pyyaml", + "pydata_sphinx_theme==0.10.0rc2", +] + +[project.urls] +Source = "https://github.com/mwaskom/seaborn" +Docs = "http://seaborn.pydata.org" + +[tool.flit.sdist] +exclude = ["doc/_static/*.svg"] diff --git a/testbed/mwaskom__seaborn/seaborn/__init__.py b/testbed/mwaskom__seaborn/seaborn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ba256ca546cdbd983a12e2477fe90112cbe368 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/__init__.py @@ -0,0 +1,21 @@ +# Import seaborn objects +from .rcmod import * # noqa: F401,F403 +from .utils import * # noqa: F401,F403 +from .palettes import * # noqa: F401,F403 +from .relational import * # noqa: F401,F403 +from .regression import * # noqa: F401,F403 +from .categorical import * # noqa: F401,F403 +from .distributions import * # noqa: F401,F403 +from .matrix import * # noqa: F401,F403 +from .miscplot import * # noqa: F401,F403 +from .axisgrid import * # noqa: F401,F403 +from .widgets import * # noqa: F401,F403 +from .colors import xkcd_rgb, crayons # noqa: F401 +from . import cm # noqa: F401 + +# Capture the original matplotlib rcParams +import matplotlib as mpl +_orig_rc_params = mpl.rcParams.copy() + +# Define the seaborn version +__version__ = "0.13.0.dev0" diff --git a/testbed/mwaskom__seaborn/seaborn/_compat.py b/testbed/mwaskom__seaborn/seaborn/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..52902439b31cad779ba6030758968dad69713e29 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_compat.py @@ -0,0 +1,168 @@ +import numpy as np +import matplotlib as mpl +from seaborn.utils import _version_predates + + +def MarkerStyle(marker=None, fillstyle=None): + """ + Allow MarkerStyle to accept a MarkerStyle object as parameter. + + Supports matplotlib < 3.3.0 + https://github.com/matplotlib/matplotlib/pull/16692 + + """ + if isinstance(marker, mpl.markers.MarkerStyle): + if fillstyle is None: + return marker + else: + marker = marker.get_marker() + return mpl.markers.MarkerStyle(marker, fillstyle) + + +def norm_from_scale(scale, norm): + """Produce a Normalize object given a Scale and min/max domain limits.""" + # This is an internal maplotlib function that simplifies things to access + # It is likely to become part of the matplotlib API at some point: + # https://github.com/matplotlib/matplotlib/issues/20329 + if isinstance(norm, mpl.colors.Normalize): + return norm + + if scale is None: + return None + + if norm is None: + vmin = vmax = None + else: + vmin, vmax = norm # TODO more helpful error if this fails? + + class ScaledNorm(mpl.colors.Normalize): + + def __call__(self, value, clip=None): + # From github.com/matplotlib/matplotlib/blob/v3.4.2/lib/matplotlib/colors.py + # See github.com/matplotlib/matplotlib/tree/v3.4.2/LICENSE + value, is_scalar = self.process_value(value) + self.autoscale_None(value) + if self.vmin > self.vmax: + raise ValueError("vmin must be less or equal to vmax") + if self.vmin == self.vmax: + return np.full_like(value, 0) + if clip is None: + clip = self.clip + if clip: + value = np.clip(value, self.vmin, self.vmax) + # ***** Seaborn changes start **** + t_value = self.transform(value).reshape(np.shape(value)) + t_vmin, t_vmax = self.transform([self.vmin, self.vmax]) + # ***** Seaborn changes end ***** + if not np.isfinite([t_vmin, t_vmax]).all(): + raise ValueError("Invalid vmin or vmax") + t_value -= t_vmin + t_value /= (t_vmax - t_vmin) + t_value = np.ma.masked_invalid(t_value, copy=False) + return t_value[0] if is_scalar else t_value + + new_norm = ScaledNorm(vmin, vmax) + new_norm.transform = scale.get_transform().transform + + return new_norm + + +def scale_factory(scale, axis, **kwargs): + """ + Backwards compatability for creation of independent scales. + + Matplotlib scales require an Axis object for instantiation on < 3.4. + But the axis is not used, aside from extraction of the axis_name in LogScale. + + """ + modify_transform = False + if _version_predates(mpl, "3.4"): + if axis[0] in "xy": + modify_transform = True + axis = axis[0] + base = kwargs.pop("base", None) + if base is not None: + kwargs[f"base{axis}"] = base + nonpos = kwargs.pop("nonpositive", None) + if nonpos is not None: + kwargs[f"nonpos{axis}"] = nonpos + + if isinstance(scale, str): + class Axis: + axis_name = axis + axis = Axis() + + scale = mpl.scale.scale_factory(scale, axis, **kwargs) + + if modify_transform: + transform = scale.get_transform() + transform.base = kwargs.get("base", 10) + if kwargs.get("nonpositive") == "mask": + # Setting a private attribute, but we only get here + # on an old matplotlib, so this won't break going forwards + transform._clip = False + + return scale + + +def set_scale_obj(ax, axis, scale): + """Handle backwards compatability with setting matplotlib scale.""" + if _version_predates(mpl, "3.4"): + # The ability to pass a BaseScale instance to Axes.set_{}scale was added + # to matplotlib in version 3.4.0: GH: matplotlib/matplotlib/pull/19089 + # Workaround: use the scale name, which is restrictive only if the user + # wants to define a custom scale; they'll need to update the registry too. + if scale.name is None: + # Hack to support our custom Formatter-less CatScale + return + method = getattr(ax, f"set_{axis}scale") + kws = {} + if scale.name == "function": + trans = scale.get_transform() + kws["functions"] = (trans._forward, trans._inverse) + method(scale.name, **kws) + axis_obj = getattr(ax, f"{axis}axis") + scale.set_default_locators_and_formatters(axis_obj) + else: + ax.set(**{f"{axis}scale": scale}) + + +def get_colormap(name): + """Handle changes to matplotlib colormap interface in 3.6.""" + try: + return mpl.colormaps[name] + except AttributeError: + return mpl.cm.get_cmap(name) + + +def register_colormap(name, cmap): + """Handle changes to matplotlib colormap interface in 3.6.""" + try: + if name not in mpl.colormaps: + mpl.colormaps.register(cmap, name=name) + except AttributeError: + mpl.cm.register_cmap(name, cmap) + + +def set_layout_engine(fig, engine): + """Handle changes to auto layout engine interface in 3.6""" + if hasattr(fig, "set_layout_engine"): + fig.set_layout_engine(engine) + else: + # _version_predates(mpl, 3.6) + if engine == "tight": + fig.set_tight_layout(True) + elif engine == "constrained": + fig.set_constrained_layout(True) + elif engine == "none": + fig.set_tight_layout(False) + fig.set_constrained_layout(False) + + +def share_axis(ax0, ax1, which): + """Handle changes to post-hoc axis sharing.""" + if _version_predates(mpl, "3.5"): + group = getattr(ax0, f"get_shared_{which}_axes")() + group.join(ax1, ax0) + else: + getattr(ax1, f"share{which}")(ax0) diff --git a/testbed/mwaskom__seaborn/seaborn/_core/__init__.py b/testbed/mwaskom__seaborn/seaborn/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/mwaskom__seaborn/seaborn/_core/data.py b/testbed/mwaskom__seaborn/seaborn/_core/data.py new file mode 100644 index 0000000000000000000000000000000000000000..535fafe83f6f88f4ca3a386d86d9a1189e56cea2 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/data.py @@ -0,0 +1,260 @@ +""" +Components for parsing variable assignments and internally representing plot data. +""" +from __future__ import annotations + +from collections.abc import Mapping, Sized +from typing import cast + +import pandas as pd +from pandas import DataFrame + +from seaborn._core.typing import DataSource, VariableSpec, ColumnName + + +class PlotData: + """ + Data table with plot variable schema and mapping to original names. + + Contains logic for parsing variable specification arguments and updating + the table with layer-specific data and/or mappings. + + Parameters + ---------- + data + Input data where variable names map to vector values. + variables + Keys are names of plot variables (x, y, ...) each value is one of: + + - name of a column (or index level, or dictionary entry) in `data` + - vector in any format that can construct a :class:`pandas.DataFrame` + + Attributes + ---------- + frame + Data table with column names having defined plot variables. + names + Dictionary mapping plot variable names to names in source data structure(s). + ids + Dictionary mapping plot variable names to unique data source identifiers. + + """ + frame: DataFrame + frames: dict[tuple, DataFrame] + names: dict[str, str | None] + ids: dict[str, str | int] + source_data: DataSource + source_vars: dict[str, VariableSpec] + + def __init__( + self, + data: DataSource, + variables: dict[str, VariableSpec], + ): + + frame, names, ids = self._assign_variables(data, variables) + + self.frame = frame + self.names = names + self.ids = ids + + self.frames = {} # TODO this is a hack, remove + + self.source_data = data + self.source_vars = variables + + def __contains__(self, key: str) -> bool: + """Boolean check on whether a variable is defined in this dataset.""" + if self.frame is None: + return any(key in df for df in self.frames.values()) + return key in self.frame + + def join( + self, + data: DataSource, + variables: dict[str, VariableSpec] | None, + ) -> PlotData: + """Add, replace, or drop variables and return as a new dataset.""" + # Inherit the original source of the upsteam data by default + if data is None: + data = self.source_data + + # TODO allow `data` to be a function (that is called on the source data?) + + if not variables: + variables = self.source_vars + + # Passing var=None implies that we do not want that variable in this layer + disinherit = [k for k, v in variables.items() if v is None] + + # Create a new dataset with just the info passed here + new = PlotData(data, variables) + + # -- Update the inherited DataSource with this new information + + drop_cols = [k for k in self.frame if k in new.frame or k in disinherit] + parts = [self.frame.drop(columns=drop_cols), new.frame] + + # Because we are combining distinct columns, this is perhaps more + # naturally thought of as a "merge"/"join". But using concat because + # some simple testing suggests that it is marginally faster. + frame = pd.concat(parts, axis=1, sort=False, copy=False) + + names = {k: v for k, v in self.names.items() if k not in disinherit} + names.update(new.names) + + ids = {k: v for k, v in self.ids.items() if k not in disinherit} + ids.update(new.ids) + + new.frame = frame + new.names = names + new.ids = ids + + # Multiple chained operations should always inherit from the original object + new.source_data = self.source_data + new.source_vars = self.source_vars + + return new + + def _assign_variables( + self, + data: DataSource, + variables: dict[str, VariableSpec], + ) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]: + """ + Assign values for plot variables given long-form data and/or vector inputs. + + Parameters + ---------- + data + Input data where variable names map to vector values. + variables + Keys are names of plot variables (x, y, ...) each value is one of: + + - name of a column (or index level, or dictionary entry) in `data` + - vector in any format that can construct a :class:`pandas.DataFrame` + + Returns + ------- + frame + Table mapping seaborn variables (x, y, color, ...) to data vectors. + names + Keys are defined seaborn variables; values are names inferred from + the inputs (or None when no name can be determined). + ids + Like the `names` dict, but `None` values are replaced by the `id()` + of the data object that defined the variable. + + Raises + ------ + ValueError + When variables are strings that don't appear in `data`, or when they are + non-indexed vector datatypes that have a different length from `data`. + + """ + source_data: Mapping | DataFrame + frame: DataFrame + names: dict[str, str | None] + ids: dict[str, str | int] + + plot_data = {} + names = {} + ids = {} + + given_data = data is not None + if data is not None: + source_data = data + else: + # Data is optional; all variables can be defined as vectors + # But simplify downstream code by always having a usable source data object + source_data = {} + + # TODO Generally interested in accepting a generic DataFrame interface + # Track https://data-apis.org/ for development + + # Variables can also be extracted from the index of a DataFrame + if isinstance(source_data, pd.DataFrame): + index = source_data.index.to_frame().to_dict("series") + else: + index = {} + + for key, val in variables.items(): + + # Simply ignore variables with no specification + if val is None: + continue + + # Try to treat the argument as a key for the data collection. + # But be flexible about what can be used as a key. + # Usually it will be a string, but allow other hashables when + # taking from the main data object. Allow only strings to reference + # fields in the index, because otherwise there is too much ambiguity. + + # TODO this will be rendered unnecessary by the following pandas fix: + # https://github.com/pandas-dev/pandas/pull/41283 + try: + hash(val) + val_is_hashable = True + except TypeError: + val_is_hashable = False + + val_as_data_key = ( + # See https://github.com/pandas-dev/pandas/pull/41283 + # (isinstance(val, abc.Hashable) and val in source_data) + (val_is_hashable and val in source_data) + or (isinstance(val, str) and val in index) + ) + + if val_as_data_key: + val = cast(ColumnName, val) + if val in source_data: + plot_data[key] = source_data[val] + elif val in index: + plot_data[key] = index[val] + names[key] = ids[key] = str(val) + + elif isinstance(val, str): + + # This looks like a column name but, lookup failed. + + err = f"Could not interpret value `{val}` for `{key}`. " + if not given_data: + err += "Value is a string, but `data` was not passed." + else: + err += "An entry with this name does not appear in `data`." + raise ValueError(err) + + else: + + # Otherwise, assume the value somehow represents data + + # Ignore empty data structures + if isinstance(val, Sized) and len(val) == 0: + continue + + # If vector has no index, it must match length of data table + if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series): + if isinstance(val, Sized) and len(data) != len(val): + val_cls = val.__class__.__name__ + err = ( + f"Length of {val_cls} vectors must match length of `data`" + f" when both are used, but `data` has length {len(data)}" + f" and the vector passed to `{key}` has length {len(val)}." + ) + raise ValueError(err) + + plot_data[key] = val + + # Try to infer the original name using pandas-like metadata + if hasattr(val, "name"): + names[key] = ids[key] = str(val.name) # type: ignore # mypy/1424 + else: + names[key] = None + ids[key] = id(val) + + # Construct a tidy plot DataFrame. This will convert a number of + # types automatically, aligning on index in case of pandas objects + # TODO Note: this fails when variable specs *only* have scalars! + frame = pd.DataFrame(plot_data) + + return frame, names, ids diff --git a/testbed/mwaskom__seaborn/seaborn/_core/exceptions.py b/testbed/mwaskom__seaborn/seaborn/_core/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..048443b0f8639e2e90a635c74e6202ae62e3ca8b --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/exceptions.py @@ -0,0 +1,32 @@ +""" +Custom exceptions for the seaborn.objects interface. + +This is very lightweight, but it's a separate module to avoid circular imports. + +""" +from __future__ import annotations + + +class PlotSpecError(RuntimeError): + """ + Error class raised from seaborn.objects.Plot for compile-time failures. + + In the declarative Plot interface, exceptions may not be triggered immediately + by bad user input (and validation at input time may not be possible). This class + is used to signal that indirect dependency. It should be raised in an exception + chain when compile-time operations fail with an error message providing useful + context (e.g., scaling errors could specify the variable that failed.) + + """ + @classmethod + def _during(cls, step: str, var: str = "") -> PlotSpecError: + """ + Initialize the class to report the failure of a specific operation. + """ + message = [] + if var: + message.append(f"{step} failed for the `{var}` variable.") + else: + message.append(f"{step} failed.") + message.append("See the traceback above for more information.") + return cls(" ".join(message)) diff --git a/testbed/mwaskom__seaborn/seaborn/_core/groupby.py b/testbed/mwaskom__seaborn/seaborn/_core/groupby.py new file mode 100644 index 0000000000000000000000000000000000000000..cc41566cdec1db185ed95998ccb6d05647f4152b --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/groupby.py @@ -0,0 +1,129 @@ +"""Simplified split-apply-combine paradigm on dataframes for internal use.""" +from __future__ import annotations + +from typing import cast, Iterable + +import pandas as pd + +from seaborn._core.rules import categorical_order + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from typing import Callable + from pandas import DataFrame, MultiIndex, Index + + +class GroupBy: + """ + Interface for Pandas GroupBy operations allowing specified group order. + + Writing our own class to do this has a few advantages: + - It constrains the interface between Plot and Stat/Move objects + - It allows control over the row order of the GroupBy result, which is + important when using in the context of some Move operations (dodge, stack, ...) + - It simplifies some complexities regarding the return type and Index contents + one encounters with Pandas, especially for DataFrame -> DataFrame applies + - It increases future flexibility regarding alternate DataFrame libraries + + """ + def __init__(self, order: list[str] | dict[str, list | None]): + """ + Initialize the GroupBy from grouping variables and optional level orders. + + Parameters + ---------- + order + List of variable names or dict mapping names to desired level orders. + Level order values can be None to use default ordering rules. The + variables can include names that are not expected to appear in the + data; these will be dropped before the groups are defined. + + """ + if not order: + raise ValueError("GroupBy requires at least one grouping variable") + + if isinstance(order, list): + order = {k: None for k in order} + self.order = order + + def _get_groups( + self, data: DataFrame + ) -> tuple[str | list[str], Index | MultiIndex]: + """Return index with Cartesian product of ordered grouping variable levels.""" + levels = {} + for var, order in self.order.items(): + if var in data: + if order is None: + order = categorical_order(data[var]) + levels[var] = order + + grouper: str | list[str] + groups: Index | MultiIndex + if not levels: + grouper = [] + groups = pd.Index([]) + elif len(levels) > 1: + grouper = list(levels) + groups = pd.MultiIndex.from_product(levels.values(), names=grouper) + else: + grouper, = list(levels) + groups = pd.Index(levels[grouper], name=grouper) + return grouper, groups + + def _reorder_columns(self, res, data): + """Reorder result columns to match original order with new columns appended.""" + cols = [c for c in data if c in res] + cols += [c for c in res if c not in data] + return res.reindex(columns=pd.Index(cols)) + + def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame: + """ + Reduce each group to a single row in the output. + + The output will have a row for each unique combination of the grouping + variable levels with null values for the aggregated variable(s) where + those combinations do not appear in the dataset. + + """ + grouper, groups = self._get_groups(data) + + if not grouper: + # We will need to see whether there are valid usecases that end up here + raise ValueError("No grouping variables are present in dataframe") + + res = ( + data + .groupby(grouper, sort=False, observed=True) + .agg(*args, **kwargs) + .reindex(groups) + .reset_index() + .pipe(self._reorder_columns, data) + ) + + return res + + def apply( + self, data: DataFrame, func: Callable[..., DataFrame], + *args, **kwargs, + ) -> DataFrame: + """Apply a DataFrame -> DataFrame mapping to each group.""" + grouper, groups = self._get_groups(data) + + if not grouper: + return self._reorder_columns(func(data, *args, **kwargs), data) + + parts = {} + for key, part_df in data.groupby(grouper, sort=False): + parts[key] = func(part_df, *args, **kwargs) + stack = [] + for key in groups: + if key in parts: + if isinstance(grouper, list): + # Implies that we had a MultiIndex so key is iterable + group_ids = dict(zip(grouper, cast(Iterable, key))) + else: + group_ids = {grouper: key} + stack.append(parts[key].assign(**group_ids)) + + res = pd.concat(stack, ignore_index=True) + return self._reorder_columns(res, data) diff --git a/testbed/mwaskom__seaborn/seaborn/_core/moves.py b/testbed/mwaskom__seaborn/seaborn/_core/moves.py new file mode 100644 index 0000000000000000000000000000000000000000..179926e71789bb6a6891aa21d80ee38696f89236 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/moves.py @@ -0,0 +1,274 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import ClassVar, Callable, Optional, Union, cast + +import numpy as np +from pandas import DataFrame + +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale +from seaborn._core.typing import Default + +default = Default() + + +@dataclass +class Move: + """Base class for objects that apply simple positional transforms.""" + + group_by_orient: ClassVar[bool] = True + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + raise NotImplementedError + + +@dataclass +class Jitter(Move): + """ + Random displacement along one or both axes to reduce overplotting. + + Parameters + ---------- + width : float + Magnitude of jitter, relative to mark width, along the orientation axis. + If not provided, the default value will be 0 when `x` or `y` are set, otherwise + there will be a small amount of jitter applied by default. + x : float + Magnitude of jitter, in data units, along the x axis. + y : float + Magnitude of jitter, in data units, along the y axis. + + Examples + -------- + .. include:: ../docstrings/objects.Jitter.rst + + """ + width: float | Default = default + x: float = 0 + y: float = 0 + seed: int | None = None + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + data = data.copy() + rng = np.random.default_rng(self.seed) + + def jitter(data, col, scale): + noise = rng.uniform(-.5, +.5, len(data)) + offsets = noise * scale + return data[col] + offsets + + if self.width is default: + width = 0.0 if self.x or self.y else 0.2 + else: + width = cast(float, self.width) + + if self.width: + data[orient] = jitter(data, orient, width * data["width"]) + if self.x: + data["x"] = jitter(data, "x", self.x) + if self.y: + data["y"] = jitter(data, "y", self.y) + + return data + + +@dataclass +class Dodge(Move): + """ + Displacement and narrowing of overlapping marks along orientation axis. + + Parameters + ---------- + empty : {'keep', 'drop', 'fill'} + gap : float + Size of gap between dodged marks. + by : list of variable names + Variables to apply the movement to, otherwise use all. + + Examples + -------- + .. include:: ../docstrings/objects.Dodge.rst + + """ + empty: str = "keep" # Options: keep, drop, fill + gap: float = 0 + + # TODO accept just a str here? + # TODO should this always be present? + # TODO should the default be an "all" singleton? + by: Optional[list[str]] = None + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + grouping_vars = [v for v in groupby.order if v in data] + groups = groupby.agg(data, {"width": "max"}) + if self.empty == "fill": + groups = groups.dropna() + + def groupby_pos(s): + grouper = [groups[v] for v in [orient, "col", "row"] if v in data] + return s.groupby(grouper, sort=False, observed=True) + + def scale_widths(w): + # TODO what value to fill missing widths??? Hard problem... + # TODO short circuit this if outer widths has no variance? + empty = 0 if self.empty == "fill" else w.mean() + filled = w.fillna(empty) + scale = filled.max() + norm = filled.sum() + if self.empty == "keep": + w = filled + return w / norm * scale + + def widths_to_offsets(w): + return w.shift(1).fillna(0).cumsum() + (w - w.sum()) / 2 + + new_widths = groupby_pos(groups["width"]).transform(scale_widths) + offsets = groupby_pos(new_widths).transform(widths_to_offsets) + + if self.gap: + new_widths *= 1 - self.gap + + groups["_dodged"] = groups[orient] + offsets + groups["width"] = new_widths + + out = ( + data + .drop("width", axis=1) + .merge(groups, on=grouping_vars, how="left") + .drop(orient, axis=1) + .rename(columns={"_dodged": orient}) + ) + + return out + + +@dataclass +class Stack(Move): + """ + Displacement of overlapping bar or area marks along the value axis. + + Examples + -------- + .. include:: ../docstrings/objects.Stack.rst + + """ + # TODO center? (or should this be a different move, eg. Stream()) + + def _stack(self, df, orient): + + # TODO should stack do something with ymin/ymax style marks? + # Should there be an upstream conversion to baseline/height parameterization? + + if df["baseline"].nunique() > 1: + err = "Stack move cannot be used when baselines are already heterogeneous" + raise RuntimeError(err) + + other = {"x": "y", "y": "x"}[orient] + stacked_lengths = (df[other] - df["baseline"]).dropna().cumsum() + offsets = stacked_lengths.shift(1).fillna(0) + + df[other] = stacked_lengths + df["baseline"] = df["baseline"] + offsets + + return df + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + # TODO where to ensure that other semantic variables are sorted properly? + # TODO why are we not using the passed in groupby here? + groupers = ["col", "row", orient] + return GroupBy(groupers).apply(data, self._stack, orient) + + +@dataclass +class Shift(Move): + """ + Displacement of all marks with the same magnitude / direction. + + Parameters + ---------- + x, y : float + Magnitude of shift, in data units, along each axis. + + Examples + -------- + .. include:: ../docstrings/objects.Shift.rst + + """ + x: float = 0 + y: float = 0 + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + data = data.copy(deep=False) + data["x"] = data["x"] + self.x + data["y"] = data["y"] + self.y + return data + + +@dataclass +class Norm(Move): + """ + Divisive scaling on the value axis after aggregating within groups. + + Parameters + ---------- + func : str or callable + Function called on each group to define the comparison value. + where : str + Query string defining the subset used to define the comparison values. + by : list of variables + Variables used to define aggregation groups. + percent : bool + If True, multiply the result by 100. + + Examples + -------- + .. include:: ../docstrings/objects.Norm.rst + + """ + + func: Union[Callable, str] = "max" + where: Optional[str] = None + by: Optional[list[str]] = None + percent: bool = False + + group_by_orient: ClassVar[bool] = False + + def _norm(self, df, var): + + if self.where is None: + denom_data = df[var] + else: + denom_data = df.query(self.where)[var] + df[var] = df[var] / denom_data.agg(self.func) + + if self.percent: + df[var] = df[var] * 100 + + return df + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + other = {"x": "y", "y": "x"}[orient] + return groupby.apply(data, self._norm, other) + + +# TODO +# @dataclass +# class Ridge(Move): +# ... diff --git a/testbed/mwaskom__seaborn/seaborn/_core/plot.py b/testbed/mwaskom__seaborn/seaborn/_core/plot.py new file mode 100644 index 0000000000000000000000000000000000000000..79d0ef5b98aa02dea32ee6df4215102bcfa1cdb3 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/plot.py @@ -0,0 +1,1739 @@ +"""The classes for specifying and compiling a declarative visualization.""" +from __future__ import annotations + +import io +import os +import re +import sys +import inspect +import itertools +import textwrap +from contextlib import contextmanager +from collections import abc +from collections.abc import Callable, Generator +from typing import Any, List, Optional, cast + +from cycler import cycler +import pandas as pd +from pandas import DataFrame, Series, Index +import matplotlib as mpl +from matplotlib.axes import Axes +from matplotlib.artist import Artist +from matplotlib.figure import Figure + +from seaborn._marks.base import Mark +from seaborn._stats.base import Stat +from seaborn._core.data import PlotData +from seaborn._core.moves import Move +from seaborn._core.scales import Scale, Nominal +from seaborn._core.subplots import Subplots +from seaborn._core.groupby import GroupBy +from seaborn._core.properties import PROPERTIES, Property +from seaborn._core.typing import ( + DataSource, + VariableSpec, + VariableSpecList, + OrderSpec, + Default, +) +from seaborn._core.exceptions import PlotSpecError +from seaborn._core.rules import categorical_order +from seaborn._compat import set_scale_obj, set_layout_engine +from seaborn.rcmod import axes_style, plotting_context +from seaborn.palettes import color_palette +from seaborn.utils import _version_predates + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from matplotlib.figure import SubFigure + + +if sys.version_info >= (3, 8): + from typing import TypedDict +else: + from typing_extensions import TypedDict + + +default = Default() + + +# ---- Definitions for internal specs ---------------------------------------------- # + + +class Layer(TypedDict, total=False): + + mark: Mark # TODO allow list? + stat: Stat | None # TODO allow list? + move: Move | list[Move] | None + data: PlotData + source: DataSource + vars: dict[str, VariableSpec] + orient: str + legend: bool + + +class FacetSpec(TypedDict, total=False): + + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + wrap: int | None + + +class PairSpec(TypedDict, total=False): + + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + cross: bool + wrap: int | None + + +# --- Local helpers ---------------------------------------------------------------- # + + +@contextmanager +def theme_context(params: dict[str, Any]) -> Generator: + """Temporarily modify specifc matplotlib rcParams.""" + orig_params = {k: mpl.rcParams[k] for k in params} + color_codes = "bgrmyck" + nice_colors = [*color_palette("deep6"), (.15, .15, .15)] + orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes] + # TODO how to allow this to reflect the color cycle when relevant? + try: + mpl.rcParams.update(params) + for (code, color) in zip(color_codes, nice_colors): + mpl.colors.colorConverter.colors[code] = color + mpl.colors.colorConverter.cache[code] = color + yield + finally: + mpl.rcParams.update(orig_params) + for (code, color) in zip(color_codes, orig_colors): + mpl.colors.colorConverter.colors[code] = color + mpl.colors.colorConverter.cache[code] = color + + +def build_plot_signature(cls): + """ + Decorator function for giving Plot a useful signature. + + Currently this mostly saves us some duplicated typing, but we would + like eventually to have a way of registering new semantic properties, + at which point dynamic signature generation would become more important. + + """ + sig = inspect.signature(cls) + params = [ + inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL), + inspect.Parameter("data", inspect.Parameter.KEYWORD_ONLY, default=None) + ] + params.extend([ + inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None) + for name in PROPERTIES + ]) + new_sig = sig.replace(parameters=params) + cls.__signature__ = new_sig + + known_properties = textwrap.fill( + ", ".join([f"|{p}|" for p in PROPERTIES]), + width=78, subsequent_indent=" " * 8, + ) + + if cls.__doc__ is not None: # support python -OO mode + cls.__doc__ = cls.__doc__.format(known_properties=known_properties) + + return cls + + +# ---- Plot configuration ---------------------------------------------------------- # + + +class ThemeConfig(mpl.RcParams): + """ + Configuration object for the Plot.theme, using matplotlib rc parameters. + """ + THEME_GROUPS = [ + "axes", "figure", "font", "grid", "hatch", "legend", "lines", + "mathtext", "markers", "patch", "savefig", "scatter", + "xaxis", "xtick", "yaxis", "ytick", + ] + + def __init__(self): + super().__init__() + self.reset() + + @property + def _default(self) -> dict[str, Any]: + + return { + **self._filter_params(mpl.rcParamsDefault), + **axes_style("darkgrid"), + **plotting_context("notebook"), + "axes.prop_cycle": cycler("color", color_palette("deep")), + } + + def reset(self) -> None: + """Update the theme dictionary with seaborn's default values.""" + self.update(self._default) + + def update(self, other: dict[str, Any] | None = None, /, **kwds): + """Update the theme with a dictionary or keyword arguments of rc parameters.""" + if other is not None: + theme = self._filter_params(other) + else: + theme = {} + theme.update(kwds) + super().update(theme) + + def _filter_params(self, params: dict[str, Any]) -> dict[str, Any]: + """Restruct to thematic rc params.""" + return { + k: v for k, v in params.items() + if any(k.startswith(p) for p in self.THEME_GROUPS) + } + + def _html_table(self, params: dict[str, Any]) -> list[str]: + + lines = [""] + for k, v in params.items(): + row = f"" + lines.append(row) + lines.append("
{k}:{v!r}
") + return lines + + def _repr_html_(self) -> str: + + repr = [ + "
", + "
", + *self._html_table(self), + "
", + "
", + ] + return "\n".join(repr) + + +class PlotConfig: + """Configuration for default behavior / appearance of class:`Plot` instances.""" + _theme = ThemeConfig() + + @property + def theme(self) -> dict[str, Any]: + """Dictionary of base theme parameters for :class:`Plot`.""" + return self._theme + + +# ---- The main interface for declarative plotting --------------------------------- # + + +@build_plot_signature +class Plot: + """ + An interface for declaratively specifying statistical graphics. + + Plots are constructed by initializing this class and adding one or more + layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally, + faceting variables or variable pairings may be defined to divide the space + into multiple subplots. The mappings from data values to visual properties + can be parametrized using scales, although the plot will try to infer good + defaults when scales are not explicitly defined. + + The constructor accepts a data source (a :class:`pandas.DataFrame` or + dictionary with columnar values) and variable assignments. Variables can be + passed as keys to the data source or directly as data vectors. If multiple + data-containing objects are provided, they will be index-aligned. + + The data source and variables defined in the constructor will be used for + all layers in the plot, unless overridden or disabled when adding a layer. + + The following variables can be defined in the constructor: + {known_properties} + + The `data`, `x`, and `y` variables can be passed as positional arguments or + using keywords. Whether the first positional argument is interpreted as a + data source or `x` variable depends on its type. + + The methods of this class return a copy of the instance; use chaining to + build up a plot through multiple calls. Methods can be called in any order. + + Most methods only add information to the plot spec; no actual processing + happens until the plot is shown or saved. It is also possible to compile + the plot without rendering it to access the lower-level representation. + + """ + config = PlotConfig() + + _data: PlotData + _layers: list[Layer] + + _scales: dict[str, Scale] + _shares: dict[str, bool | str] + _limits: dict[str, tuple[Any, Any]] + _labels: dict[str, str | Callable[[str], str]] + _theme: dict[str, Any] + + _facet_spec: FacetSpec + _pair_spec: PairSpec + + _figure_spec: dict[str, Any] + _subplot_spec: dict[str, Any] + _layout_spec: dict[str, Any] + + def __init__( + self, + *args: DataSource | VariableSpec, + data: DataSource = None, + **variables: VariableSpec, + ): + + if args: + data, variables = self._resolve_positionals(args, data, variables) + + unknown = [x for x in variables if x not in PROPERTIES] + if unknown: + err = f"Plot() got unexpected keyword argument(s): {', '.join(unknown)}" + raise TypeError(err) + + self._data = PlotData(data, variables) + + self._layers = [] + + self._scales = {} + self._shares = {} + self._limits = {} + self._labels = {} + self._theme = {} + + self._facet_spec = {} + self._pair_spec = {} + + self._figure_spec = {} + self._subplot_spec = {} + self._layout_spec = {} + + self._target = None + + def _resolve_positionals( + self, + args: tuple[DataSource | VariableSpec, ...], + data: DataSource, + variables: dict[str, VariableSpec], + ) -> tuple[DataSource, dict[str, VariableSpec]]: + """Handle positional arguments, which may contain data / x / y.""" + if len(args) > 3: + err = "Plot() accepts no more than 3 positional arguments (data, x, y)." + raise TypeError(err) + + # TODO need some clearer way to differentiate data / vector here + # (There might be an abstract DataFrame class to use here?) + if isinstance(args[0], (abc.Mapping, pd.DataFrame)): + if data is not None: + raise TypeError("`data` given by both name and position.") + data, args = args[0], args[1:] + + if len(args) == 2: + x, y = args + elif len(args) == 1: + x, y = *args, None + else: + x = y = None + + for name, var in zip("yx", (y, x)): + if var is not None: + if name in variables: + raise TypeError(f"`{name}` given by both name and position.") + # Keep coordinates at the front of the variables dict + # Cast type because we know this isn't a DataSource at this point + variables = {name: cast(VariableSpec, var), **variables} + + return data, variables + + def __add__(self, other): + + if isinstance(other, Mark) or isinstance(other, Stat): + raise TypeError("Sorry, this isn't ggplot! Perhaps try Plot.add?") + + other_type = other.__class__.__name__ + raise TypeError(f"Unsupported operand type(s) for +: 'Plot' and '{other_type}") + + def _repr_png_(self) -> tuple[bytes, dict[str, float]]: + + return self.plot()._repr_png_() + + # TODO _repr_svg_? + + def _clone(self) -> Plot: + """Generate a new object with the same information as the current spec.""" + new = Plot() + + # TODO any way to enforce that data does not get mutated? + new._data = self._data + + new._layers.extend(self._layers) + + new._scales.update(self._scales) + new._shares.update(self._shares) + new._limits.update(self._limits) + new._labels.update(self._labels) + new._theme.update(self._theme) + + new._facet_spec.update(self._facet_spec) + new._pair_spec.update(self._pair_spec) + + new._figure_spec.update(self._figure_spec) + new._subplot_spec.update(self._subplot_spec) + new._layout_spec.update(self._layout_spec) + + new._target = self._target + + return new + + def _theme_with_defaults(self) -> dict[str, Any]: + + theme = self.config.theme.copy() + theme.update(self._theme) + return theme + + @property + def _variables(self) -> list[str]: + + variables = ( + list(self._data.frame) + + list(self._pair_spec.get("variables", [])) + + list(self._facet_spec.get("variables", [])) + ) + for layer in self._layers: + variables.extend(v for v in layer["vars"] if v not in variables) + + # Coerce to str in return to appease mypy; we know these will only + # ever be strings but I don't think we can type a DataFrame that way yet + return [str(v) for v in variables] + + def on(self, target: Axes | SubFigure | Figure) -> Plot: + """ + Provide existing Matplotlib figure or axes for drawing the plot. + + When using this method, you will also need to explicitly call a method that + triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you + want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot` + first to compile the plot without rendering it. + + Parameters + ---------- + target : Axes, SubFigure, or Figure + Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add + artists without otherwise modifying the figure. Otherwise, subplots will be + created within the space of the given :class:`matplotlib.figure.Figure` or + :class:`matplotlib.figure.SubFigure`. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.on.rst + + """ + accepted_types: tuple # Allow tuple of various length + if hasattr(mpl.figure, "SubFigure"): # Added in mpl 3.4 + accepted_types = ( + mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure + ) + accepted_types_str = ( + f"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}" + ) + else: + accepted_types = mpl.axes.Axes, mpl.figure.Figure + accepted_types_str = f"{mpl.axes.Axes} or {mpl.figure.Figure}" + + if not isinstance(target, accepted_types): + err = ( + f"The `Plot.on` target must be an instance of {accepted_types_str}. " + f"You passed an instance of {target.__class__} instead." + ) + raise TypeError(err) + + new = self._clone() + new._target = target + + return new + + def add( + self, + mark: Mark, + *transforms: Stat | Mark, + orient: str | None = None, + legend: bool = True, + data: DataSource = None, + **variables: VariableSpec, + ) -> Plot: + """ + Specify a layer of the visualization in terms of mark and data transform(s). + + This is the main method for specifying how the data should be visualized. + It can be called multiple times with different arguments to define + a plot with multiple layers. + + Parameters + ---------- + mark : :class:`Mark` + The visual representation of the data to use in this layer. + transforms : :class:`Stat` or :class:`Move` + Objects representing transforms to be applied before plotting the data. + Currently, at most one :class:`Stat` can be used, and it + must be passed first. This constraint will be relaxed in the future. + orient : "x", "y", "v", or "h" + The orientation of the mark, which also affects how transforms are computed. + Typically corresponds to the axis that defines groups for aggregation. + The "v" (vertical) and "h" (horizontal) options are synonyms for "x" / "y", + but may be more intuitive with some marks. When not provided, an + orientation will be inferred from characteristics of the data and scales. + legend : bool + Option to suppress the mark/mappings for this layer from the legend. + data : DataFrame or dict + Data source to override the global source provided in the constructor. + variables : data vectors or identifiers + Additional layer-specific variables, including variables that will be + passed directly to the transforms without scaling. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.add.rst + + """ + if not isinstance(mark, Mark): + msg = f"mark must be a Mark instance, not {type(mark)!r}." + raise TypeError(msg) + + # TODO This API for transforms was a late decision, and previously Plot.add + # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances. + # It will take some work to refactor the internals so that Stat and Move are + # treated identically, and until then well need to "unpack" the transforms + # here and enforce limitations on the order / types. + + stat: Optional[Stat] + move: Optional[List[Move]] + error = False + if not transforms: + stat, move = None, None + elif isinstance(transforms[0], Stat): + stat = transforms[0] + move = [m for m in transforms[1:] if isinstance(m, Move)] + error = len(move) != len(transforms) - 1 + else: + stat = None + move = [m for m in transforms if isinstance(m, Move)] + error = len(move) != len(transforms) + + if error: + msg = " ".join([ + "Transforms must have at most one Stat type (in the first position),", + "and all others must be a Move type. Given transform type(s):", + ", ".join(str(type(t).__name__) for t in transforms) + "." + ]) + raise TypeError(msg) + + new = self._clone() + new._layers.append({ + "mark": mark, + "stat": stat, + "move": move, + # TODO it doesn't work to supply scalars to variables, but it should + "vars": variables, + "source": data, + "legend": legend, + "orient": {"v": "x", "h": "y"}.get(orient, orient), # type: ignore + }) + + return new + + def pair( + self, + x: VariableSpecList = None, + y: VariableSpecList = None, + wrap: int | None = None, + cross: bool = True, + ) -> Plot: + """ + Produce subplots by pairing multiple `x` and/or `y` variables. + + Parameters + ---------- + x, y : sequence(s) of data vectors or identifiers + Variables that will define the grid of subplots. + wrap : int + When using only `x` or `y`, "wrap" subplots across a two-dimensional grid + with this many columns (when using `x`) or rows (when using `y`). + cross : bool + When False, zip the `x` and `y` lists such that the first subplot gets the + first pair, the second gets the second pair, etc. Otherwise, create a + two-dimensional grid from the cartesian product of the lists. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.pair.rst + + """ + # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows + # This may also be possible by setting `wrap=1`, but is that too unobvious? + # TODO PairGrid features not currently implemented: diagonals, corner + + pair_spec: PairSpec = {} + + axes = {"x": [] if x is None else x, "y": [] if y is None else y} + for axis, arg in axes.items(): + if isinstance(arg, (str, int)): + err = f"You must pass a sequence of variable keys to `{axis}`" + raise TypeError(err) + + pair_spec["variables"] = {} + pair_spec["structure"] = {} + + for axis in "xy": + keys = [] + for i, col in enumerate(axes[axis]): + key = f"{axis}{i}" + keys.append(key) + pair_spec["variables"][key] = col + + if keys: + pair_spec["structure"][axis] = keys + + if not cross and len(axes["x"]) != len(axes["y"]): + err = "Lengths of the `x` and `y` lists must match with cross=False" + raise ValueError(err) + + pair_spec["cross"] = cross + pair_spec["wrap"] = wrap + + new = self._clone() + new._pair_spec.update(pair_spec) + return new + + def facet( + self, + col: VariableSpec = None, + row: VariableSpec = None, + order: OrderSpec | dict[str, OrderSpec] = None, + wrap: int | None = None, + ) -> Plot: + """ + Produce subplots with conditional subsets of the data. + + Parameters + ---------- + col, row : data vectors or identifiers + Variables used to define subsets along the columns and/or rows of the grid. + Can be references to the global data source passed in the constructor. + order : list of strings, or dict with dimensional keys + Define the order of the faceting variables. + wrap : int + When using only `col` or `row`, wrap subplots across a two-dimensional + grid with this many subplots on the faceting dimension. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.facet.rst + + """ + variables: dict[str, VariableSpec] = {} + if col is not None: + variables["col"] = col + if row is not None: + variables["row"] = row + + structure = {} + if isinstance(order, dict): + for dim in ["col", "row"]: + dim_order = order.get(dim) + if dim_order is not None: + structure[dim] = list(dim_order) + elif order is not None: + if col is not None and row is not None: + err = " ".join([ + "When faceting on both col= and row=, passing `order` as a list" + "is ambiguous. Use a dict with 'col' and/or 'row' keys instead." + ]) + raise RuntimeError(err) + elif col is not None: + structure["col"] = list(order) + elif row is not None: + structure["row"] = list(order) + + spec: FacetSpec = { + "variables": variables, + "structure": structure, + "wrap": wrap, + } + + new = self._clone() + new._facet_spec.update(spec) + + return new + + # TODO def twin()? + + def scale(self, **scales: Scale) -> Plot: + """ + Specify mappings from data units to visual properties. + + Keywords correspond to variables defined in the plot, including coordinate + variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.). + + A number of "magic" arguments are accepted, including: + - The name of a transform (e.g., `"log"`, `"sqrt"`) + - The name of a palette (e.g., `"viridis"`, `"muted"`) + - A tuple of values, defining the output range (e.g. `(1, 5)`) + - A dict, implying a :class:`Nominal` scale (e.g. `{"a": .2, "b": .5}`) + - A list of values, implying a :class:`Nominal` scale (e.g. `["b", "r"]`) + + For more explicit control, pass a scale spec object such as :class:`Continuous` + or :class:`Nominal`. Or pass `None` to use an "identity" scale, which treats + data values as literally encoding visual properties. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.scale.rst + + """ + new = self._clone() + new._scales.update(scales) + return new + + def share(self, **shares: bool | str) -> Plot: + """ + Control sharing of axis limits and ticks across subplots. + + Keywords correspond to variables defined in the plot, and values can be + boolean (to share across all subplots), or one of "row" or "col" (to share + more selectively across one dimension of a grid). + + Behavior for non-coordinate variables is currently undefined. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.share.rst + + """ + new = self._clone() + new._shares.update(shares) + return new + + def limit(self, **limits: tuple[Any, Any]) -> Plot: + """ + Control the range of visible data. + + Keywords correspond to variables defined in the plot, and values are a + `(min, max)` tuple (where either can be `None` to leave unset). + + Limits apply only to the axis; data outside the visible range are + still used for any stat transforms and added to the plot. + + Behavior for non-coordinate variables is currently undefined. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.limit.rst + + """ + new = self._clone() + new._limits.update(limits) + return new + + def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot: + """ + Control the labels and titles for axes, legends, and subplots. + + Additional keywords correspond to variables defined in the plot. + Values can be one of the following types: + + - string (used literally; pass "" to clear the default label) + - function (called on the default label) + + For coordinate variables, the value sets the axis label. + For semantic variables, the value sets the legend title. + For faceting variables, `title=` modifies the subplot-specific label, + while `col=` and/or `row=` add a label for the faceting variable. + When using a single subplot, `title=` sets its title. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.label.rst + + + """ + new = self._clone() + if title is not None: + new._labels["title"] = title + new._labels.update(variables) + return new + + def layout( + self, + *, + size: tuple[float, float] | Default = default, + engine: str | None | Default = default, + ) -> Plot: + """ + Control the figure size and layout. + + .. note:: + + Default figure sizes and the API for specifying the figure size are subject + to change in future "experimental" releases of the objects API. The default + layout engine may also change. + + Parameters + ---------- + size : (width, height) + Size of the resulting figure, in inches. Size is inclusive of legend when + using pyplot, but not otherwise. + engine : {{"tight", "constrained", None}} + Name of method for automatically adjusting the layout to remove overlap. + The default depends on whether :meth:`Plot.on` is used. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.layout.rst + + """ + # TODO add an "auto" mode for figsize that roughly scales with the rcParams + # figsize (so that works), but expands to prevent subplots from being squished + # Also should we have height=, aspect=, exclusive with figsize? Or working + # with figsize when only one is defined? + + new = self._clone() + + if size is not default: + new._figure_spec["figsize"] = size + if engine is not default: + new._layout_spec["engine"] = engine + + return new + + # TODO def legend (ugh) + + def theme(self, *args: dict[str, Any]) -> Plot: + """ + Control the appearance of elements in the plot. + + .. note:: + + The API for customizing plot appearance is not yet finalized. + Currently, the only valid argument is a dict of matplotlib rc parameters. + (This dict must be passed as a positional argument.) + + It is likely that this method will be enhanced in future releases. + + Matplotlib rc parameters are documented on the following page: + https://matplotlib.org/stable/tutorials/introductory/customizing.html + + Examples + -------- + .. include:: ../docstrings/objects.Plot.theme.rst + + """ + new = self._clone() + + # We can skip this whole block on Python 3.8+ with positional-only syntax + nargs = len(args) + if nargs != 1: + err = f"theme() takes 1 positional argument, but {nargs} were given" + raise TypeError(err) + + rc = mpl.RcParams(args[0]) + new._theme.update(rc) + + return new + + def save(self, loc, **kwargs) -> Plot: + """ + Compile the plot and write it to a buffer or file on disk. + + Parameters + ---------- + loc : str, path, or buffer + Location on disk to save the figure, or a buffer to write into. + kwargs + Other keyword arguments are passed through to + :meth:`matplotlib.figure.Figure.savefig`. + + """ + # TODO expose important keyword arguments in our signature? + with theme_context(self._theme_with_defaults()): + self._plot().save(loc, **kwargs) + return self + + def show(self, **kwargs) -> None: + """ + Compile the plot and display it by hooking into pyplot. + + Calling this method is not necessary to render a plot in notebook context, + but it may be in other environments (e.g., in a terminal). After compiling the + plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters). + + Unlike other :class:`Plot` methods, there is no return value. This should be + the last method you call when specifying a plot. + + """ + # TODO make pyplot configurable at the class level, and when not using, + # import IPython.display and call on self to populate cell output? + + # Keep an eye on whether matplotlib implements "attaching" an existing + # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024 + + self.plot(pyplot=True).show(**kwargs) + + def plot(self, pyplot: bool = False) -> Plotter: + """ + Compile the plot spec and return the Plotter object. + """ + with theme_context(self._theme_with_defaults()): + return self._plot(pyplot) + + def _plot(self, pyplot: bool = False) -> Plotter: + + # TODO if we have _target object, pyplot should be determined by whether it + # is hooked into the pyplot state machine (how do we check?) + + plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults()) + + # Process the variable assignments and initialize the figure + common, layers = plotter._extract_data(self) + plotter._setup_figure(self, common, layers) + + # Process the scale spec for coordinate variables and transform their data + coord_vars = [v for v in self._variables if re.match(r"^x|y", v)] + plotter._setup_scales(self, common, layers, coord_vars) + + # Apply statistical transform(s) + plotter._compute_stats(self, layers) + + # Process scale spec for semantic variables and coordinates computed by stat + plotter._setup_scales(self, common, layers) + + # TODO Remove these after updating other methods + # ---- Maybe have debug= param that attaches these when True? + plotter._data = common + plotter._layers = layers + + # Process the data for each layer and add matplotlib artists + for layer in layers: + plotter._plot_layer(self, layer) + + # Add various figure decorations + plotter._make_legend(self) + plotter._finalize_figure(self) + + return plotter + + +# ---- The plot compilation engine ---------------------------------------------- # + + +class Plotter: + """ + Engine for compiling a :class:`Plot` spec into a Matplotlib figure. + + This class is not intended to be instantiated directly by users. + + """ + # TODO decide if we ever want these (Plot.plot(debug=True))? + _data: PlotData + _layers: list[Layer] + _figure: Figure + + def __init__(self, pyplot: bool, theme: dict[str, Any]): + + self._pyplot = pyplot + self._theme = theme + self._legend_contents: list[tuple[ + tuple[str, str | int], list[Artist], list[str], + ]] = [] + self._scales: dict[str, Scale] = {} + + def save(self, loc, **kwargs) -> Plotter: # TODO type args + kwargs.setdefault("dpi", 96) + try: + loc = os.path.expanduser(loc) + except TypeError: + # loc may be a buffer in which case that would not work + pass + self._figure.savefig(loc, **kwargs) + return self + + def show(self, **kwargs) -> None: + """ + Display the plot by hooking into pyplot. + + This method calls :func:`matplotlib.pyplot.show` with any keyword parameters. + + """ + # TODO if we did not create the Plotter with pyplot, is it possible to do this? + # If not we should clearly raise. + import matplotlib.pyplot as plt + with theme_context(self._theme): + plt.show(**kwargs) + + # TODO API for accessing the underlying matplotlib objects + # TODO what else is useful in the public API for this class? + + def _repr_png_(self) -> tuple[bytes, dict[str, float]]: + + # TODO better to do this through a Jupyter hook? e.g. + # ipy = IPython.core.formatters.get_ipython() + # fmt = ipy.display_formatter.formatters["text/html"] + # fmt.for_type(Plot, ...) + # Would like to have a svg option too, not sure how to make that flexible + + # TODO use matplotlib backend directly instead of going through savefig? + + # TODO perhaps have self.show() flip a switch to disable this, so that + # user does not end up with two versions of the figure in the output + + # TODO use bbox_inches="tight" like the inline backend? + # pro: better results, con: (sometimes) confusing results + # Better solution would be to default (with option to change) + # to using constrained/tight layout. + + # TODO need to decide what the right default behavior here is: + # - Use dpi=72 to match default InlineBackend figure size? + # - Accept a generic "scaling" somewhere and scale DPI from that, + # either with 1x -> 72 or 1x -> 96 and the default scaling be .75? + # - Listen to rcParams? InlineBackend behavior makes that so complicated :( + # - Do we ever want to *not* use retina mode at this point? + + from PIL import Image + + dpi = 96 + buffer = io.BytesIO() + + with theme_context(self._theme): # TODO _theme_with_defaults? + self._figure.savefig(buffer, dpi=dpi * 2, format="png", bbox_inches="tight") + data = buffer.getvalue() + + scaling = .85 / 2 + w, h = Image.open(buffer).size + metadata = {"width": w * scaling, "height": h * scaling} + return data, metadata + + def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]: + + common_data = ( + p._data + .join(None, p._facet_spec.get("variables")) + .join(None, p._pair_spec.get("variables")) + ) + + layers: list[Layer] = [] + for layer in p._layers: + spec = layer.copy() + spec["data"] = common_data.join(layer.get("source"), layer.get("vars")) + layers.append(spec) + + return common_data, layers + + def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str: + + label: str + if var in p._labels: + manual_label = p._labels[var] + if callable(manual_label) and auto_label is not None: + label = manual_label(auto_label) + else: + label = cast(str, manual_label) + elif auto_label is None: + label = "" + else: + label = auto_label + return label + + def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None: + + # --- Parsing the faceting/pairing parameterization to specify figure grid + + subplot_spec = p._subplot_spec.copy() + facet_spec = p._facet_spec.copy() + pair_spec = p._pair_spec.copy() + + for axis in "xy": + if axis in p._shares: + subplot_spec[f"share{axis}"] = p._shares[axis] + + for dim in ["col", "row"]: + if dim in common.frame and dim not in facet_spec["structure"]: + order = categorical_order(common.frame[dim]) + facet_spec["structure"][dim] = order + + self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec) + + # --- Figure initialization + self._figure = subplots.init_figure( + pair_spec, self._pyplot, p._figure_spec, p._target, + ) + + # --- Figure annotation + for sub in subplots: + ax = sub["ax"] + for axis in "xy": + axis_key = sub[axis] + + # ~~ Axis labels + + # TODO Should we make it possible to use only one x/y label for + # all rows/columns in a faceted plot? Maybe using sub{axis}label, + # although the alignments of the labels from that method leaves + # something to be desired (in terms of how it defines 'centered'). + names = [ + common.names.get(axis_key), + *(layer["data"].names.get(axis_key) for layer in layers) + ] + auto_label = next((name for name in names if name is not None), None) + label = self._resolve_label(p, axis_key, auto_label) + ax.set(**{f"{axis}label": label}) + + # ~~ Decoration visibility + + # TODO there should be some override (in Plot.layout?) so that + # axis / tick labels can be shown on interior shared axes if desired + + axis_obj = getattr(ax, f"{axis}axis") + visible_side = {"x": "bottom", "y": "left"}.get(axis) + show_axis_label = ( + sub[visible_side] + or not p._pair_spec.get("cross", True) + or ( + axis in p._pair_spec.get("structure", {}) + and bool(p._pair_spec.get("wrap")) + ) + ) + axis_obj.get_label().set_visible(show_axis_label) + + show_tick_labels = ( + show_axis_label + or subplot_spec.get(f"share{axis}") not in ( + True, "all", {"x": "col", "y": "row"}[axis] + ) + ) + for group in ("major", "minor"): + for t in getattr(axis_obj, f"get_{group}ticklabels")(): + t.set_visible(show_tick_labels) + + # TODO we want right-side titles for row facets in most cases? + # Let's have what we currently call "margin titles" but properly using the + # ax.set_title interface (see my gist) + title_parts = [] + for dim in ["col", "row"]: + if sub[dim] is not None: + val = self._resolve_label(p, "title", f"{sub[dim]}") + if dim in p._labels: + key = self._resolve_label(p, dim, common.names.get(dim)) + val = f"{key} {val}" + title_parts.append(val) + + has_col = sub["col"] is not None + has_row = sub["row"] is not None + show_title = ( + has_col and has_row + or (has_col or has_row) and p._facet_spec.get("wrap") + or (has_col and sub["top"]) + # TODO or has_row and sub["right"] and + or has_row # TODO and not + ) + if title_parts: + title = " | ".join(title_parts) + title_text = ax.set_title(title) + title_text.set_visible(show_title) + elif not (has_col or has_row): + title = self._resolve_label(p, "title", None) + title_text = ax.set_title(title) + + def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None: + + grouping_vars = [v for v in PROPERTIES if v not in "xy"] + grouping_vars += ["col", "row", "group"] + + pair_vars = spec._pair_spec.get("structure", {}) + + for layer in layers: + + data = layer["data"] + mark = layer["mark"] + stat = layer["stat"] + + if stat is None: + continue + + iter_axes = itertools.product(*[ + pair_vars.get(axis, [axis]) for axis in "xy" + ]) + + old = data.frame + + if pair_vars: + data.frames = {} + data.frame = data.frame.iloc[:0] # TODO to simplify typing + + for coord_vars in iter_axes: + + pairings = "xy", coord_vars + + df = old.copy() + scales = self._scales.copy() + + for axis, var in zip(*pairings): + if axis != var: + df = df.rename(columns={var: axis}) + drop_cols = [x for x in df if re.match(rf"{axis}\d+", str(x))] + df = df.drop(drop_cols, axis=1) + scales[axis] = scales[var] + + orient = layer["orient"] or mark._infer_orient(scales) + + if stat.group_by_orient: + grouper = [orient, *grouping_vars] + else: + grouper = grouping_vars + groupby = GroupBy(grouper) + res = stat(df, groupby, orient, scales) + + if pair_vars: + data.frames[coord_vars] = res + else: + data.frame = res + + def _get_scale( + self, spec: Plot, var: str, prop: Property, values: Series + ) -> Scale: + + if var in spec._scales: + arg = spec._scales[var] + if arg is None or isinstance(arg, Scale): + scale = arg + else: + scale = prop.infer_scale(arg, values) + else: + scale = prop.default_scale(values) + + return scale + + def _get_subplot_data(self, df, var, view, share_state): + + if share_state in [True, "all"]: + # The all-shared case is easiest, every subplot sees all the data + seed_values = df[var] + else: + # Otherwise, we need to setup separate scales for different subplots + if share_state in [False, "none"]: + # Fully independent axes are also easy: use each subplot's data + idx = self._get_subplot_index(df, view) + elif share_state in df: + # Sharing within row/col is more complicated + use_rows = df[share_state] == view[share_state] + idx = df.index[use_rows] + else: + # This configuration doesn't make much sense, but it's fine + idx = df.index + + seed_values = df.loc[idx, var] + + return seed_values + + def _setup_scales( + self, p: Plot, + common: PlotData, + layers: list[Layer], + variables: list[str] | None = None, + ) -> None: + + if variables is None: + # Add variables that have data but not a scale, which happens + # because this method can be called multiple time, to handle + # variables added during the Stat transform. + variables = [] + for layer in layers: + variables.extend(layer["data"].frame.columns) + for df in layer["data"].frames.values(): + variables.extend(str(v) for v in df if v not in variables) + variables = [v for v in variables if v not in self._scales] + + for var in variables: + + # Determine whether this is a coordinate variable + # (i.e., x/y, paired x/y, or derivative such as xmax) + m = re.match(r"^(?P(?Px|y)\d*).*", var) + if m is None: + coord = axis = None + else: + coord = m["coord"] + axis = m["axis"] + + # Get keys that handle things like x0, xmax, properly where relevant + prop_key = var if axis is None else axis + scale_key = var if coord is None else coord + + if prop_key not in PROPERTIES: + continue + + # Concatenate layers, using only the relevant coordinate and faceting vars, + # This is unnecessarily wasteful, as layer data will often be redundant. + # But figuring out the minimal amount we need is more complicated. + cols = [var, "col", "row"] + parts = [common.frame.filter(cols)] + for layer in layers: + parts.append(layer["data"].frame.filter(cols)) + for df in layer["data"].frames.values(): + parts.append(df.filter(cols)) + var_df = pd.concat(parts, ignore_index=True) + + prop = PROPERTIES[prop_key] + scale = self._get_scale(p, scale_key, prop, var_df[var]) + + if scale_key not in p._variables: + # TODO this implies that the variable was added by the stat + # It allows downstream orientation inference to work properly. + # But it feels rather hacky, so ideally revisit. + scale._priority = 0 # type: ignore + + if axis is None: + # We could think about having a broader concept of (un)shared properties + # In general, not something you want to do (different scales in facets) + # But could make sense e.g. with paired plots. Build later. + share_state = None + subplots = [] + else: + share_state = self._subplots.subplot_spec[f"share{axis}"] + subplots = [view for view in self._subplots if view[axis] == coord] + + # Shared categorical axes are broken on matplotlib<3.4.0. + # https://github.com/matplotlib/matplotlib/pull/18308 + # This only affects us when sharing *paired* axes. This is a novel/niche + # behavior, so we will raise rather than hack together a workaround. + if axis is not None and _version_predates(mpl, "3.4"): + paired_axis = axis in p._pair_spec.get("structure", {}) + cat_scale = isinstance(scale, Nominal) + ok_dim = {"x": "col", "y": "row"}[axis] + shared_axes = share_state not in [False, "none", ok_dim] + if paired_axis and cat_scale and shared_axes: + err = "Sharing paired categorical axes requires matplotlib>=3.4.0" + raise RuntimeError(err) + + if scale is None: + self._scales[var] = Scale._identity() + else: + try: + self._scales[var] = scale._setup(var_df[var], prop) + except Exception as err: + raise PlotSpecError._during("Scale setup", var) from err + + if axis is None or (var != coord and coord in p._variables): + # Everything below here applies only to coordinate variables + continue + + # Set up an empty series to receive the transformed values. + # We need this to handle piecemeal transforms of categories -> floats. + transformed_data = [] + for layer in layers: + index = layer["data"].frame.index + empty_series = pd.Series(dtype=float, index=index, name=var) + transformed_data.append(empty_series) + + for view in subplots: + + axis_obj = getattr(view["ax"], f"{axis}axis") + seed_values = self._get_subplot_data(var_df, var, view, share_state) + view_scale = scale._setup(seed_values, prop, axis=axis_obj) + set_scale_obj(view["ax"], axis, view_scale._matplotlib_scale) + + for layer, new_series in zip(layers, transformed_data): + layer_df = layer["data"].frame + if var not in layer_df: + continue + + idx = self._get_subplot_index(layer_df, view) + try: + new_series.loc[idx] = view_scale(layer_df.loc[idx, var]) + except Exception as err: + spec_error = PlotSpecError._during("Scaling operation", var) + raise spec_error from err + + # Now the transformed data series are complete, set update the layer data + for layer, new_series in zip(layers, transformed_data): + layer_df = layer["data"].frame + if var in layer_df: + layer_df[var] = new_series + + def _plot_layer(self, p: Plot, layer: Layer) -> None: + + data = layer["data"] + mark = layer["mark"] + move = layer["move"] + + default_grouping_vars = ["col", "row", "group"] # TODO where best to define? + grouping_properties = [v for v in PROPERTIES if v[0] not in "xy"] + + pair_variables = p._pair_spec.get("structure", {}) + + for subplots, df, scales in self._generate_pairings(data, pair_variables): + + orient = layer["orient"] or mark._infer_orient(scales) + + def get_order(var): + # Ignore order for x/y: they have been scaled to numeric indices, + # so any original order is no longer valid. Default ordering rules + # sorted unique numbers will correctly reconstruct intended order + # TODO This is tricky, make sure we add some tests for this + if var not in "xy" and var in scales: + return getattr(scales[var], "order", None) + + if orient in df: + width = pd.Series(index=df.index, dtype=float) + for view in subplots: + view_idx = self._get_subplot_data( + df, orient, view, p._shares.get(orient) + ).index + view_df = df.loc[view_idx] + if "width" in mark._mappable_props: + view_width = mark._resolve(view_df, "width", None) + elif "width" in df: + view_width = view_df["width"] + else: + view_width = 0.8 # TODO what default? + spacing = scales[orient]._spacing(view_df.loc[view_idx, orient]) + width.loc[view_idx] = view_width * spacing + df["width"] = width + + if "baseline" in mark._mappable_props: + # TODO what marks should have this? + # If we can set baseline with, e.g., Bar(), then the + # "other" (e.g. y for x oriented bars) parameterization + # is somewhat ambiguous. + baseline = mark._resolve(df, "baseline", None) + else: + # TODO unlike width, we might not want to add baseline to data + # if the mark doesn't use it. Practically, there is a concern about + # Mark abstraction like Area / Ribbon + baseline = 0 if "baseline" not in df else df["baseline"] + df["baseline"] = baseline + + if move is not None: + moves = move if isinstance(move, list) else [move] + for move_step in moves: + move_by = getattr(move_step, "by", None) + if move_by is None: + move_by = grouping_properties + move_groupers = [*move_by, *default_grouping_vars] + if move_step.group_by_orient: + move_groupers.insert(0, orient) + order = {var: get_order(var) for var in move_groupers} + groupby = GroupBy(order) + df = move_step(df, groupby, orient, scales) + + df = self._unscale_coords(subplots, df, orient) + + grouping_vars = mark._grouping_props + default_grouping_vars + split_generator = self._setup_split_generator(grouping_vars, df, subplots) + + mark._plot(split_generator, scales, orient) + + # TODO is this the right place for this? + for view in self._subplots: + view["ax"].autoscale_view() + + if layer["legend"]: + self._update_legend_contents(p, mark, data, scales) + + def _unscale_coords( + self, subplots: list[dict], df: DataFrame, orient: str, + ) -> DataFrame: + # TODO do we still have numbers in the variable name at this point? + coord_cols = [c for c in df if re.match(r"^[xy]\D*$", str(c))] + drop_cols = [*coord_cols, "width"] if "width" in df else coord_cols + out_df = ( + df + .drop(drop_cols, axis=1) + .reindex(df.columns, axis=1) # So unscaled columns retain their place + .copy(deep=False) + ) + + for view in subplots: + view_df = self._filter_subplot_data(df, view) + axes_df = view_df[coord_cols] + for var, values in axes_df.items(): + + axis = getattr(view["ax"], f"{str(var)[0]}axis") + # TODO see https://github.com/matplotlib/matplotlib/issues/22713 + transform = axis.get_transform().inverted().transform + inverted = transform(values) + out_df.loc[values.index, str(var)] = inverted + + if var == orient and "width" in view_df: + width = view_df["width"] + out_df.loc[values.index, "width"] = ( + transform(values + width / 2) - transform(values - width / 2) + ) + + return out_df + + def _generate_pairings( + self, data: PlotData, pair_variables: dict, + ) -> Generator[ + tuple[list[dict], DataFrame, dict[str, Scale]], None, None + ]: + # TODO retype return with subplot_spec or similar + + iter_axes = itertools.product(*[ + pair_variables.get(axis, [axis]) for axis in "xy" + ]) + + for x, y in iter_axes: + + subplots = [] + for view in self._subplots: + if (view["x"] == x) and (view["y"] == y): + subplots.append(view) + + if data.frame.empty and data.frames: + out_df = data.frames[(x, y)].copy() + elif not pair_variables: + out_df = data.frame.copy() + else: + if data.frame.empty and data.frames: + out_df = data.frames[(x, y)].copy() + else: + out_df = data.frame.copy() + + scales = self._scales.copy() + if x in out_df: + scales["x"] = self._scales[x] + if y in out_df: + scales["y"] = self._scales[y] + + for axis, var in zip("xy", (x, y)): + if axis != var: + out_df = out_df.rename(columns={var: axis}) + cols = [col for col in out_df if re.match(rf"{axis}\d+", str(col))] + out_df = out_df.drop(cols, axis=1) + + yield subplots, out_df, scales + + def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index: + + dims = df.columns.intersection(["col", "row"]) + if dims.empty: + return df.index + + keep_rows = pd.Series(True, df.index, dtype=bool) + for dim in dims: + keep_rows &= df[dim] == subplot[dim] + return df.index[keep_rows] + + def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame: + # TODO note redundancies with preceding function ... needs refactoring + dims = df.columns.intersection(["col", "row"]) + if dims.empty: + return df + + keep_rows = pd.Series(True, df.index, dtype=bool) + for dim in dims: + keep_rows &= df[dim] == subplot[dim] + return df[keep_rows] + + def _setup_split_generator( + self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]], + ) -> Callable[[], Generator]: + + grouping_keys = [] + grouping_vars = [ + v for v in grouping_vars if v in df and v not in ["col", "row"] + ] + for var in grouping_vars: + order = getattr(self._scales[var], "order", None) + if order is None: + order = categorical_order(df[var]) + grouping_keys.append(order) + + def split_generator(keep_na=False) -> Generator: + + for view in subplots: + + axes_df = self._filter_subplot_data(df, view) + + with pd.option_context("mode.use_inf_as_na", True): + if keep_na: + # The simpler thing to do would be x.dropna().reindex(x.index). + # But that doesn't work with the way that the subset iteration + # is written below, which assumes data for grouping vars. + # Matplotlib (usually?) masks nan data, so this should "work". + # Downstream code can also drop these rows, at some speed cost. + present = axes_df.notna().all(axis=1) + nulled = {} + for axis in "xy": + if axis in axes_df: + nulled[axis] = axes_df[axis].where(present) + axes_df = axes_df.assign(**nulled) + else: + axes_df = axes_df.dropna() + + subplot_keys = {} + for dim in ["col", "row"]: + if view[dim] is not None: + subplot_keys[dim] = view[dim] + + if not grouping_vars or not any(grouping_keys): + if not axes_df.empty: + yield subplot_keys, axes_df.copy(), view["ax"] + continue + + grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False) + + for key in itertools.product(*grouping_keys): + + # Pandas fails with singleton tuple inputs + pd_key = key[0] if len(key) == 1 else key + + try: + df_subset = grouped_df.get_group(pd_key) + except KeyError: + # TODO (from initial work on categorical plots refactor) + # We are adding this to allow backwards compatability + # with the empty artists that old categorical plots would + # add (before 0.12), which we may decide to break, in which + # case this option could be removed + df_subset = axes_df.loc[[]] + + if df_subset.empty: + continue + + sub_vars = dict(zip(grouping_vars, key)) + sub_vars.update(subplot_keys) + + # TODO need copy(deep=...) policy (here, above, anywhere else?) + yield sub_vars, df_subset.copy(), view["ax"] + + return split_generator + + def _update_legend_contents( + self, + p: Plot, + mark: Mark, + data: PlotData, + scales: dict[str, Scale], + ) -> None: + """Add legend artists / labels for one layer in the plot.""" + if data.frame.empty and data.frames: + legend_vars: list[str] = [] + for frame in data.frames.values(): + frame_vars = frame.columns.intersection(list(scales)) + legend_vars.extend(v for v in frame_vars if v not in legend_vars) + else: + legend_vars = list(data.frame.columns.intersection(list(scales))) + + # First pass: Identify the values that will be shown for each variable + schema: list[tuple[ + tuple[str, str | int], list[str], tuple[list, list[str]] + ]] = [] + schema = [] + for var in legend_vars: + var_legend = scales[var]._legend + if var_legend is not None: + values, labels = var_legend + for (_, part_id), part_vars, _ in schema: + if data.ids[var] == part_id: + # Allow multiple plot semantics to represent same data variable + part_vars.append(var) + break + else: + title = self._resolve_label(p, var, data.names[var]) + entry = (title, data.ids[var]), [var], (values, labels) + schema.append(entry) + + # Second pass, generate an artist corresponding to each value + contents: list[tuple[tuple[str, str | int], Any, list[str]]] = [] + for key, variables, (values, labels) in schema: + artists = [] + for val in values: + artist = mark._legend_artist(variables, val, scales) + if artist is not None: + artists.append(artist) + if artists: + contents.append((key, artists, labels)) + + self._legend_contents.extend(contents) + + def _make_legend(self, p: Plot) -> None: + """Create the legend artist(s) and add onto the figure.""" + # Combine artists representing same information across layers + # Input list has an entry for each distinct variable in each layer + # Output dict has an entry for each distinct variable + merged_contents: dict[ + tuple[str, str | int], tuple[list[Artist], list[str]], + ] = {} + for key, new_artists, labels in self._legend_contents: + # Key is (name, id); we need the id to resolve variable uniqueness, + # but will need the name in the next step to title the legend + if key in merged_contents: + # Copy so inplace updates don't propagate back to legend_contents + existing_artists = merged_contents[key][0] + for i, artist in enumerate(existing_artists): + # Matplotlib accepts a tuple of artists and will overlay them + if isinstance(artist, tuple): + artist += new_artists[i], + else: + existing_artists[i] = artist, new_artists[i] + else: + merged_contents[key] = new_artists.copy(), labels + + # TODO explain + loc = "center right" if self._pyplot else "center left" + + base_legend = None + for (name, _), (handles, labels) in merged_contents.items(): + + legend = mpl.legend.Legend( + self._figure, + handles, + labels, + title=name, + loc=loc, + bbox_to_anchor=(.98, .55), + ) + + if base_legend: + # Matplotlib has no public API for this so it is a bit of a hack. + # Ideally we'd define our own legend class with more flexibility, + # but that is a lot of work! + base_legend_box = base_legend.get_children()[0] + this_legend_box = legend.get_children()[0] + base_legend_box.get_children().extend(this_legend_box.get_children()) + else: + base_legend = legend + self._figure.legends.append(legend) + + def _finalize_figure(self, p: Plot) -> None: + + for sub in self._subplots: + ax = sub["ax"] + for axis in "xy": + axis_key = sub[axis] + axis_obj = getattr(ax, f"{axis}axis") + + # Axis limits + if axis_key in p._limits: + convert_units = getattr(ax, f"{axis}axis").convert_units + a, b = p._limits[axis_key] + lo = a if a is None else convert_units(a) + hi = b if b is None else convert_units(b) + if isinstance(a, str): + lo = cast(float, lo) - 0.5 + if isinstance(b, str): + hi = cast(float, hi) + 0.5 + ax.set(**{f"{axis}lim": (lo, hi)}) + + if axis_key in self._scales: # TODO when would it not be? + self._scales[axis_key]._finalize(p, axis_obj) + + if (engine := p._layout_spec.get("engine", default)) is not default: + # None is a valid arg for Figure.set_layout_engine, hence `default` + set_layout_engine(self._figure, engine) + elif p._target is None: + # Don't modify the layout engine if the user supplied their own + # matplotlib figure and didn't specify an engine through Plot + # TODO switch default to "constrained"? + # TODO either way, make configurable + set_layout_engine(self._figure, "tight") diff --git a/testbed/mwaskom__seaborn/seaborn/_core/properties.py b/testbed/mwaskom__seaborn/seaborn/_core/properties.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d7c21eb13d7481102579b0d068eb59112208e5 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/properties.py @@ -0,0 +1,839 @@ +from __future__ import annotations +import itertools +import warnings + +import numpy as np +from pandas import Series +import matplotlib as mpl +from matplotlib.colors import to_rgb, to_rgba, to_rgba_array +from matplotlib.path import Path + +from seaborn._core.scales import Scale, Boolean, Continuous, Nominal, Temporal +from seaborn._core.rules import categorical_order, variable_type +from seaborn._compat import MarkerStyle +from seaborn.palettes import QUAL_PALETTES, color_palette, blend_palette +from seaborn.utils import get_color_cycle + +from typing import Any, Callable, Tuple, List, Union, Optional + +try: + from numpy.typing import ArrayLike +except ImportError: + # numpy<1.20.0 (Jan 2021) + ArrayLike = Any + +RGBTuple = Tuple[float, float, float] +RGBATuple = Tuple[float, float, float, float] +ColorSpec = Union[RGBTuple, RGBATuple, str] + +DashPattern = Tuple[float, ...] +DashPatternWithOffset = Tuple[float, Optional[DashPattern]] + +MarkerPattern = Union[ + float, + str, + Tuple[int, int, float], + List[Tuple[float, float]], + Path, + MarkerStyle, +] + +Mapping = Callable[[ArrayLike], ArrayLike] + + +# =================================================================================== # +# Base classes +# =================================================================================== # + + +class Property: + """Base class for visual properties that can be set directly or be data scaling.""" + + # When True, scales for this property will populate the legend by default + legend = False + + # When True, scales for this property normalize data to [0, 1] before mapping + normed = False + + def __init__(self, variable: str | None = None): + """Initialize the property with the name of the corresponding plot variable.""" + if not variable: + variable = self.__class__.__name__.lower() + self.variable = variable + + def default_scale(self, data: Series) -> Scale: + """Given data, initialize appropriate scale class.""" + + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + if var_type == "numeric": + return Continuous() + elif var_type == "datetime": + return Temporal() + elif var_type == "boolean": + return Boolean() + else: + return Nominal() + + def infer_scale(self, arg: Any, data: Series) -> Scale: + """Given data and a scaling argument, initialize appropriate scale class.""" + # TODO put these somewhere external for validation + # TODO putting this here won't pick it up if subclasses define infer_scale + # (e.g. color). How best to handle that? One option is to call super after + # handling property-specific possibilities (e.g. for color check that the + # arg is not a valid palette name) but that could get tricky. + trans_args = ["log", "symlog", "logit", "pow", "sqrt"] + if isinstance(arg, str): + if any(arg.startswith(k) for k in trans_args): + # TODO validate numeric type? That should happen centrally somewhere + return Continuous(trans=arg) + else: + msg = f"Unknown magic arg for {self.variable} scale: '{arg}'." + raise ValueError(msg) + else: + arg_type = type(arg).__name__ + msg = f"Magic arg for {self.variable} scale must be str, not {arg_type}." + raise TypeError(msg) + + def get_mapping(self, scale: Scale, data: Series) -> Mapping: + """Return a function that maps from data domain to property range.""" + def identity(x): + return x + return identity + + def standardize(self, val: Any) -> Any: + """Coerce flexible property value to standardized representation.""" + return val + + def _check_dict_entries(self, levels: list, values: dict) -> None: + """Input check when values are provided as a dictionary.""" + missing = set(levels) - set(values) + if missing: + formatted = ", ".join(map(repr, sorted(missing, key=str))) + err = f"No entry in {self.variable} dictionary for {formatted}" + raise ValueError(err) + + def _check_list_length(self, levels: list, values: list) -> list: + """Input check when values are provided as a list.""" + message = "" + if len(levels) > len(values): + message = " ".join([ + f"\nThe {self.variable} list has fewer values ({len(values)})", + f"than needed ({len(levels)}) and will cycle, which may", + "produce an uninterpretable plot." + ]) + values = [x for _, x in zip(levels, itertools.cycle(values))] + + elif len(values) > len(levels): + message = " ".join([ + f"The {self.variable} list has more values ({len(values)})", + f"than needed ({len(levels)}), which may not be intended.", + ]) + values = values[:len(levels)] + + # TODO look into custom PlotSpecWarning with better formatting + if message: + warnings.warn(message, UserWarning) + + return values + + +# =================================================================================== # +# Properties relating to spatial position of marks on the plotting axes +# =================================================================================== # + + +class Coordinate(Property): + """The position of visual marks with respect to the axes of the plot.""" + legend = False + normed = False + + +# =================================================================================== # +# Properties with numeric values where scale range can be defined as an interval +# =================================================================================== # + + +class IntervalProperty(Property): + """A numeric property where scale range can be defined as an interval.""" + legend = True + normed = True + + _default_range: tuple[float, float] = (0, 1) + + @property + def default_range(self) -> tuple[float, float]: + """Min and max values used by default for semantic mapping.""" + return self._default_range + + def _forward(self, values: ArrayLike) -> ArrayLike: + """Transform applied to native values before linear mapping into interval.""" + return values + + def _inverse(self, values: ArrayLike) -> ArrayLike: + """Transform applied to results of mapping that returns to native values.""" + return values + + def infer_scale(self, arg: Any, data: Series) -> Scale: + """Given data and a scaling argument, initialize appropriate scale class.""" + + # TODO infer continuous based on log/sqrt etc? + + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + + if var_type == "boolean": + return Boolean(arg) + elif isinstance(arg, (list, dict)): + return Nominal(arg) + elif var_type == "categorical": + return Nominal(arg) + elif var_type == "datetime": + return Temporal(arg) + # TODO other variable types + else: + return Continuous(arg) + + def get_mapping(self, scale: Scale, data: Series) -> Mapping: + """Return a function that maps from data domain to property range.""" + if isinstance(scale, Nominal): + return self._get_nominal_mapping(scale, data) + elif isinstance(scale, Boolean): + return self._get_boolean_mapping(scale, data) + + if scale.values is None: + vmin, vmax = self._forward(self.default_range) + elif isinstance(scale.values, tuple) and len(scale.values) == 2: + vmin, vmax = self._forward(scale.values) + else: + if isinstance(scale.values, tuple): + actual = f"{len(scale.values)}-tuple" + else: + actual = str(type(scale.values)) + scale_class = scale.__class__.__name__ + err = " ".join([ + f"Values for {self.variable} variables with {scale_class} scale", + f"must be 2-tuple; not {actual}.", + ]) + raise TypeError(err) + + def mapping(x): + return self._inverse(np.multiply(x, vmax - vmin) + vmin) + + return mapping + + def _get_nominal_mapping(self, scale: Nominal, data: Series) -> Mapping: + """Identify evenly-spaced values using interval or explicit mapping.""" + levels = categorical_order(data, scale.order) + values = self._get_values(scale, levels) + + def mapping(x): + ixs = np.asarray(x, np.intp) + out = np.full(len(x), np.nan) + use = np.isfinite(x) + out[use] = np.take(values, ixs[use]) + return out + + return mapping + + def _get_boolean_mapping(self, scale: Boolean, data: Series) -> Mapping: + """Identify evenly-spaced values using interval or explicit mapping.""" + values = self._get_values(scale, [True, False]) + + def mapping(x): + out = np.full(len(x), np.nan) + use = np.isfinite(x) + out[use] = np.where(x[use], *values) + return out + + return mapping + + def _get_values(self, scale: Scale, levels: list) -> list: + """Validate scale.values and identify a value for each level.""" + if isinstance(scale.values, dict): + self._check_dict_entries(levels, scale.values) + values = [scale.values[x] for x in levels] + elif isinstance(scale.values, list): + values = self._check_list_length(levels, scale.values) + else: + if scale.values is None: + vmin, vmax = self.default_range + elif isinstance(scale.values, tuple): + vmin, vmax = scale.values + else: + scale_class = scale.__class__.__name__ + err = " ".join([ + f"Values for {self.variable} variables with {scale_class} scale", + f"must be a dict, list or tuple; not {type(scale.values)}", + ]) + raise TypeError(err) + + vmin, vmax = self._forward([vmin, vmax]) + values = list(self._inverse(np.linspace(vmax, vmin, len(levels)))) + + return values + + +class PointSize(IntervalProperty): + """Size (diameter) of a point mark, in points, with scaling by area.""" + _default_range = 2, 8 # TODO use rcparams? + + def _forward(self, values): + """Square native values to implement linear scaling of point area.""" + return np.square(values) + + def _inverse(self, values): + """Invert areal values back to point diameter.""" + return np.sqrt(values) + + +class LineWidth(IntervalProperty): + """Thickness of a line mark, in points.""" + @property + def default_range(self) -> tuple[float, float]: + """Min and max values used by default for semantic mapping.""" + base = mpl.rcParams["lines.linewidth"] + return base * .5, base * 2 + + +class EdgeWidth(IntervalProperty): + """Thickness of the edges on a patch mark, in points.""" + @property + def default_range(self) -> tuple[float, float]: + """Min and max values used by default for semantic mapping.""" + base = mpl.rcParams["patch.linewidth"] + return base * .5, base * 2 + + +class Stroke(IntervalProperty): + """Thickness of lines that define point glyphs.""" + _default_range = .25, 2.5 + + +class Alpha(IntervalProperty): + """Opacity of the color values for an arbitrary mark.""" + _default_range = .3, .95 + # TODO validate / enforce that output is in [0, 1] + + +class Offset(IntervalProperty): + """Offset for edge-aligned text, in point units.""" + _default_range = 0, 5 + _legend = False + + +class FontSize(IntervalProperty): + """Font size for textual marks, in points.""" + _legend = False + + @property + def default_range(self) -> tuple[float, float]: + """Min and max values used by default for semantic mapping.""" + base = mpl.rcParams["font.size"] + return base * .5, base * 2 + + +# =================================================================================== # +# Properties defined by arbitrary objects with inherently nominal scaling +# =================================================================================== # + + +class ObjectProperty(Property): + """A property defined by arbitrary an object, with inherently nominal scaling.""" + legend = True + normed = False + + # Object representing null data, should appear invisible when drawn by matplotlib + # Note that we now drop nulls in Plot._plot_layer and thus may not need this + null_value: Any = None + + def _default_values(self, n: int) -> list: + raise NotImplementedError() + + def default_scale(self, data: Series) -> Scale: + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + return Boolean() if var_type == "boolean" else Nominal() + + def infer_scale(self, arg: Any, data: Series) -> Scale: + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + return Boolean(arg) if var_type == "boolean" else Nominal(arg) + + def get_mapping(self, scale: Scale, data: Series) -> Mapping: + """Define mapping as lookup into list of object values.""" + boolean_scale = isinstance(scale, Boolean) + order = getattr(scale, "order", [True, False] if boolean_scale else None) + levels = categorical_order(data, order) + values = self._get_values(scale, levels) + + if boolean_scale: + values = values[::-1] + + def mapping(x): + ixs = np.asarray(x, np.intp) + return [ + values[ix] if np.isfinite(x_i) else self.null_value + for x_i, ix in zip(x, ixs) + ] + + return mapping + + def _get_values(self, scale: Scale, levels: list) -> list: + """Validate scale.values and identify a value for each level.""" + n = len(levels) + if isinstance(scale.values, dict): + self._check_dict_entries(levels, scale.values) + values = [scale.values[x] for x in levels] + elif isinstance(scale.values, list): + values = self._check_list_length(levels, scale.values) + elif scale.values is None: + values = self._default_values(n) + else: + msg = " ".join([ + f"Scale values for a {self.variable} variable must be provided", + f"in a dict or list; not {type(scale.values)}." + ]) + raise TypeError(msg) + + values = [self.standardize(x) for x in values] + return values + + +class Marker(ObjectProperty): + """Shape of points in scatter-type marks or lines with data points marked.""" + null_value = MarkerStyle("") + + # TODO should we have named marker "palettes"? (e.g. see d3 options) + + # TODO need some sort of "require_scale" functionality + # to raise when we get the wrong kind explicitly specified + + def standardize(self, val: MarkerPattern) -> MarkerStyle: + return MarkerStyle(val) + + def _default_values(self, n: int) -> list[MarkerStyle]: + """Build an arbitrarily long list of unique marker styles. + + Parameters + ---------- + n : int + Number of unique marker specs to generate. + + Returns + ------- + markers : list of string or tuples + Values for defining :class:`matplotlib.markers.MarkerStyle` objects. + All markers will be filled. + + """ + # Start with marker specs that are well distinguishable + markers = [ + "o", "X", (4, 0, 45), "P", (4, 0, 0), (4, 1, 0), "^", (4, 1, 45), "v", + ] + + # Now generate more from regular polygons of increasing order + s = 5 + while len(markers) < n: + a = 360 / (s + 1) / 2 + markers.extend([(s + 1, 1, a), (s + 1, 0, a), (s, 1, 0), (s, 0, 0)]) + s += 1 + + markers = [MarkerStyle(m) for m in markers[:n]] + + return markers + + +class LineStyle(ObjectProperty): + """Dash pattern for line-type marks.""" + null_value = "" + + def standardize(self, val: str | DashPattern) -> DashPatternWithOffset: + return self._get_dash_pattern(val) + + def _default_values(self, n: int) -> list[DashPatternWithOffset]: + """Build an arbitrarily long list of unique dash styles for lines. + + Parameters + ---------- + n : int + Number of unique dash specs to generate. + + Returns + ------- + dashes : list of strings or tuples + Valid arguments for the ``dashes`` parameter on + :class:`matplotlib.lines.Line2D`. The first spec is a solid + line (``""``), the remainder are sequences of long and short + dashes. + + """ + # Start with dash specs that are well distinguishable + dashes: list[str | DashPattern] = [ + "-", (4, 1.5), (1, 1), (3, 1.25, 1.5, 1.25), (5, 1, 1, 1), + ] + + # Now programmatically build as many as we need + p = 3 + while len(dashes) < n: + + # Take combinations of long and short dashes + a = itertools.combinations_with_replacement([3, 1.25], p) + b = itertools.combinations_with_replacement([4, 1], p) + + # Interleave the combinations, reversing one of the streams + segment_list = itertools.chain(*zip(list(a)[1:-1][::-1], list(b)[1:-1])) + + # Now insert the gaps + for segments in segment_list: + gap = min(segments) + spec = tuple(itertools.chain(*((seg, gap) for seg in segments))) + dashes.append(spec) + + p += 1 + + return [self._get_dash_pattern(x) for x in dashes] + + @staticmethod + def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset: + """Convert linestyle arguments to dash pattern with offset.""" + # Copied and modified from Matplotlib 3.4 + # go from short hand -> full strings + ls_mapper = {"-": "solid", "--": "dashed", "-.": "dashdot", ":": "dotted"} + if isinstance(style, str): + style = ls_mapper.get(style, style) + # un-dashed styles + if style in ["solid", "none", "None"]: + offset = 0 + dashes = None + # dashed styles + elif style in ["dashed", "dashdot", "dotted"]: + offset = 0 + dashes = tuple(mpl.rcParams[f"lines.{style}_pattern"]) + else: + options = [*ls_mapper.values(), *ls_mapper.keys()] + msg = f"Linestyle string must be one of {options}, not {repr(style)}." + raise ValueError(msg) + + elif isinstance(style, tuple): + if len(style) > 1 and isinstance(style[1], tuple): + offset, dashes = style + elif len(style) > 1 and style[1] is None: + offset, dashes = style + else: + offset = 0 + dashes = style + else: + val_type = type(style).__name__ + msg = f"Linestyle must be str or tuple, not {val_type}." + raise TypeError(msg) + + # Normalize offset to be positive and shorter than the dash cycle + if dashes is not None: + try: + dsum = sum(dashes) + except TypeError as err: + msg = f"Invalid dash pattern: {dashes}" + raise TypeError(msg) from err + if dsum: + offset %= dsum + + return offset, dashes + + +class TextAlignment(ObjectProperty): + legend = False + + +class HorizontalAlignment(TextAlignment): + + def _default_values(self, n: int) -> list: + vals = itertools.cycle(["left", "right"]) + return [next(vals) for _ in range(n)] + + +class VerticalAlignment(TextAlignment): + + def _default_values(self, n: int) -> list: + vals = itertools.cycle(["top", "bottom"]) + return [next(vals) for _ in range(n)] + + +# =================================================================================== # +# Properties with RGB(A) color values +# =================================================================================== # + + +class Color(Property): + """Color, as RGB(A), scalable with nominal palettes or continuous gradients.""" + legend = True + normed = True + + def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple: + # Return color with alpha channel only if the input spec has it + # This is so that RGBA colors can override the Alpha property + if to_rgba(val) != to_rgba(val, 1): + return to_rgba(val) + else: + return to_rgb(val) + + def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike: + """Convert color sequence to RGB(A) array, preserving but not adding alpha.""" + def has_alpha(x): + return to_rgba(x) != to_rgba(x, 1) + + if isinstance(colors, np.ndarray): + needs_alpha = colors.shape[1] == 4 + else: + needs_alpha = any(has_alpha(x) for x in colors) + + if needs_alpha: + return to_rgba_array(colors) + else: + return to_rgba_array(colors)[:, :3] + + def infer_scale(self, arg: Any, data: Series) -> Scale: + # TODO when inferring Continuous without data, verify type + + # TODO need to rethink the variable type system + # (e.g. boolean, ordered categories as Ordinal, etc).. + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + + if var_type == "boolean": + return Boolean(arg) + + if isinstance(arg, (dict, list)): + return Nominal(arg) + + if isinstance(arg, tuple): + if var_type == "categorical": + # TODO It seems reasonable to allow a gradient mapping for nominal + # scale but it also feels "technically" wrong. Should this infer + # Ordinal with categorical data and, if so, verify orderedness? + return Nominal(arg) + return Continuous(arg) + + if callable(arg): + return Continuous(arg) + + # TODO Do we accept str like "log", "pow", etc. for semantics? + + if not isinstance(arg, str): + msg = " ".join([ + f"A single scale argument for {self.variable} variables must be", + f"a string, dict, tuple, list, or callable, not {type(arg)}." + ]) + raise TypeError(msg) + + if arg in QUAL_PALETTES: + return Nominal(arg) + elif var_type == "numeric": + return Continuous(arg) + # TODO implement scales for date variables and any others. + else: + return Nominal(arg) + + def get_mapping(self, scale: Scale, data: Series) -> Mapping: + """Return a function that maps from data domain to color values.""" + # TODO what is best way to do this conditional? + # Should it be class-based or should classes have behavioral attributes? + if isinstance(scale, Nominal): + return self._get_nominal_mapping(scale, data) + elif isinstance(scale, Boolean): + return self._get_boolean_mapping(scale, data) + + if scale.values is None: + # TODO Rethink best default continuous color gradient + mapping = color_palette("ch:", as_cmap=True) + elif isinstance(scale.values, tuple): + # TODO blend_palette will strip alpha, but we should support + # interpolation on all four channels + mapping = blend_palette(scale.values, as_cmap=True) + elif isinstance(scale.values, str): + # TODO for matplotlib colormaps this will clip extremes, which is + # different from what using the named colormap directly would do + # This may or may not be desireable. + mapping = color_palette(scale.values, as_cmap=True) + elif callable(scale.values): + mapping = scale.values + else: + scale_class = scale.__class__.__name__ + msg = " ".join([ + f"Scale values for {self.variable} with a {scale_class} mapping", + f"must be string, tuple, or callable; not {type(scale.values)}." + ]) + raise TypeError(msg) + + def _mapping(x): + # Remove alpha channel so it does not override alpha property downstream + # TODO this will need to be more flexible to support RGBA tuples (see above) + invalid = ~np.isfinite(x) + out = mapping(x)[:, :3] + out[invalid] = np.nan + return out + + return _mapping + + def _get_nominal_mapping(self, scale: Nominal, data: Series) -> Mapping: + + levels = categorical_order(data, scale.order) + colors = self._get_values(scale, levels) + + def mapping(x): + ixs = np.asarray(x, np.intp) + use = np.isfinite(x) + out = np.full((len(ixs), colors.shape[1]), np.nan) + out[use] = np.take(colors, ixs[use], axis=0) + return out + + return mapping + + def _get_boolean_mapping(self, scale: Boolean, data: Series) -> Mapping: + + colors = self._get_values(scale, [True, False]) + + def mapping(x): + + use = np.isfinite(x) + x = np.asarray(x).astype(bool) + out = np.full((len(x), colors.shape[1]), np.nan) + out[x & use] = colors[0] + out[~x & use] = colors[1] + return out + + return mapping + + def _get_values(self, scale: Scale, levels: list) -> ArrayLike: + """Validate scale.values and identify a value for each level.""" + n = len(levels) + values = scale.values + if isinstance(values, dict): + self._check_dict_entries(levels, values) + colors = [values[x] for x in levels] + elif isinstance(values, list): + colors = self._check_list_length(levels, values) + elif isinstance(values, tuple): + colors = blend_palette(values, n) + elif isinstance(values, str): + colors = color_palette(values, n) + elif values is None: + if n <= len(get_color_cycle()): + # Use current (global) default palette + colors = color_palette(n_colors=n) + else: + colors = color_palette("husl", n) + else: + scale_class = scale.__class__.__name__ + msg = " ".join([ + f"Scale values for {self.variable} with a {scale_class} mapping", + f"must be string, list, tuple, or dict; not {type(scale.values)}." + ]) + raise TypeError(msg) + + return self._standardize_color_sequence(colors) + + +# =================================================================================== # +# Properties that can take only two states +# =================================================================================== # + + +class Fill(Property): + """Boolean property of points/bars/patches that can be solid or outlined.""" + legend = True + normed = False + + def default_scale(self, data: Series) -> Scale: + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + return Boolean() if var_type == "boolean" else Nominal() + + def infer_scale(self, arg: Any, data: Series) -> Scale: + var_type = variable_type(data, boolean_type="boolean", strict_boolean=True) + return Boolean(arg) if var_type == "boolean" else Nominal(arg) + + def standardize(self, val: Any) -> bool: + return bool(val) + + def _default_values(self, n: int) -> list: + """Return a list of n values, alternating True and False.""" + if n > 2: + msg = " ".join([ + f"The variable assigned to {self.variable} has more than two levels,", + f"so {self.variable} values will cycle and may be uninterpretable", + ]) + # TODO fire in a "nice" way (see above) + warnings.warn(msg, UserWarning) + return [x for x, _ in zip(itertools.cycle([True, False]), range(n))] + + def get_mapping(self, scale: Scale, data: Series) -> Mapping: + """Return a function that maps each data value to True or False.""" + boolean_scale = isinstance(scale, Boolean) + order = getattr(scale, "order", [True, False] if boolean_scale else None) + levels = categorical_order(data, order) + values = self._get_values(scale, levels) + + if boolean_scale: + values = values[::-1] + + def mapping(x): + ixs = np.asarray(x, np.intp) + return [ + values[ix] if np.isfinite(x_i) else False + for x_i, ix in zip(x, ixs) + ] + + return mapping + + def _get_values(self, scale: Scale, levels: list) -> list: + """Validate scale.values and identify a value for each level.""" + if isinstance(scale.values, list): + values = [bool(x) for x in scale.values] + elif isinstance(scale.values, dict): + values = [bool(scale.values[x]) for x in levels] + elif scale.values is None: + values = self._default_values(len(levels)) + else: + msg = " ".join([ + f"Scale values for {self.variable} must be passed in", + f"a list or dict; not {type(scale.values)}." + ]) + raise TypeError(msg) + + return values + + +# =================================================================================== # +# Enumeration of properties for use by Plot and Mark classes +# =================================================================================== # +# TODO turn this into a property registry with hooks, etc. +# TODO Users do not interact directly with properties, so how to document them? + + +PROPERTY_CLASSES = { + "x": Coordinate, + "y": Coordinate, + "color": Color, + "alpha": Alpha, + "fill": Fill, + "marker": Marker, + "pointsize": PointSize, + "stroke": Stroke, + "linewidth": LineWidth, + "linestyle": LineStyle, + "fillcolor": Color, + "fillalpha": Alpha, + "edgewidth": EdgeWidth, + "edgestyle": LineStyle, + "edgecolor": Color, + "edgealpha": Alpha, + "text": Property, + "halign": HorizontalAlignment, + "valign": VerticalAlignment, + "offset": Offset, + "fontsize": FontSize, + "xmin": Coordinate, + "xmax": Coordinate, + "ymin": Coordinate, + "ymax": Coordinate, + "group": Property, + # TODO pattern? + # TODO gradient? +} + +PROPERTIES = {var: cls(var) for var, cls in PROPERTY_CLASSES.items()} diff --git a/testbed/mwaskom__seaborn/seaborn/_core/rules.py b/testbed/mwaskom__seaborn/seaborn/_core/rules.py new file mode 100644 index 0000000000000000000000000000000000000000..0de7bcd7fab23bb358c6f79be8ef91f1a568dac2 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/rules.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import warnings +from collections import UserString +from numbers import Number +from datetime import datetime + +import numpy as np +import pandas as pd + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from typing import Literal + from pandas import Series + + +class VarType(UserString): + """ + Prevent comparisons elsewhere in the library from using the wrong name. + + Errors are simple assertions because users should not be able to trigger + them. If that changes, they should be more verbose. + + """ + # TODO VarType is an awfully overloaded name, but so is DataType ... + # TODO adding unknown because we are using this in for scales, is that right? + allowed = "numeric", "datetime", "categorical", "boolean", "unknown" + + def __init__(self, data): + assert data in self.allowed, data + super().__init__(data) + + def __eq__(self, other): + assert other in self.allowed, other + return self.data == other + + +def variable_type( + vector: Series, + boolean_type: Literal["numeric", "categorical", "boolean"] = "numeric", + strict_boolean: bool = False, +) -> VarType: + """ + Determine whether a vector contains numeric, categorical, or datetime data. + + This function differs from the pandas typing API in a few ways: + + - Python sequences or object-typed PyData objects are considered numeric if + all of their entries are numeric. + - String or mixed-type data are considered categorical even if not + explicitly represented as a :class:`pandas.api.types.CategoricalDtype`. + - There is some flexibility about how to treat binary / boolean data. + + Parameters + ---------- + vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence + Input data to test. + boolean_type : 'numeric', 'categorical', or 'boolean' + Type to use for vectors containing only 0s and 1s (and NAs). + strict_boolean : bool + If True, only consider data to be boolean when the dtype is bool or Boolean. + + Returns + ------- + var_type : 'numeric', 'categorical', or 'datetime' + Name identifying the type of data in the vector. + """ + + # If a categorical dtype is set, infer categorical + if pd.api.types.is_categorical_dtype(vector): + return VarType("categorical") + + # Special-case all-na data, which is always "numeric" + if pd.isna(vector).all(): + return VarType("numeric") + + # Special-case binary/boolean data, allow caller to determine + # This triggers a numpy warning when vector has strings/objects + # https://github.com/numpy/numpy/issues/6784 + # Because we reduce with .all(), we are agnostic about whether the + # comparison returns a scalar or vector, so we will ignore the warning. + # It triggers a separate DeprecationWarning when the vector has datetimes: + # https://github.com/numpy/numpy/issues/13548 + # This is considered a bug by numpy and will likely go away. + with warnings.catch_warnings(): + warnings.simplefilter( + action='ignore', + category=(FutureWarning, DeprecationWarning) # type: ignore # mypy bug? + ) + if strict_boolean: + if isinstance(vector.dtype, pd.core.dtypes.base.ExtensionDtype): + boolean_dtypes = ["bool", "boolean"] + else: + boolean_dtypes = ["bool"] + boolean_vector = vector.dtype in boolean_dtypes + else: + boolean_vector = bool(np.isin(vector, [0, 1, np.nan]).all()) + if boolean_vector: + return VarType(boolean_type) + + # Defer to positive pandas tests + if pd.api.types.is_numeric_dtype(vector): + return VarType("numeric") + + if pd.api.types.is_datetime64_dtype(vector): + return VarType("datetime") + + # --- If we get to here, we need to check the entries + + # Check for a collection where everything is a number + + def all_numeric(x): + for x_i in x: + if not isinstance(x_i, Number): + return False + return True + + if all_numeric(vector): + return VarType("numeric") + + # Check for a collection where everything is a datetime + + def all_datetime(x): + for x_i in x: + if not isinstance(x_i, (datetime, np.datetime64)): + return False + return True + + if all_datetime(vector): + return VarType("datetime") + + # Otherwise, our final fallback is to consider things categorical + + return VarType("categorical") + + +def categorical_order(vector: Series, order: list | None = None) -> list: + """ + Return a list of unique data values using seaborn's ordering rules. + + Parameters + ---------- + vector : Series + Vector of "categorical" values + order : list + Desired order of category levels to override the order determined + from the `data` object. + + Returns + ------- + order : list + Ordered list of category levels not including null values. + + """ + if order is not None: + return order + + if vector.dtype.name == "category": + order = list(vector.cat.categories) + else: + order = list(filter(pd.notnull, vector.unique())) + if variable_type(pd.Series(order)) == "numeric": + order.sort() + + return order diff --git a/testbed/mwaskom__seaborn/seaborn/_core/scales.py b/testbed/mwaskom__seaborn/seaborn/_core/scales.py new file mode 100644 index 0000000000000000000000000000000000000000..8c597e126ea27133cb3e94a5395c8ff388266c47 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/scales.py @@ -0,0 +1,1092 @@ +from __future__ import annotations +import re +from copy import copy +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, Tuple, Optional, ClassVar + +import numpy as np +import matplotlib as mpl +from matplotlib.ticker import ( + Locator, + Formatter, + AutoLocator, + AutoMinorLocator, + FixedLocator, + LinearLocator, + LogLocator, + SymmetricalLogLocator, + MaxNLocator, + MultipleLocator, + EngFormatter, + FuncFormatter, + LogFormatterSciNotation, + ScalarFormatter, + StrMethodFormatter, +) +from matplotlib.dates import ( + AutoDateLocator, + AutoDateFormatter, + ConciseDateFormatter, +) +from matplotlib.axis import Axis +from matplotlib.scale import ScaleBase +from pandas import Series + +from seaborn._core.rules import categorical_order +from seaborn._core.typing import Default, default + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from seaborn._core.plot import Plot + from seaborn._core.properties import Property + from numpy.typing import ArrayLike, NDArray + + TransFuncs = Tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + + # TODO Reverting typing to Any as it was proving too complicated to + # work out the right way to communicate the types to mypy. Revisit! + Pipeline = Sequence[Optional[Callable[[Any], Any]]] + + +class Scale: + """Base class for objects that map data values to visual properties.""" + + values: tuple | str | list | dict | None + + _priority: ClassVar[int] + _pipeline: Pipeline + _matplotlib_scale: ScaleBase + _spacer: staticmethod + _legend: tuple[list[Any], list[str]] | None + + def __post_init__(self): + + self._tick_params = None + self._label_params = None + self._legend = None + + def tick(self): + raise NotImplementedError() + + def label(self): + raise NotImplementedError() + + def _get_locators(self): + raise NotImplementedError() + + def _get_formatter(self, locator: Locator | None = None): + raise NotImplementedError() + + def _get_scale(self, name: str, forward: Callable, inverse: Callable): + + major_locator, minor_locator = self._get_locators(**self._tick_params) + major_formatter = self._get_formatter(major_locator, **self._label_params) + + class InternalScale(mpl.scale.FuncScale): + def set_default_locators_and_formatters(self, axis): + axis.set_major_locator(major_locator) + if minor_locator is not None: + axis.set_minor_locator(minor_locator) + axis.set_major_formatter(major_formatter) + + return InternalScale(name, (forward, inverse)) + + def _spacing(self, x: Series) -> float: + space = self._spacer(x) + if np.isnan(space): + # This happens when there is no variance in the orient coordinate data + # Not exactly clear what the right default is, but 1 seems reasonable? + return 1 + return space + + def _setup( + self, data: Series, prop: Property, axis: Axis | None = None, + ) -> Scale: + raise NotImplementedError() + + def _finalize(self, p: Plot, axis: Axis) -> None: + """Perform scale-specific axis tweaks after adding artists.""" + pass + + def __call__(self, data: Series) -> ArrayLike: + + trans_data: Series | NDArray | list + + # TODO sometimes we need to handle scalars (e.g. for Line) + # but what is the best way to do that? + scalar_data = np.isscalar(data) + if scalar_data: + trans_data = np.array([data]) + else: + trans_data = data + + for func in self._pipeline: + if func is not None: + trans_data = func(trans_data) + + if scalar_data: + return trans_data[0] + else: + return trans_data + + @staticmethod + def _identity(): + + class Identity(Scale): + _pipeline = [] + _spacer = None + _legend = None + _matplotlib_scale = None + + return Identity() + + +@dataclass +class Boolean(Scale): + """ + A scale with a discrete domain of True and False values. + + The behavior is similar to the :class:`Nominal` scale, but property + mappings and legends will use a [True, False] ordering rather than + a sort using numeric rules. Coordinate variables accomplish this by + inverting axis limits so as to maintain underlying numeric positioning. + Input data are cast to boolean values, respecting missing data. + + """ + values: tuple | list | dict | None = None + + _priority: ClassVar[int] = 3 + + def _setup( + self, data: Series, prop: Property, axis: Axis | None = None, + ) -> Scale: + + new = copy(self) + if new._tick_params is None: + new = new.tick() + if new._label_params is None: + new = new.label() + + def na_safe_cast(x): + # TODO this doesn't actually need to be a closure + if np.isscalar(x): + return float(bool(x)) + else: + if hasattr(x, "notna"): + # Handle pd.NA; np<>pd interop with NA is tricky + use = x.notna().to_numpy() + else: + use = np.isfinite(x) + out = np.full(len(x), np.nan, dtype=float) + out[use] = x[use].astype(bool).astype(float) + return out + + new._pipeline = [na_safe_cast, prop.get_mapping(new, data)] + new._spacer = _default_spacer + if prop.legend: + new._legend = [True, False], ["True", "False"] + + forward, inverse = _make_identity_transforms() + mpl_scale = new._get_scale(str(data.name), forward, inverse) + + axis = PseudoAxis(mpl_scale) if axis is None else axis + mpl_scale.set_default_locators_and_formatters(axis) + new._matplotlib_scale = mpl_scale + + return new + + def _finalize(self, p: Plot, axis: Axis) -> None: + + # We want values to appear in a True, False order but also want + # True/False to be drawn at 1/0 positions respectively to avoid nasty + # surprises if additional artists are added through the matplotlib API. + # We accomplish this using axis inversion akin to what we do in Nominal. + + ax = axis.axes + name = axis.axis_name + axis.grid(False, which="both") + if name not in p._limits: + nticks = len(axis.get_major_ticks()) + lo, hi = -.5, nticks - .5 + if name == "x": + lo, hi = hi, lo + set_lim = getattr(ax, f"set_{name}lim") + set_lim(lo, hi, auto=None) + + def tick(self, locator: Locator | None = None): + new = copy(self) + new._tick_params = {"locator": locator} + return new + + def label(self, formatter: Formatter | None = None): + new = copy(self) + new._label_params = {"formatter": formatter} + return new + + def _get_locators(self, locator): + if locator is not None: + return locator + return FixedLocator([0, 1]), None + + def _get_formatter(self, locator, formatter): + if formatter is not None: + return formatter + return FuncFormatter(lambda x, _: str(bool(x))) + + +@dataclass +class Nominal(Scale): + """ + A categorical scale without relative importance / magnitude. + """ + # Categorical (convert to strings), un-sortable + + values: tuple | str | list | dict | None = None + order: list | None = None + + _priority: ClassVar[int] = 4 + + def _setup( + self, data: Series, prop: Property, axis: Axis | None = None, + ) -> Scale: + + new = copy(self) + if new._tick_params is None: + new = new.tick() + if new._label_params is None: + new = new.label() + + # TODO flexibility over format() which isn't great for numbers / dates + stringify = np.vectorize(format, otypes=["object"]) + + units_seed = categorical_order(data, new.order) + + # TODO move to Nominal._get_scale? + # TODO this needs some more complicated rethinking about how to pass + # a unit dictionary down to these methods, along with how much we want + # to invest in their API. What is it useful for tick() to do here? + # (Ordinal may be different if we draw that contrast). + # Any customization we do to allow, e.g., label wrapping will probably + # require defining our own Formatter subclass. + # We could also potentially implement auto-wrapping in an Axis subclass + # (see Axis.draw ... it already is computing the bboxes). + # major_locator, minor_locator = new._get_locators(**new._tick_params) + # major_formatter = new._get_formatter(major_locator, **new._label_params) + + class CatScale(mpl.scale.LinearScale): + name = None # To work around mpl<3.4 compat issues + + def set_default_locators_and_formatters(self, axis): + ... + # axis.set_major_locator(major_locator) + # if minor_locator is not None: + # axis.set_minor_locator(minor_locator) + # axis.set_major_formatter(major_formatter) + + mpl_scale = CatScale(data.name) + if axis is None: + axis = PseudoAxis(mpl_scale) + + # TODO Currently just used in non-Coordinate contexts, but should + # we use this to (A) set the padding we want for categorial plots + # and (B) allow the values parameter for a Coordinate to set xlim/ylim + axis.set_view_interval(0, len(units_seed) - 1) + + new._matplotlib_scale = mpl_scale + + # TODO array cast necessary to handle float/int mixture, which we need + # to solve in a more systematic way probably + # (i.e. if we have [1, 2.5], do we want [1.0, 2.5]? Unclear) + axis.update_units(stringify(np.array(units_seed))) + + # TODO define this more centrally + def convert_units(x): + # TODO only do this with explicit order? + # (But also category dtype?) + # TODO isin fails when units_seed mixes numbers and strings (numpy error?) + # but np.isin also does not seem any faster? (Maybe not broadcasting in C) + # keep = x.isin(units_seed) + keep = np.array([x_ in units_seed for x_ in x], bool) + out = np.full(len(x), np.nan) + out[keep] = axis.convert_units(stringify(x[keep])) + return out + + new._pipeline = [convert_units, prop.get_mapping(new, data)] + new._spacer = _default_spacer + + if prop.legend: + new._legend = units_seed, list(stringify(units_seed)) + + return new + + def _finalize(self, p: Plot, axis: Axis) -> None: + + ax = axis.axes + name = axis.axis_name + axis.grid(False, which="both") + if name not in p._limits: + nticks = len(axis.get_major_ticks()) + lo, hi = -.5, nticks - .5 + if name == "y": + lo, hi = hi, lo + set_lim = getattr(ax, f"set_{name}lim") + set_lim(lo, hi, auto=None) + + def tick(self, locator: Locator | None = None) -> Nominal: + """ + Configure the selection of ticks for the scale's axis or legend. + + .. note:: + This API is under construction and will be enhanced over time. + At the moment, it is probably not very useful. + + Parameters + ---------- + locator : :class:`matplotlib.ticker.Locator` subclass + Pre-configured matplotlib locator; other parameters will not be used. + + Returns + ------- + Copy of self with new tick configuration. + + """ + new = copy(self) + new._tick_params = {"locator": locator} + return new + + def label(self, formatter: Formatter | None = None) -> Nominal: + """ + Configure the selection of labels for the scale's axis or legend. + + .. note:: + This API is under construction and will be enhanced over time. + At the moment, it is probably not very useful. + + Parameters + ---------- + formatter : :class:`matplotlib.ticker.Formatter` subclass + Pre-configured matplotlib formatter; other parameters will not be used. + + Returns + ------- + scale + Copy of self with new tick configuration. + + """ + new = copy(self) + new._label_params = {"formatter": formatter} + return new + + def _get_locators(self, locator): + + if locator is not None: + return locator, None + + locator = mpl.category.StrCategoryLocator({}) + + return locator, None + + def _get_formatter(self, locator, formatter): + + if formatter is not None: + return formatter + + formatter = mpl.category.StrCategoryFormatter({}) + + return formatter + + +@dataclass +class Ordinal(Scale): + # Categorical (convert to strings), sortable, can skip ticklabels + ... + + +@dataclass +class Discrete(Scale): + # Numeric, integral, can skip ticks/ticklabels + ... + + +@dataclass +class ContinuousBase(Scale): + + values: tuple | str | None = None + norm: tuple | None = None + + def _setup( + self, data: Series, prop: Property, axis: Axis | None = None, + ) -> Scale: + + new = copy(self) + if new._tick_params is None: + new = new.tick() + if new._label_params is None: + new = new.label() + + forward, inverse = new._get_transform() + + mpl_scale = new._get_scale(str(data.name), forward, inverse) + + if axis is None: + axis = PseudoAxis(mpl_scale) + axis.update_units(data) + + mpl_scale.set_default_locators_and_formatters(axis) + new._matplotlib_scale = mpl_scale + + normalize: Optional[Callable[[ArrayLike], ArrayLike]] + if prop.normed: + if new.norm is None: + vmin, vmax = data.min(), data.max() + else: + vmin, vmax = new.norm + vmin, vmax = map(float, axis.convert_units((vmin, vmax))) + a = forward(vmin) + b = forward(vmax) - forward(vmin) + + def normalize(x): + return (x - a) / b + + else: + normalize = vmin = vmax = None + + new._pipeline = [ + axis.convert_units, + forward, + normalize, + prop.get_mapping(new, data) + ] + + def spacer(x): + x = x.dropna().unique() + if len(x) < 2: + return np.nan + return np.min(np.diff(np.sort(x))) + new._spacer = spacer + + # TODO How to allow disabling of legend for all uses of property? + # Could add a Scale parameter, or perhaps Scale.suppress()? + # Are there other useful parameters that would be in Scale.legend() + # besides allowing Scale.legend(False)? + if prop.legend: + axis.set_view_interval(vmin, vmax) + locs = axis.major.locator() + locs = locs[(vmin <= locs) & (locs <= vmax)] + # Avoid having an offset / scientific notation in a legend + # as we don't represent that anywhere so it ends up incorrect. + # This could become an option (e.g. Continuous.label(offset=True)) + # in which case we would need to figure out how to show it. + if hasattr(axis.major.formatter, "set_useOffset"): + axis.major.formatter.set_useOffset(False) + if hasattr(axis.major.formatter, "set_scientific"): + axis.major.formatter.set_scientific(False) + labels = axis.major.formatter.format_ticks(locs) + new._legend = list(locs), list(labels) + + return new + + def _get_transform(self): + + arg = self.trans + + def get_param(method, default): + if arg == method: + return default + return float(arg[len(method):]) + + if arg is None: + return _make_identity_transforms() + elif isinstance(arg, tuple): + return arg + elif isinstance(arg, str): + if arg == "ln": + return _make_log_transforms() + elif arg == "logit": + base = get_param("logit", 10) + return _make_logit_transforms(base) + elif arg.startswith("log"): + base = get_param("log", 10) + return _make_log_transforms(base) + elif arg.startswith("symlog"): + c = get_param("symlog", 1) + return _make_symlog_transforms(c) + elif arg.startswith("pow"): + exp = get_param("pow", 2) + return _make_power_transforms(exp) + elif arg == "sqrt": + return _make_sqrt_transforms() + else: + raise ValueError(f"Unknown value provided for trans: {arg!r}") + + +@dataclass +class Continuous(ContinuousBase): + """ + A numeric scale supporting norms and functional transforms. + """ + values: tuple | str | None = None + trans: str | TransFuncs | None = None + + # TODO Add this to deal with outliers? + # outside: Literal["keep", "drop", "clip"] = "keep" + + _priority: ClassVar[int] = 1 + + def tick( + self, + locator: Locator | None = None, *, + at: Sequence[float] | None = None, + upto: int | None = None, + count: int | None = None, + every: float | None = None, + between: tuple[float, float] | None = None, + minor: int | None = None, + ) -> Continuous: + """ + Configure the selection of ticks for the scale's axis or legend. + + Parameters + ---------- + locator : :class:`matplotlib.ticker.Locator` subclass + Pre-configured matplotlib locator; other parameters will not be used. + at : sequence of floats + Place ticks at these specific locations (in data units). + upto : int + Choose "nice" locations for ticks, but do not exceed this number. + count : int + Choose exactly this number of ticks, bounded by `between` or axis limits. + every : float + Choose locations at this interval of separation (in data units). + between : pair of floats + Bound upper / lower ticks when using `every` or `count`. + minor : int + Number of unlabeled ticks to draw between labeled "major" ticks. + + Returns + ------- + scale + Copy of self with new tick configuration. + + """ + # Input checks + if locator is not None and not isinstance(locator, Locator): + raise TypeError( + f"Tick locator must be an instance of {Locator!r}, " + f"not {type(locator)!r}." + ) + log_base, symlog_thresh = self._parse_for_log_params(self.trans) + if log_base or symlog_thresh: + if count is not None and between is None: + raise RuntimeError("`count` requires `between` with log transform.") + if every is not None: + raise RuntimeError("`every` not supported with log transform.") + + new = copy(self) + new._tick_params = { + "locator": locator, + "at": at, + "upto": upto, + "count": count, + "every": every, + "between": between, + "minor": minor, + } + return new + + def label( + self, + formatter: Formatter | None = None, *, + like: str | Callable | None = None, + base: int | None | Default = default, + unit: str | None = None, + ) -> Continuous: + """ + Configure the appearance of tick labels for the scale's axis or legend. + + Parameters + ---------- + formatter : :class:`matplotlib.ticker.Formatter` subclass + Pre-configured formatter to use; other parameters will be ignored. + like : str or callable + Either a format pattern (e.g., `".2f"`), a format string with fields named + `x` and/or `pos` (e.g., `"${x:.2f}"`), or a callable with a signature like + `f(x: float, pos: int) -> str`. In the latter variants, `x` is passed as the + tick value and `pos` is passed as the tick index. + base : number + Use log formatter (with scientific notation) having this value as the base. + Set to `None` to override the default formatter with a log transform. + unit : str or (str, str) tuple + Use SI prefixes with these units (e.g., with `unit="g"`, a tick value + of 5000 will appear as `5 kg`). When a tuple, the first element gives the + separator between the number and unit. + + Returns + ------- + scale + Copy of self with new label configuration. + + """ + # Input checks + if formatter is not None and not isinstance(formatter, Formatter): + raise TypeError( + f"Label formatter must be an instance of {Formatter!r}, " + f"not {type(formatter)!r}" + ) + if like is not None and not (isinstance(like, str) or callable(like)): + msg = f"`like` must be a string or callable, not {type(like).__name__}." + raise TypeError(msg) + + new = copy(self) + new._label_params = { + "formatter": formatter, + "like": like, + "base": base, + "unit": unit, + } + return new + + def _parse_for_log_params( + self, trans: str | TransFuncs | None + ) -> tuple[float | None, float | None]: + + log_base = symlog_thresh = None + if isinstance(trans, str): + m = re.match(r"^log(\d*)", trans) + if m is not None: + log_base = float(m[1] or 10) + m = re.match(r"symlog(\d*)", trans) + if m is not None: + symlog_thresh = float(m[1] or 1) + return log_base, symlog_thresh + + def _get_locators(self, locator, at, upto, count, every, between, minor): + + log_base, symlog_thresh = self._parse_for_log_params(self.trans) + + if locator is not None: + major_locator = locator + + elif upto is not None: + if log_base: + major_locator = LogLocator(base=log_base, numticks=upto) + else: + major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10]) + + elif count is not None: + if between is None: + # This is rarely useful (unless you are setting limits) + major_locator = LinearLocator(count) + else: + if log_base or symlog_thresh: + forward, inverse = self._get_transform() + lo, hi = forward(between) + ticks = inverse(np.linspace(lo, hi, num=count)) + else: + ticks = np.linspace(*between, num=count) + major_locator = FixedLocator(ticks) + + elif every is not None: + if between is None: + major_locator = MultipleLocator(every) + else: + lo, hi = between + ticks = np.arange(lo, hi + every, every) + major_locator = FixedLocator(ticks) + + elif at is not None: + major_locator = FixedLocator(at) + + else: + if log_base: + major_locator = LogLocator(log_base) + elif symlog_thresh: + major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10) + else: + major_locator = AutoLocator() + + if minor is None: + minor_locator = LogLocator(log_base, subs=None) if log_base else None + else: + if log_base: + subs = np.linspace(0, log_base, minor + 2)[1:-1] + minor_locator = LogLocator(log_base, subs=subs) + else: + minor_locator = AutoMinorLocator(minor + 1) + + return major_locator, minor_locator + + def _get_formatter(self, locator, formatter, like, base, unit): + + log_base, symlog_thresh = self._parse_for_log_params(self.trans) + if base is default: + if symlog_thresh: + log_base = 10 + base = log_base + + if formatter is not None: + return formatter + + if like is not None: + if isinstance(like, str): + if "{x" in like or "{pos" in like: + fmt = like + else: + fmt = f"{{x:{like}}}" + formatter = StrMethodFormatter(fmt) + else: + formatter = FuncFormatter(like) + + elif base is not None: + # We could add other log options if necessary + formatter = LogFormatterSciNotation(base) + + elif unit is not None: + if isinstance(unit, tuple): + sep, unit = unit + elif not unit: + sep = "" + else: + sep = " " + formatter = EngFormatter(unit, sep=sep) + + else: + formatter = ScalarFormatter() + + return formatter + + +@dataclass +class Temporal(ContinuousBase): + """ + A scale for date/time data. + """ + # TODO date: bool? + # For when we only care about the time component, would affect + # default formatter and norm conversion. Should also happen in + # Property.default_scale. The alternative was having distinct + # Calendric / Temporal scales, but that feels a bit fussy, and it + # would get in the way of using first-letter shorthands because + # Calendric and Continuous would collide. Still, we haven't implemented + # those yet, and having a clear distinction betewen date(time) / time + # may be more useful. + + trans = None + + _priority: ClassVar[int] = 2 + + def tick( + self, locator: Locator | None = None, *, + upto: int | None = None, + ) -> Temporal: + """ + Configure the selection of ticks for the scale's axis or legend. + + .. note:: + This API is under construction and will be enhanced over time. + + Parameters + ---------- + locator : :class:`matplotlib.ticker.Locator` subclass + Pre-configured matplotlib locator; other parameters will not be used. + upto : int + Choose "nice" locations for ticks, but do not exceed this number. + + Returns + ------- + scale + Copy of self with new tick configuration. + + """ + if locator is not None and not isinstance(locator, Locator): + err = ( + f"Tick locator must be an instance of {Locator!r}, " + f"not {type(locator)!r}." + ) + raise TypeError(err) + + new = copy(self) + new._tick_params = {"locator": locator, "upto": upto} + return new + + def label( + self, + formatter: Formatter | None = None, *, + concise: bool = False, + ) -> Temporal: + """ + Configure the appearance of tick labels for the scale's axis or legend. + + .. note:: + This API is under construction and will be enhanced over time. + + Parameters + ---------- + formatter : :class:`matplotlib.ticker.Formatter` subclass + Pre-configured formatter to use; other parameters will be ignored. + concise : bool + If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make + the tick labels as compact as possible. + + Returns + ------- + scale + Copy of self with new label configuration. + + """ + new = copy(self) + new._label_params = {"formatter": formatter, "concise": concise} + return new + + def _get_locators(self, locator, upto): + + if locator is not None: + major_locator = locator + elif upto is not None: + major_locator = AutoDateLocator(minticks=2, maxticks=upto) + + else: + major_locator = AutoDateLocator(minticks=2, maxticks=6) + minor_locator = None + + return major_locator, minor_locator + + def _get_formatter(self, locator, formatter, concise): + + if formatter is not None: + return formatter + + if concise: + # TODO ideally we would have concise coordinate ticks, + # but full semantic ticks. Is that possible? + formatter = ConciseDateFormatter(locator) + else: + formatter = AutoDateFormatter(locator) + + return formatter + + +# ----------------------------------------------------------------------------------- # + + +# TODO Have this separate from Temporal or have Temporal(date=True) or similar? +# class Calendric(Scale): + +# TODO Needed? Or handle this at layer (in stat or as param, eg binning=) +# class Binned(Scale): + +# TODO any need for color-specific scales? +# class Sequential(Continuous): +# class Diverging(Continuous): +# class Qualitative(Nominal): + + +# ----------------------------------------------------------------------------------- # + + +class PseudoAxis: + """ + Internal class implementing minimal interface equivalent to matplotlib Axis. + + Coordinate variables are typically scaled by attaching the Axis object from + the figure where the plot will end up. Matplotlib has no similar concept of + and axis for the other mappable variables (color, etc.), but to simplify the + code, this object acts like an Axis and can be used to scale other variables. + + """ + axis_name = "" # Matplotlib requirement but not actually used + + def __init__(self, scale): + + self.converter = None + self.units = None + self.scale = scale + self.major = mpl.axis.Ticker() + self.minor = mpl.axis.Ticker() + + # It appears that this needs to be initialized this way on matplotlib 3.1, + # but not later versions. It is unclear whether there are any issues with it. + self._data_interval = None, None + + scale.set_default_locators_and_formatters(self) + # self.set_default_intervals() Is this ever needed? + + def set_view_interval(self, vmin, vmax): + self._view_interval = vmin, vmax + + def get_view_interval(self): + return self._view_interval + + # TODO do we want to distinguish view/data intervals? e.g. for a legend + # we probably want to represent the full range of the data values, but + # still norm the colormap. If so, we'll need to track data range separately + # from the norm, which we currently don't do. + + def set_data_interval(self, vmin, vmax): + self._data_interval = vmin, vmax + + def get_data_interval(self): + return self._data_interval + + def get_tick_space(self): + # TODO how to do this in a configurable / auto way? + # Would be cool to have legend density adapt to figure size, etc. + return 5 + + def set_major_locator(self, locator): + self.major.locator = locator + locator.set_axis(self) + + def set_major_formatter(self, formatter): + self.major.formatter = formatter + formatter.set_axis(self) + + def set_minor_locator(self, locator): + self.minor.locator = locator + locator.set_axis(self) + + def set_minor_formatter(self, formatter): + self.minor.formatter = formatter + formatter.set_axis(self) + + def set_units(self, units): + self.units = units + + def update_units(self, x): + """Pass units to the internal converter, potentially updating its mapping.""" + self.converter = mpl.units.registry.get_converter(x) + if self.converter is not None: + self.converter.default_units(x, self) + + info = self.converter.axisinfo(self.units, self) + + if info is None: + return + if info.majloc is not None: + self.set_major_locator(info.majloc) + if info.majfmt is not None: + self.set_major_formatter(info.majfmt) + + # This is in matplotlib method; do we need this? + # self.set_default_intervals() + + def convert_units(self, x): + """Return a numeric representation of the input data.""" + if np.issubdtype(np.asarray(x).dtype, np.number): + return x + elif self.converter is None: + return x + return self.converter.convert(x, self.units, self) + + def get_scale(self): + # Note that matplotlib actually returns a string here! + # (e.g., with a log scale, axis.get_scale() returns "log") + # Currently we just hit it with minor ticks where it checks for + # scale == "log". I'm not sure how you'd actually use log-scale + # minor "ticks" in a legend context, so this is fine.... + return self.scale + + def get_majorticklocs(self): + return self.major.locator() + + +# ------------------------------------------------------------------------------------ # +# Transform function creation + + +def _make_identity_transforms() -> TransFuncs: + + def identity(x): + return x + + return identity, identity + + +def _make_logit_transforms(base: float | None = None) -> TransFuncs: + + log, exp = _make_log_transforms(base) + + def logit(x): + with np.errstate(invalid="ignore", divide="ignore"): + return log(x) - log(1 - x) + + def expit(x): + with np.errstate(invalid="ignore", divide="ignore"): + return exp(x) / (1 + exp(x)) + + return logit, expit + + +def _make_log_transforms(base: float | None = None) -> TransFuncs: + + fs: TransFuncs + if base is None: + fs = np.log, np.exp + elif base == 2: + fs = np.log2, partial(np.power, 2) + elif base == 10: + fs = np.log10, partial(np.power, 10) + else: + def forward(x): + return np.log(x) / np.log(base) + fs = forward, partial(np.power, base) + + def log(x: ArrayLike) -> ArrayLike: + with np.errstate(invalid="ignore", divide="ignore"): + return fs[0](x) + + def exp(x: ArrayLike) -> ArrayLike: + with np.errstate(invalid="ignore", divide="ignore"): + return fs[1](x) + + return log, exp + + +def _make_symlog_transforms(c: float = 1, base: float = 10) -> TransFuncs: + + # From https://iopscience.iop.org/article/10.1088/0957-0233/24/2/027001 + + # Note: currently not using base because we only get + # one parameter from the string, and are using c (this is consistent with d3) + + log, exp = _make_log_transforms(base) + + def symlog(x): + with np.errstate(invalid="ignore", divide="ignore"): + return np.sign(x) * log(1 + np.abs(np.divide(x, c))) + + def symexp(x): + with np.errstate(invalid="ignore", divide="ignore"): + return np.sign(x) * c * (exp(np.abs(x)) - 1) + + return symlog, symexp + + +def _make_sqrt_transforms() -> TransFuncs: + + def sqrt(x): + return np.sign(x) * np.sqrt(np.abs(x)) + + def square(x): + return np.sign(x) * np.square(x) + + return sqrt, square + + +def _make_power_transforms(exp: float) -> TransFuncs: + + def forward(x): + return np.sign(x) * np.power(np.abs(x), exp) + + def inverse(x): + return np.sign(x) * np.power(np.abs(x), 1 / exp) + + return forward, inverse + + +def _default_spacer(x: Series) -> float: + return 1 diff --git a/testbed/mwaskom__seaborn/seaborn/_core/subplots.py b/testbed/mwaskom__seaborn/seaborn/_core/subplots.py new file mode 100644 index 0000000000000000000000000000000000000000..83b8e136ad37dd8dc28f754d13db83c9dfbcf4f0 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/subplots.py @@ -0,0 +1,269 @@ +from __future__ import annotations +from collections.abc import Generator + +import numpy as np +import matplotlib as mpl +import matplotlib.pyplot as plt + +from matplotlib.axes import Axes +from matplotlib.figure import Figure +from typing import TYPE_CHECKING +if TYPE_CHECKING: # TODO move to seaborn._core.typing? + from seaborn._core.plot import FacetSpec, PairSpec + from matplotlib.figure import SubFigure + + +class Subplots: + """ + Interface for creating and using matplotlib subplots based on seaborn parameters. + + Parameters + ---------- + subplot_spec : dict + Keyword args for :meth:`matplotlib.figure.Figure.subplots`. + facet_spec : dict + Parameters that control subplot faceting. + pair_spec : dict + Parameters that control subplot pairing. + data : PlotData + Data used to define figure setup. + + """ + def __init__( + self, + subplot_spec: dict, # TODO define as TypedDict + facet_spec: FacetSpec, + pair_spec: PairSpec, + ): + + self.subplot_spec = subplot_spec + + self._check_dimension_uniqueness(facet_spec, pair_spec) + self._determine_grid_dimensions(facet_spec, pair_spec) + self._handle_wrapping(facet_spec, pair_spec) + self._determine_axis_sharing(pair_spec) + + def _check_dimension_uniqueness( + self, facet_spec: FacetSpec, pair_spec: PairSpec + ) -> None: + """Reject specs that pair and facet on (or wrap to) same figure dimension.""" + err = None + + facet_vars = facet_spec.get("variables", {}) + + if facet_spec.get("wrap") and {"col", "row"} <= set(facet_vars): + err = "Cannot wrap facets when specifying both `col` and `row`." + elif ( + pair_spec.get("wrap") + and pair_spec.get("cross", True) + and len(pair_spec.get("structure", {}).get("x", [])) > 1 + and len(pair_spec.get("structure", {}).get("y", [])) > 1 + ): + err = "Cannot wrap subplots when pairing on both `x` and `y`." + + collisions = {"x": ["columns", "rows"], "y": ["rows", "columns"]} + for pair_axis, (multi_dim, wrap_dim) in collisions.items(): + if pair_axis not in pair_spec.get("structure", {}): + continue + elif multi_dim[:3] in facet_vars: + err = f"Cannot facet the {multi_dim} while pairing on `{pair_axis}``." + elif wrap_dim[:3] in facet_vars and facet_spec.get("wrap"): + err = f"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``." + elif wrap_dim[:3] in facet_vars and pair_spec.get("wrap"): + err = f"Cannot wrap the {multi_dim} while faceting the {wrap_dim}." + + if err is not None: + raise RuntimeError(err) # TODO what err class? Define PlotSpecError? + + def _determine_grid_dimensions( + self, facet_spec: FacetSpec, pair_spec: PairSpec + ) -> None: + """Parse faceting and pairing information to define figure structure.""" + self.grid_dimensions: dict[str, list] = {} + for dim, axis in zip(["col", "row"], ["x", "y"]): + + facet_vars = facet_spec.get("variables", {}) + if dim in facet_vars: + self.grid_dimensions[dim] = facet_spec["structure"][dim] + elif axis in pair_spec.get("structure", {}): + self.grid_dimensions[dim] = [ + None for _ in pair_spec.get("structure", {})[axis] + ] + else: + self.grid_dimensions[dim] = [None] + + self.subplot_spec[f"n{dim}s"] = len(self.grid_dimensions[dim]) + + if not pair_spec.get("cross", True): + self.subplot_spec["nrows"] = 1 + + self.n_subplots = self.subplot_spec["ncols"] * self.subplot_spec["nrows"] + + def _handle_wrapping( + self, facet_spec: FacetSpec, pair_spec: PairSpec + ) -> None: + """Update figure structure parameters based on facet/pair wrapping.""" + self.wrap = wrap = facet_spec.get("wrap") or pair_spec.get("wrap") + if not wrap: + return + + wrap_dim = "row" if self.subplot_spec["nrows"] > 1 else "col" + flow_dim = {"row": "col", "col": "row"}[wrap_dim] + n_subplots = self.subplot_spec[f"n{wrap_dim}s"] + flow = int(np.ceil(n_subplots / wrap)) + + if wrap < self.subplot_spec[f"n{wrap_dim}s"]: + self.subplot_spec[f"n{wrap_dim}s"] = wrap + self.subplot_spec[f"n{flow_dim}s"] = flow + self.n_subplots = n_subplots + self.wrap_dim = wrap_dim + + def _determine_axis_sharing(self, pair_spec: PairSpec) -> None: + """Update subplot spec with default or specified axis sharing parameters.""" + axis_to_dim = {"x": "col", "y": "row"} + key: str + val: str | bool + for axis in "xy": + key = f"share{axis}" + # Always use user-specified value, if present + if key not in self.subplot_spec: + if axis in pair_spec.get("structure", {}): + # Paired axes are shared along one dimension by default + if self.wrap is None and pair_spec.get("cross", True): + val = axis_to_dim[axis] + else: + val = False + else: + # This will pick up faceted plots, as well as single subplot + # figures, where the value doesn't really matter + val = True + self.subplot_spec[key] = val + + def init_figure( + self, + pair_spec: PairSpec, + pyplot: bool = False, + figure_kws: dict | None = None, + target: Axes | Figure | SubFigure = None, + ) -> Figure: + """Initialize matplotlib objects and add seaborn-relevant metadata.""" + # TODO reduce need to pass pair_spec here? + + if figure_kws is None: + figure_kws = {} + + if isinstance(target, mpl.axes.Axes): + + if max(self.subplot_spec["nrows"], self.subplot_spec["ncols"]) > 1: + err = " ".join([ + "Cannot create multiple subplots after calling `Plot.on` with", + f"a {mpl.axes.Axes} object.", + ]) + try: + err += f" You may want to use a {mpl.figure.SubFigure} instead." + except AttributeError: # SubFigure added in mpl 3.4 + pass + raise RuntimeError(err) + + self._subplot_list = [{ + "ax": target, + "left": True, + "right": True, + "top": True, + "bottom": True, + "col": None, + "row": None, + "x": "x", + "y": "y", + }] + self._figure = target.figure + return self._figure + + elif ( + hasattr(mpl.figure, "SubFigure") # Added in mpl 3.4 + and isinstance(target, mpl.figure.SubFigure) + ): + figure = target.figure + elif isinstance(target, mpl.figure.Figure): + figure = target + else: + if pyplot: + figure = plt.figure(**figure_kws) + else: + figure = mpl.figure.Figure(**figure_kws) + target = figure + self._figure = figure + + axs = target.subplots(**self.subplot_spec, squeeze=False) + + if self.wrap: + # Remove unused Axes and flatten the rest into a (2D) vector + axs_flat = axs.ravel({"col": "C", "row": "F"}[self.wrap_dim]) + axs, extra = np.split(axs_flat, [self.n_subplots]) + for ax in extra: + ax.remove() + if self.wrap_dim == "col": + axs = axs[np.newaxis, :] + else: + axs = axs[:, np.newaxis] + + # Get i, j coordinates for each Axes object + # Note that i, j are with respect to faceting/pairing, + # not the subplot grid itself, (which only matters in the case of wrapping). + iter_axs: np.ndenumerate | zip + if not pair_spec.get("cross", True): + indices = np.arange(self.n_subplots) + iter_axs = zip(zip(indices, indices), axs.flat) + else: + iter_axs = np.ndenumerate(axs) + + self._subplot_list = [] + for (i, j), ax in iter_axs: + + info = {"ax": ax} + + nrows, ncols = self.subplot_spec["nrows"], self.subplot_spec["ncols"] + if not self.wrap: + info["left"] = j % ncols == 0 + info["right"] = (j + 1) % ncols == 0 + info["top"] = i == 0 + info["bottom"] = i == nrows - 1 + elif self.wrap_dim == "col": + info["left"] = j % ncols == 0 + info["right"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots) + info["top"] = j < ncols + info["bottom"] = j >= (self.n_subplots - ncols) + elif self.wrap_dim == "row": + info["left"] = i < nrows + info["right"] = i >= self.n_subplots - nrows + info["top"] = i % nrows == 0 + info["bottom"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots) + + if not pair_spec.get("cross", True): + info["top"] = j < ncols + info["bottom"] = j >= self.n_subplots - ncols + + for dim in ["row", "col"]: + idx = {"row": i, "col": j}[dim] + info[dim] = self.grid_dimensions[dim][idx] + + for axis in "xy": + + idx = {"x": j, "y": i}[axis] + if axis in pair_spec.get("structure", {}): + key = f"{axis}{idx}" + else: + key = axis + info[axis] = key + + self._subplot_list.append(info) + + return figure + + def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict? + """Yield each subplot dictionary with Axes object and metadata.""" + yield from self._subplot_list + + def __len__(self) -> int: + """Return the number of subplots in this figure.""" + return len(self._subplot_list) diff --git a/testbed/mwaskom__seaborn/seaborn/_core/typing.py b/testbed/mwaskom__seaborn/seaborn/_core/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..5295b995e47028d210f8a08cef9ae5a35d2f8543 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_core/typing.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from datetime import date, datetime, timedelta +from typing import Any, Optional, Union, Mapping, Tuple, List, Dict +from collections.abc import Hashable, Iterable + +from numpy import ndarray # TODO use ArrayLike? +from pandas import DataFrame, Series, Index, Timestamp, Timedelta +from matplotlib.colors import Colormap, Normalize + + +ColumnName = Union[ + str, bytes, date, datetime, timedelta, bool, complex, Timestamp, Timedelta +] +Vector = Union[Series, Index, ndarray] + +VariableSpec = Union[ColumnName, Vector, None] +VariableSpecList = Union[List[VariableSpec], Index, None] + +DataSource = Union[DataFrame, Mapping[Hashable, Vector], None] + +OrderSpec = Union[Iterable, None] # TODO technically str is iterable +NormSpec = Union[Tuple[Optional[float], Optional[float]], Normalize, None] + +# TODO for discrete mappings, it would be ideal to use a parameterized type +# as the dict values / list entries should be of specific type(s) for each method +PaletteSpec = Union[str, list, dict, Colormap, None] +DiscreteValueSpec = Union[dict, list, None] +ContinuousValueSpec = Union[ + Tuple[float, float], List[float], Dict[Any, float], None, +] + + +class Default: + def __repr__(self): + return "" + + +default = Default() diff --git a/testbed/mwaskom__seaborn/seaborn/_decorators.py b/testbed/mwaskom__seaborn/seaborn/_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7b2e9b49c810f1483f73d06f3cac8908b576b2 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_decorators.py @@ -0,0 +1,16 @@ +from inspect import signature + + +def share_init_params_with_map(cls): + """Make cls.map a classmethod with same signature as cls.__init__.""" + map_sig = signature(cls.map) + init_sig = signature(cls.__init__) + + new = [v for k, v in init_sig.parameters.items() if k != "self"] + new.insert(0, map_sig.parameters["cls"]) + cls.map.__signature__ = map_sig.replace(parameters=new) + cls.map.__doc__ = cls.__init__.__doc__ + + cls.map = classmethod(cls.map) + + return cls diff --git a/testbed/mwaskom__seaborn/seaborn/_docstrings.py b/testbed/mwaskom__seaborn/seaborn/_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab210b6ffbf63f21ebee9a4a3d59dcbc94fcb57 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_docstrings.py @@ -0,0 +1,198 @@ +import re +import pydoc +from .external.docscrape import NumpyDocString + + +class DocstringComponents: + + regexp = re.compile(r"\n((\n|.)+)\n\s*", re.MULTILINE) + + def __init__(self, comp_dict, strip_whitespace=True): + """Read entries from a dict, optionally stripping outer whitespace.""" + if strip_whitespace: + entries = {} + for key, val in comp_dict.items(): + m = re.match(self.regexp, val) + if m is None: + entries[key] = val + else: + entries[key] = m.group(1) + else: + entries = comp_dict.copy() + + self.entries = entries + + def __getattr__(self, attr): + """Provide dot access to entries for clean raw docstrings.""" + if attr in self.entries: + return self.entries[attr] + else: + try: + return self.__getattribute__(attr) + except AttributeError as err: + # If Python is run with -OO, it will strip docstrings and our lookup + # from self.entries will fail. We check for __debug__, which is actually + # set to False by -O (it is True for normal execution). + # But we only want to see an error when building the docs; + # not something users should see, so this slight inconsistency is fine. + if __debug__: + raise err + else: + pass + + @classmethod + def from_nested_components(cls, **kwargs): + """Add multiple sub-sets of components.""" + return cls(kwargs, strip_whitespace=False) + + @classmethod + def from_function_params(cls, func): + """Use the numpydoc parser to extract components from existing func.""" + params = NumpyDocString(pydoc.getdoc(func))["Parameters"] + comp_dict = {} + for p in params: + name = p.name + type = p.type + desc = "\n ".join(p.desc) + comp_dict[name] = f"{name} : {type}\n {desc}" + + return cls(comp_dict) + + +# TODO is "vector" the best term here? We mean to imply 1D data with a variety +# of types? + +# TODO now that we can parse numpydoc style strings, do we need to define dicts +# of docstring components, or just write out a docstring? + + +_core_params = dict( + data=""" +data : :class:`pandas.DataFrame`, :class:`numpy.ndarray`, mapping, or sequence + Input data structure. Either a long-form collection of vectors that can be + assigned to named variables or a wide-form dataset that will be internally + reshaped. + """, # TODO add link to user guide narrative when exists + xy=""" +x, y : vectors or keys in ``data`` + Variables that specify positions on the x and y axes. + """, + hue=""" +hue : vector or key in ``data`` + Semantic variable that is mapped to determine the color of plot elements. + """, + palette=""" +palette : string, list, dict, or :class:`matplotlib.colors.Colormap` + Method for choosing the colors to use when mapping the ``hue`` semantic. + String values are passed to :func:`color_palette`. List or dict values + imply categorical mapping, while a colormap object implies numeric mapping. + """, # noqa: E501 + hue_order=""" +hue_order : vector of strings + Specify the order of processing and plotting for categorical levels of the + ``hue`` semantic. + """, + hue_norm=""" +hue_norm : tuple or :class:`matplotlib.colors.Normalize` + Either a pair of values that set the normalization range in data units + or an object that will map from data units into a [0, 1] interval. Usage + implies numeric mapping. + """, + color=""" +color : :mod:`matplotlib color ` + Single color specification for when hue mapping is not used. Otherwise, the + plot will try to hook into the matplotlib property cycle. + """, + ax=""" +ax : :class:`matplotlib.axes.Axes` + Pre-existing axes for the plot. Otherwise, call :func:`matplotlib.pyplot.gca` + internally. + """, # noqa: E501 +) + + +_core_returns = dict( + ax=""" +:class:`matplotlib.axes.Axes` + The matplotlib axes containing the plot. + """, + facetgrid=""" +:class:`FacetGrid` + An object managing one or more subplots that correspond to conditional data + subsets with convenient methods for batch-setting of axes attributes. + """, + jointgrid=""" +:class:`JointGrid` + An object managing multiple subplots that correspond to joint and marginal axes + for plotting a bivariate relationship or distribution. + """, + pairgrid=""" +:class:`PairGrid` + An object managing multiple subplots that correspond to joint and marginal axes + for pairwise combinations of multiple variables in a dataset. + """, +) + + +_seealso_blurbs = dict( + + # Relational plots + scatterplot=""" +scatterplot : Plot data using points. + """, + lineplot=""" +lineplot : Plot data using lines. + """, + + # Distribution plots + displot=""" +displot : Figure-level interface to distribution plot functions. + """, + histplot=""" +histplot : Plot a histogram of binned counts with optional normalization or smoothing. + """, + kdeplot=""" +kdeplot : Plot univariate or bivariate distributions using kernel density estimation. + """, + ecdfplot=""" +ecdfplot : Plot empirical cumulative distribution functions. + """, + rugplot=""" +rugplot : Plot a tick at each observation value along the x and/or y axes. + """, + + # Categorical plots + stripplot=""" +stripplot : Plot a categorical scatter with jitter. + """, + swarmplot=""" +swarmplot : Plot a categorical scatter with non-overlapping points. + """, + violinplot=""" +violinplot : Draw an enhanced boxplot using kernel density estimation. + """, + pointplot=""" +pointplot : Plot point estimates and CIs using markers and lines. + """, + + # Multiples + jointplot=""" +jointplot : Draw a bivariate plot with univariate marginal distributions. + """, + pairplot=""" +jointplot : Draw multiple bivariate plots with univariate marginal distributions. + """, + jointgrid=""" +JointGrid : Set up a figure with joint and marginal views on bivariate data. + """, + pairgrid=""" +PairGrid : Set up a figure with joint and marginal views on multiple variables. + """, +) + + +_core_docs = dict( + params=DocstringComponents(_core_params), + returns=DocstringComponents(_core_returns), + seealso=DocstringComponents(_seealso_blurbs), +) diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/__init__.py b/testbed/mwaskom__seaborn/seaborn/_marks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/area.py b/testbed/mwaskom__seaborn/seaborn/_marks/area.py new file mode 100644 index 0000000000000000000000000000000000000000..7514a6d13b7a373ff3c89ccbe06abec77442c0f2 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/area.py @@ -0,0 +1,170 @@ +from __future__ import annotations +from collections import defaultdict +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableBool, + MappableFloat, + MappableColor, + MappableStyle, + resolve_properties, + resolve_color, + document_properties, +) + + +class AreaBase: + + def _plot(self, split_gen, scales, orient): + + patches = defaultdict(list) + + for keys, data, ax in split_gen(): + + kws = {} + data = self._standardize_coordinate_parameters(data, orient) + resolved = resolve_properties(self, keys, scales) + verts = self._get_verts(data, orient) + ax.update_datalim(verts) + + # TODO should really move this logic into resolve_color + fc = resolve_color(self, keys, "", scales) + if not resolved["fill"]: + fc = mpl.colors.to_rgba(fc, 0) + + kws["facecolor"] = fc + kws["edgecolor"] = resolve_color(self, keys, "edge", scales) + kws["linewidth"] = resolved["edgewidth"] + kws["linestyle"] = resolved["edgestyle"] + + patches[ax].append(mpl.patches.Polygon(verts, **kws)) + + for ax, ax_patches in patches.items(): + + for patch in ax_patches: + self._postprocess_artist(patch, ax, orient) + ax.add_patch(patch) + + def _standardize_coordinate_parameters(self, data, orient): + return data + + def _postprocess_artist(self, artist, ax, orient): + pass + + def _get_verts(self, data, orient): + + dv = {"x": "y", "y": "x"}[orient] + data = data.sort_values(orient, kind="mergesort") + verts = np.concatenate([ + data[[orient, f"{dv}min"]].to_numpy(), + data[[orient, f"{dv}max"]].to_numpy()[::-1], + ]) + if orient == "y": + verts = verts[:, ::-1] + return verts + + def _legend_artist(self, variables, value, scales): + + keys = {v: value for v in variables} + resolved = resolve_properties(self, keys, scales) + + fc = resolve_color(self, keys, "", scales) + if not resolved["fill"]: + fc = mpl.colors.to_rgba(fc, 0) + + return mpl.patches.Patch( + facecolor=fc, + edgecolor=resolve_color(self, keys, "edge", scales), + linewidth=resolved["edgewidth"], + linestyle=resolved["edgestyle"], + **self.artist_kws, + ) + + +@document_properties +@dataclass +class Area(AreaBase, Mark): + """ + A fill mark drawn from a baseline to data values. + + See also + -------- + Band : A fill mark representing an interval between values. + + Examples + -------- + .. include:: ../docstrings/objects.Area.rst + + """ + color: MappableColor = Mappable("C0", ) + alpha: MappableFloat = Mappable(.2, ) + fill: MappableBool = Mappable(True, ) + edgecolor: MappableColor = Mappable(depend="color") + edgealpha: MappableFloat = Mappable(1, ) + edgewidth: MappableFloat = Mappable(rc="patch.linewidth", ) + edgestyle: MappableStyle = Mappable("-", ) + + # TODO should this be settable / mappable? + baseline: MappableFloat = Mappable(0, grouping=False) + + def _standardize_coordinate_parameters(self, data, orient): + dv = {"x": "y", "y": "x"}[orient] + return data.rename(columns={"baseline": f"{dv}min", dv: f"{dv}max"}) + + def _postprocess_artist(self, artist, ax, orient): + + # TODO copying a lot of code from Bar, let's abstract this + # See comments there, I am not going to repeat them too + + artist.set_linewidth(artist.get_linewidth() * 2) + + linestyle = artist.get_linestyle() + if linestyle[1]: + linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1])) + artist.set_linestyle(linestyle) + + artist.set_clip_path(artist.get_path(), artist.get_transform() + ax.transData) + if self.artist_kws.get("clip_on", True): + artist.set_clip_box(ax.bbox) + + val_idx = ["y", "x"].index(orient) + artist.sticky_edges[val_idx][:] = (0, np.inf) + + +@document_properties +@dataclass +class Band(AreaBase, Mark): + """ + A fill mark representing an interval between values. + + See also + -------- + Area : A fill mark drawn from a baseline to data values. + + Examples + -------- + .. include:: ../docstrings/objects.Band.rst + + """ + color: MappableColor = Mappable("C0", ) + alpha: MappableFloat = Mappable(.2, ) + fill: MappableBool = Mappable(True, ) + edgecolor: MappableColor = Mappable(depend="color", ) + edgealpha: MappableFloat = Mappable(1, ) + edgewidth: MappableFloat = Mappable(0, ) + edgestyle: MappableFloat = Mappable("-", ) + + def _standardize_coordinate_parameters(self, data, orient): + # dv = {"x": "y", "y": "x"}[orient] + # TODO assert that all(ymax >= ymin)? + # TODO what if only one exist? + other = {"x": "y", "y": "x"}[orient] + if not set(data.columns) & {f"{other}min", f"{other}max"}: + agg = {f"{other}min": (other, "min"), f"{other}max": (other, "max")} + data = data.groupby(orient).agg(**agg).reset_index() + return data diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/bar.py b/testbed/mwaskom__seaborn/seaborn/_marks/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..729f4fe89d6e5bbc6ead47ed150c74e17c4a856c --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/bar.py @@ -0,0 +1,250 @@ +from __future__ import annotations +from collections import defaultdict +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableBool, + MappableColor, + MappableFloat, + MappableStyle, + resolve_properties, + resolve_color, + document_properties +) +from seaborn.utils import _version_predates + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from typing import Any + from matplotlib.artist import Artist + from seaborn._core.scales import Scale + + +class BarBase(Mark): + + def _make_patches(self, data, scales, orient): + + kws = self._resolve_properties(data, scales) + if orient == "x": + kws["x"] = (data["x"] - data["width"] / 2).to_numpy() + kws["y"] = data["baseline"].to_numpy() + kws["w"] = data["width"].to_numpy() + kws["h"] = (data["y"] - data["baseline"]).to_numpy() + else: + kws["x"] = data["baseline"].to_numpy() + kws["y"] = (data["y"] - data["width"] / 2).to_numpy() + kws["w"] = (data["x"] - data["baseline"]).to_numpy() + kws["h"] = data["width"].to_numpy() + + kws.pop("width", None) + kws.pop("baseline", None) + + val_dim = {"x": "h", "y": "w"}[orient] + bars, vals = [], [] + + for i in range(len(data)): + + row = {k: v[i] for k, v in kws.items()} + + # Skip bars with no value. It's possible we'll want to make this + # an option (i.e so you have an artist for animating or annotating), + # but let's keep things simple for now. + if not np.nan_to_num(row[val_dim]): + continue + + bar = mpl.patches.Rectangle( + xy=(row["x"], row["y"]), + width=row["w"], + height=row["h"], + facecolor=row["facecolor"], + edgecolor=row["edgecolor"], + linestyle=row["edgestyle"], + linewidth=row["edgewidth"], + **self.artist_kws, + ) + bars.append(bar) + vals.append(row[val_dim]) + + return bars, vals + + def _resolve_properties(self, data, scales): + + resolved = resolve_properties(self, data, scales) + + resolved["facecolor"] = resolve_color(self, data, "", scales) + resolved["edgecolor"] = resolve_color(self, data, "edge", scales) + + fc = resolved["facecolor"] + if isinstance(fc, tuple): + resolved["facecolor"] = fc[0], fc[1], fc[2], fc[3] * resolved["fill"] + else: + fc[:, 3] = fc[:, 3] * resolved["fill"] # TODO Is inplace mod a problem? + resolved["facecolor"] = fc + + return resolved + + def _legend_artist( + self, variables: list[str], value: Any, scales: dict[str, Scale], + ) -> Artist: + # TODO return some sensible default? + key = {v: value for v in variables} + key = self._resolve_properties(key, scales) + artist = mpl.patches.Patch( + facecolor=key["facecolor"], + edgecolor=key["edgecolor"], + linewidth=key["edgewidth"], + linestyle=key["edgestyle"], + ) + return artist + + +@document_properties +@dataclass +class Bar(BarBase): + """ + A bar mark drawn between baseline and data values. + + See also + -------- + Bars : A faster bar mark with defaults more suitable for histograms. + + Examples + -------- + .. include:: ../docstrings/objects.Bar.rst + + """ + color: MappableColor = Mappable("C0", grouping=False) + alpha: MappableFloat = Mappable(.7, grouping=False) + fill: MappableBool = Mappable(True, grouping=False) + edgecolor: MappableColor = Mappable(depend="color", grouping=False) + edgealpha: MappableFloat = Mappable(1, grouping=False) + edgewidth: MappableFloat = Mappable(rc="patch.linewidth", grouping=False) + edgestyle: MappableStyle = Mappable("-", grouping=False) + # pattern: MappableString = Mappable(None) # TODO no Property yet + + width: MappableFloat = Mappable(.8, grouping=False) + baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable? + + def _plot(self, split_gen, scales, orient): + + val_idx = ["y", "x"].index(orient) + + for _, data, ax in split_gen(): + + bars, vals = self._make_patches(data, scales, orient) + + for bar in bars: + + # Because we are clipping the artist (see below), the edges end up + # looking half as wide as they actually are. I don't love this clumsy + # workaround, which is going to cause surprises if you work with the + # artists directly. We may need to revisit after feedback. + bar.set_linewidth(bar.get_linewidth() * 2) + linestyle = bar.get_linestyle() + if linestyle[1]: + linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1])) + bar.set_linestyle(linestyle) + + # This is a bit of a hack to handle the fact that the edge lines are + # centered on the actual extents of the bar, and overlap when bars are + # stacked or dodged. We may discover that this causes problems and needs + # to be revisited at some point. Also it should be faster to clip with + # a bbox than a path, but I cant't work out how to get the intersection + # with the axes bbox. + bar.set_clip_path(bar.get_path(), bar.get_transform() + ax.transData) + if self.artist_kws.get("clip_on", True): + # It seems the above hack undoes the default axes clipping + bar.set_clip_box(ax.bbox) + bar.sticky_edges[val_idx][:] = (0, np.inf) + ax.add_patch(bar) + + # Add a container which is useful for, e.g. Axes.bar_label + if _version_predates(mpl, "3.4"): + container_kws = {} + else: + orientation = {"x": "vertical", "y": "horizontal"}[orient] + container_kws = dict(datavalues=vals, orientation=orientation) + container = mpl.container.BarContainer(bars, **container_kws) + ax.add_container(container) + + +@document_properties +@dataclass +class Bars(BarBase): + """ + A faster bar mark with defaults more suitable histograms. + + See also + -------- + Bar : A bar mark drawn between baseline and data values. + + Examples + -------- + .. include:: ../docstrings/objects.Bars.rst + + """ + color: MappableColor = Mappable("C0", grouping=False) + alpha: MappableFloat = Mappable(.7, grouping=False) + fill: MappableBool = Mappable(True, grouping=False) + edgecolor: MappableColor = Mappable(rc="patch.edgecolor", grouping=False) + edgealpha: MappableFloat = Mappable(1, grouping=False) + edgewidth: MappableFloat = Mappable(auto=True, grouping=False) + edgestyle: MappableStyle = Mappable("-", grouping=False) + # pattern: MappableString = Mappable(None) # TODO no Property yet + + width: MappableFloat = Mappable(1, grouping=False) + baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable? + + def _plot(self, split_gen, scales, orient): + + ori_idx = ["x", "y"].index(orient) + val_idx = ["y", "x"].index(orient) + + patches = defaultdict(list) + for _, data, ax in split_gen(): + bars, _ = self._make_patches(data, scales, orient) + patches[ax].extend(bars) + + collections = {} + for ax, ax_patches in patches.items(): + + col = mpl.collections.PatchCollection(ax_patches, match_original=True) + col.sticky_edges[val_idx][:] = (0, np.inf) + ax.add_collection(col, autolim=False) + collections[ax] = col + + # Workaround for matplotlib autoscaling bug + # https://github.com/matplotlib/matplotlib/issues/11898 + # https://github.com/matplotlib/matplotlib/issues/23129 + xys = np.vstack([path.vertices for path in col.get_paths()]) + ax.update_datalim(xys) + + if "edgewidth" not in scales and isinstance(self.edgewidth, Mappable): + + for ax in collections: + ax.autoscale_view() + + def get_dimensions(collection): + edges, widths = [], [] + for verts in (path.vertices for path in collection.get_paths()): + edges.append(min(verts[:, ori_idx])) + widths.append(np.ptp(verts[:, ori_idx])) + return np.array(edges), np.array(widths) + + min_width = np.inf + for ax, col in collections.items(): + edges, widths = get_dimensions(col) + points = 72 / ax.figure.dpi * abs( + ax.transData.transform([edges + widths] * 2) + - ax.transData.transform([edges] * 2) + ) + min_width = min(min_width, min(points[:, ori_idx])) + + linewidth = min(.1 * min_width, mpl.rcParams["patch.linewidth"]) + for _, col in collections.items(): + col.set_linewidth(linewidth) diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/base.py b/testbed/mwaskom__seaborn/seaborn/_marks/base.py new file mode 100644 index 0000000000000000000000000000000000000000..324d0221e7acb43c9124a4178f0f7d1f46b1a9a6 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/base.py @@ -0,0 +1,316 @@ +from __future__ import annotations +from dataclasses import dataclass, fields, field +import textwrap +from typing import Any, Callable, Union +from collections.abc import Generator + +import numpy as np +import pandas as pd +import matplotlib as mpl + +from numpy import ndarray +from pandas import DataFrame +from matplotlib.artist import Artist + +from seaborn._core.scales import Scale +from seaborn._core.properties import ( + PROPERTIES, + Property, + RGBATuple, + DashPattern, + DashPatternWithOffset, +) +from seaborn._core.exceptions import PlotSpecError + + +class Mappable: + def __init__( + self, + val: Any = None, + depend: str | None = None, + rc: str | None = None, + auto: bool = False, + grouping: bool = True, + ): + """ + Property that can be mapped from data or set directly, with flexible defaults. + + Parameters + ---------- + val : Any + Use this value as the default. + depend : str + Use the value of this feature as the default. + rc : str + Use the value of this rcParam as the default. + auto : bool + The default value will depend on other parameters at compile time. + grouping : bool + If True, use the mapped variable to define groups. + + """ + if depend is not None: + assert depend in PROPERTIES + if rc is not None: + assert rc in mpl.rcParams + + self._val = val + self._rc = rc + self._depend = depend + self._auto = auto + self._grouping = grouping + + def __repr__(self): + """Nice formatting for when object appears in Mark init signature.""" + if self._val is not None: + s = f"<{repr(self._val)}>" + elif self._depend is not None: + s = f"" + elif self._rc is not None: + s = f"" + elif self._auto: + s = "" + else: + s = "" + return s + + @property + def depend(self) -> Any: + """Return the name of the feature to source a default value from.""" + return self._depend + + @property + def grouping(self) -> bool: + return self._grouping + + @property + def default(self) -> Any: + """Get the default value for this feature, or access the relevant rcParam.""" + if self._val is not None: + return self._val + return mpl.rcParams.get(self._rc) + + +# TODO where is the right place to put this kind of type aliasing? + +MappableBool = Union[bool, Mappable] +MappableString = Union[str, Mappable] +MappableFloat = Union[float, Mappable] +MappableColor = Union[str, tuple, Mappable] +MappableStyle = Union[str, DashPattern, DashPatternWithOffset, Mappable] + + +@dataclass +class Mark: + """Base class for objects that visually represent data.""" + + artist_kws: dict = field(default_factory=dict) + + @property + def _mappable_props(self): + return { + f.name: getattr(self, f.name) for f in fields(self) + if isinstance(f.default, Mappable) + } + + @property + def _grouping_props(self): + # TODO does it make sense to have variation within a Mark's + # properties about whether they are grouping? + return [ + f.name for f in fields(self) + if isinstance(f.default, Mappable) and f.default.grouping + ] + + # TODO make this method private? Would extender every need to call directly? + def _resolve( + self, + data: DataFrame | dict[str, Any], + name: str, + scales: dict[str, Scale] | None = None, + ) -> Any: + """Obtain default, specified, or mapped value for a named feature. + + Parameters + ---------- + data : DataFrame or dict with scalar values + Container with data values for features that will be semantically mapped. + name : string + Identity of the feature / semantic. + scales: dict + Mapping from variable to corresponding scale object. + + Returns + ------- + value or array of values + Outer return type depends on whether `data` is a dict (implying that + we want a single value) or DataFrame (implying that we want an array + of values with matching length). + + """ + feature = self._mappable_props[name] + prop = PROPERTIES.get(name, Property(name)) + directly_specified = not isinstance(feature, Mappable) + return_multiple = isinstance(data, pd.DataFrame) + return_array = return_multiple and not name.endswith("style") + + # Special case width because it needs to be resolved and added to the dataframe + # during layer prep (so the Move operations use it properly). + # TODO how does width *scaling* work, e.g. for violin width by count? + if name == "width": + directly_specified = directly_specified and name not in data + + if directly_specified: + feature = prop.standardize(feature) + if return_multiple: + feature = [feature] * len(data) + if return_array: + feature = np.array(feature) + return feature + + if name in data: + if scales is None or name not in scales: + # TODO Might this obviate the identity scale? Just don't add a scale? + feature = data[name] + else: + scale = scales[name] + value = data[name] + try: + feature = scale(value) + except Exception as err: + raise PlotSpecError._during("Scaling operation", name) from err + + if return_array: + feature = np.asarray(feature) + return feature + + if feature.depend is not None: + # TODO add source_func or similar to transform the source value? + # e.g. set linewidth as a proportion of pointsize? + return self._resolve(data, feature.depend, scales) + + default = prop.standardize(feature.default) + if return_multiple: + default = [default] * len(data) + if return_array: + default = np.array(default) + return default + + def _infer_orient(self, scales: dict) -> str: # TODO type scales + + # TODO The original version of this (in seaborn._oldcore) did more checking. + # Paring that down here for the prototype to see what restrictions make sense. + + # TODO rethink this to map from scale type to "DV priority" and use that? + # e.g. Nominal > Discrete > Continuous + + x = 0 if "x" not in scales else scales["x"]._priority + y = 0 if "y" not in scales else scales["y"]._priority + + if y > x: + return "y" + else: + return "x" + + def _plot( + self, + split_generator: Callable[[], Generator], + scales: dict[str, Scale], + orient: str, + ) -> None: + """Main interface for creating a plot.""" + raise NotImplementedError() + + def _legend_artist( + self, variables: list[str], value: Any, scales: dict[str, Scale], + ) -> Artist: + + return None + + +def resolve_properties( + mark: Mark, data: DataFrame, scales: dict[str, Scale] +) -> dict[str, Any]: + + props = { + name: mark._resolve(data, name, scales) for name in mark._mappable_props + } + return props + + +def resolve_color( + mark: Mark, + data: DataFrame | dict, + prefix: str = "", + scales: dict[str, Scale] | None = None, +) -> RGBATuple | ndarray: + """ + Obtain a default, specified, or mapped value for a color feature. + + This method exists separately to support the relationship between a + color and its corresponding alpha. We want to respect alpha values that + are passed in specified (or mapped) color values but also make use of a + separate `alpha` variable, which can be mapped. This approach may also + be extended to support mapping of specific color channels (i.e. + luminance, chroma) in the future. + + Parameters + ---------- + mark : + Mark with the color property. + data : + Container with data values for features that will be semantically mapped. + prefix : + Support "color", "fillcolor", etc. + + """ + color = mark._resolve(data, f"{prefix}color", scales) + + if f"{prefix}alpha" in mark._mappable_props: + alpha = mark._resolve(data, f"{prefix}alpha", scales) + else: + alpha = mark._resolve(data, "alpha", scales) + + def visible(x, axis=None): + """Detect "invisible" colors to set alpha appropriately.""" + # TODO First clause only needed to handle non-rgba arrays, + # which we are trying to handle upstream + return np.array(x).dtype.kind != "f" or np.isfinite(x).all(axis) + + # Second check here catches vectors of strings with identity scale + # It could probably be handled better upstream. This is a tricky problem + if np.ndim(color) < 2 and all(isinstance(x, float) for x in color): + if len(color) == 4: + return mpl.colors.to_rgba(color) + alpha = alpha if visible(color) else np.nan + return mpl.colors.to_rgba(color, alpha) + else: + if np.ndim(color) == 2 and color.shape[1] == 4: + return mpl.colors.to_rgba_array(color) + alpha = np.where(visible(color, axis=1), alpha, np.nan) + return mpl.colors.to_rgba_array(color, alpha) + + # TODO should we be implementing fill here too? + # (i.e. set fillalpha to 0 when fill=False) + + +def document_properties(mark): + + properties = [f.name for f in fields(mark) if isinstance(f.default, Mappable)] + text = [ + "", + " This mark defines the following properties:", + textwrap.fill( + ", ".join([f"|{p}|" for p in properties]), + width=78, initial_indent=" " * 8, subsequent_indent=" " * 8, + ), + ] + + docstring_lines = mark.__doc__.split("\n") + new_docstring = "\n".join([ + *docstring_lines[:2], + *text, + *docstring_lines[2:], + ]) + mark.__doc__ = new_docstring + return mark diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/dot.py b/testbed/mwaskom__seaborn/seaborn/_marks/dot.py new file mode 100644 index 0000000000000000000000000000000000000000..beef412dec2030d791b986aeb0261f5c0ba69766 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/dot.py @@ -0,0 +1,200 @@ +from __future__ import annotations +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableBool, + MappableFloat, + MappableString, + MappableColor, + MappableStyle, + resolve_properties, + resolve_color, + document_properties, +) + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from typing import Any + from matplotlib.artist import Artist + from seaborn._core.scales import Scale + + +class DotBase(Mark): + + def _resolve_paths(self, data): + + paths = [] + path_cache = {} + marker = data["marker"] + + def get_transformed_path(m): + return m.get_path().transformed(m.get_transform()) + + if isinstance(marker, mpl.markers.MarkerStyle): + return get_transformed_path(marker) + + for m in marker: + if m not in path_cache: + path_cache[m] = get_transformed_path(m) + paths.append(path_cache[m]) + return paths + + def _resolve_properties(self, data, scales): + + resolved = resolve_properties(self, data, scales) + resolved["path"] = self._resolve_paths(resolved) + resolved["size"] = resolved["pointsize"] ** 2 + + if isinstance(data, dict): # Properties for single dot + filled_marker = resolved["marker"].is_filled() + else: + filled_marker = [m.is_filled() for m in resolved["marker"]] + + resolved["fill"] = resolved["fill"] * filled_marker + + return resolved + + def _plot(self, split_gen, scales, orient): + + # TODO Not backcompat with allowed (but nonfunctional) univariate plots + # (That should be solved upstream by defaulting to "" for unset x/y?) + # (Be mindful of xmin/xmax, etc!) + + for _, data, ax in split_gen(): + + offsets = np.column_stack([data["x"], data["y"]]) + data = self._resolve_properties(data, scales) + + points = mpl.collections.PathCollection( + offsets=offsets, + paths=data["path"], + sizes=data["size"], + facecolors=data["facecolor"], + edgecolors=data["edgecolor"], + linewidths=data["linewidth"], + linestyles=data["edgestyle"], + transOffset=ax.transData, + transform=mpl.transforms.IdentityTransform(), + **self.artist_kws, + ) + ax.add_collection(points) + + def _legend_artist( + self, variables: list[str], value: Any, scales: dict[str, Scale], + ) -> Artist: + + key = {v: value for v in variables} + res = self._resolve_properties(key, scales) + + return mpl.collections.PathCollection( + paths=[res["path"]], + sizes=[res["size"]], + facecolors=[res["facecolor"]], + edgecolors=[res["edgecolor"]], + linewidths=[res["linewidth"]], + linestyles=[res["edgestyle"]], + transform=mpl.transforms.IdentityTransform(), + **self.artist_kws, + ) + + +@document_properties +@dataclass +class Dot(DotBase): + """ + A mark suitable for dot plots or less-dense scatterplots. + + See also + -------- + Dots : A dot mark defined by strokes to better handle overplotting. + + Examples + -------- + .. include:: ../docstrings/objects.Dot.rst + + """ + marker: MappableString = Mappable("o", grouping=False) + pointsize: MappableFloat = Mappable(6, grouping=False) # TODO rcParam? + stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam? + color: MappableColor = Mappable("C0", grouping=False) + alpha: MappableFloat = Mappable(1, grouping=False) + fill: MappableBool = Mappable(True, grouping=False) + edgecolor: MappableColor = Mappable(depend="color", grouping=False) + edgealpha: MappableFloat = Mappable(depend="alpha", grouping=False) + edgewidth: MappableFloat = Mappable(.5, grouping=False) # TODO rcParam? + edgestyle: MappableStyle = Mappable("-", grouping=False) + + def _resolve_properties(self, data, scales): + + resolved = super()._resolve_properties(data, scales) + filled = resolved["fill"] + + main_stroke = resolved["stroke"] + edge_stroke = resolved["edgewidth"] + resolved["linewidth"] = np.where(filled, edge_stroke, main_stroke) + + main_color = resolve_color(self, data, "", scales) + edge_color = resolve_color(self, data, "edge", scales) + + if not np.isscalar(filled): + # Expand dims to use in np.where with rgba arrays + filled = filled[:, None] + resolved["edgecolor"] = np.where(filled, edge_color, main_color) + + filled = np.squeeze(filled) + if isinstance(main_color, tuple): + # TODO handle this in resolve_color + main_color = tuple([*main_color[:3], main_color[3] * filled]) + else: + main_color = np.c_[main_color[:, :3], main_color[:, 3] * filled] + resolved["facecolor"] = main_color + + return resolved + + +@document_properties +@dataclass +class Dots(DotBase): + """ + A dot mark defined by strokes to better handle overplotting. + + See also + -------- + Dot : A mark suitable for dot plots or less-dense scatterplots. + + Examples + -------- + .. include:: ../docstrings/objects.Dots.rst + + """ + # TODO retype marker as MappableMarker + marker: MappableString = Mappable(rc="scatter.marker", grouping=False) + pointsize: MappableFloat = Mappable(4, grouping=False) # TODO rcParam? + stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam? + color: MappableColor = Mappable("C0", grouping=False) + alpha: MappableFloat = Mappable(1, grouping=False) # TODO auto alpha? + fill: MappableBool = Mappable(True, grouping=False) + fillcolor: MappableColor = Mappable(depend="color", grouping=False) + fillalpha: MappableFloat = Mappable(.2, grouping=False) + + def _resolve_properties(self, data, scales): + + resolved = super()._resolve_properties(data, scales) + resolved["linewidth"] = resolved.pop("stroke") + resolved["facecolor"] = resolve_color(self, data, "fill", scales) + resolved["edgecolor"] = resolve_color(self, data, "", scales) + resolved.setdefault("edgestyle", (0, None)) + + fc = resolved["facecolor"] + if isinstance(fc, tuple): + resolved["facecolor"] = fc[0], fc[1], fc[2], fc[3] * resolved["fill"] + else: + fc[:, 3] = fc[:, 3] * resolved["fill"] # TODO Is inplace mod a problem? + resolved["facecolor"] = fc + + return resolved diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/line.py b/testbed/mwaskom__seaborn/seaborn/_marks/line.py new file mode 100644 index 0000000000000000000000000000000000000000..a517f1b8b79483c5bc0374322d73d6affe2bdbda --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/line.py @@ -0,0 +1,285 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import ClassVar + +import numpy as np +import matplotlib as mpl + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableFloat, + MappableString, + MappableColor, + resolve_properties, + resolve_color, + document_properties, +) + + +@document_properties +@dataclass +class Path(Mark): + """ + A mark connecting data points in the order they appear. + + See also + -------- + Line : A mark connecting data points with sorting along the orientation axis. + Paths : A faster but less-flexible mark for drawing many paths. + + Examples + -------- + .. include:: ../docstrings/objects.Path.rst + + """ + color: MappableColor = Mappable("C0") + alpha: MappableFloat = Mappable(1) + linewidth: MappableFloat = Mappable(rc="lines.linewidth") + linestyle: MappableString = Mappable(rc="lines.linestyle") + marker: MappableString = Mappable(rc="lines.marker") + pointsize: MappableFloat = Mappable(rc="lines.markersize") + fillcolor: MappableColor = Mappable(depend="color") + edgecolor: MappableColor = Mappable(depend="color") + edgewidth: MappableFloat = Mappable(rc="lines.markeredgewidth") + + _sort: ClassVar[bool] = False + + def _plot(self, split_gen, scales, orient): + + for keys, data, ax in split_gen(keep_na=not self._sort): + + vals = resolve_properties(self, keys, scales) + vals["color"] = resolve_color(self, keys, scales=scales) + vals["fillcolor"] = resolve_color(self, keys, prefix="fill", scales=scales) + vals["edgecolor"] = resolve_color(self, keys, prefix="edge", scales=scales) + + if self._sort: + data = data.sort_values(orient, kind="mergesort") + + artist_kws = self.artist_kws.copy() + self._handle_capstyle(artist_kws, vals) + + line = mpl.lines.Line2D( + data["x"].to_numpy(), + data["y"].to_numpy(), + color=vals["color"], + linewidth=vals["linewidth"], + linestyle=vals["linestyle"], + marker=vals["marker"], + markersize=vals["pointsize"], + markerfacecolor=vals["fillcolor"], + markeredgecolor=vals["edgecolor"], + markeredgewidth=vals["edgewidth"], + **artist_kws, + ) + ax.add_line(line) + + def _legend_artist(self, variables, value, scales): + + keys = {v: value for v in variables} + vals = resolve_properties(self, keys, scales) + vals["color"] = resolve_color(self, keys, scales=scales) + vals["fillcolor"] = resolve_color(self, keys, prefix="fill", scales=scales) + vals["edgecolor"] = resolve_color(self, keys, prefix="edge", scales=scales) + + artist_kws = self.artist_kws.copy() + self._handle_capstyle(artist_kws, vals) + + return mpl.lines.Line2D( + [], [], + color=vals["color"], + linewidth=vals["linewidth"], + linestyle=vals["linestyle"], + marker=vals["marker"], + markersize=vals["pointsize"], + markerfacecolor=vals["fillcolor"], + markeredgecolor=vals["edgecolor"], + markeredgewidth=vals["edgewidth"], + **artist_kws, + ) + + def _handle_capstyle(self, kws, vals): + + # Work around for this matplotlib issue: + # https://github.com/matplotlib/matplotlib/issues/23437 + if vals["linestyle"][1] is None: + capstyle = kws.get("solid_capstyle", mpl.rcParams["lines.solid_capstyle"]) + kws["dash_capstyle"] = capstyle + + +@document_properties +@dataclass +class Line(Path): + """ + A mark connecting data points with sorting along the orientation axis. + + See also + -------- + Path : A mark connecting data points in the order they appear. + Lines : A faster but less-flexible mark for drawing many lines. + + Examples + -------- + .. include:: ../docstrings/objects.Line.rst + + """ + _sort: ClassVar[bool] = True + + +@document_properties +@dataclass +class Paths(Mark): + """ + A faster but less-flexible mark for drawing many paths. + + See also + -------- + Path : A mark connecting data points in the order they appear. + + Examples + -------- + .. include:: ../docstrings/objects.Paths.rst + + """ + color: MappableColor = Mappable("C0") + alpha: MappableFloat = Mappable(1) + linewidth: MappableFloat = Mappable(rc="lines.linewidth") + linestyle: MappableString = Mappable(rc="lines.linestyle") + + _sort: ClassVar[bool] = False + + def __post_init__(self): + + # LineCollection artists have a capstyle property but don't source its value + # from the rc, so we do that manually here. Unfortunately, because we add + # only one LineCollection, we have the use the same capstyle for all lines + # even when they are dashed. It's a slight inconsistency, but looks fine IMO. + self.artist_kws.setdefault("capstyle", mpl.rcParams["lines.solid_capstyle"]) + + def _plot(self, split_gen, scales, orient): + + line_data = {} + for keys, data, ax in split_gen(keep_na=not self._sort): + + if ax not in line_data: + line_data[ax] = { + "segments": [], + "colors": [], + "linewidths": [], + "linestyles": [], + } + + segments = self._setup_segments(data, orient) + line_data[ax]["segments"].extend(segments) + n = len(segments) + + vals = resolve_properties(self, keys, scales) + vals["color"] = resolve_color(self, keys, scales=scales) + + line_data[ax]["colors"].extend([vals["color"]] * n) + line_data[ax]["linewidths"].extend([vals["linewidth"]] * n) + line_data[ax]["linestyles"].extend([vals["linestyle"]] * n) + + for ax, ax_data in line_data.items(): + lines = mpl.collections.LineCollection(**ax_data, **self.artist_kws) + # Handle datalim update manually + # https://github.com/matplotlib/matplotlib/issues/23129 + ax.add_collection(lines, autolim=False) + if ax_data["segments"]: + xy = np.concatenate(ax_data["segments"]) + ax.update_datalim(xy) + + def _legend_artist(self, variables, value, scales): + + key = resolve_properties(self, {v: value for v in variables}, scales) + + artist_kws = self.artist_kws.copy() + capstyle = artist_kws.pop("capstyle") + artist_kws["solid_capstyle"] = capstyle + artist_kws["dash_capstyle"] = capstyle + + return mpl.lines.Line2D( + [], [], + color=key["color"], + linewidth=key["linewidth"], + linestyle=key["linestyle"], + **artist_kws, + ) + + def _setup_segments(self, data, orient): + + if self._sort: + data = data.sort_values(orient, kind="mergesort") + + # Column stack to avoid block consolidation + xy = np.column_stack([data["x"], data["y"]]) + + return [xy] + + +@document_properties +@dataclass +class Lines(Paths): + """ + A faster but less-flexible mark for drawing many lines. + + See also + -------- + Line : A mark connecting data points with sorting along the orientation axis. + + Examples + -------- + .. include:: ../docstrings/objects.Lines.rst + + """ + _sort: ClassVar[bool] = True + + +@document_properties +@dataclass +class Range(Paths): + """ + An oriented line mark drawn between min/max values. + + Examples + -------- + .. include:: ../docstrings/objects.Range.rst + + """ + def _setup_segments(self, data, orient): + + # TODO better checks on what variables we have + # TODO what if only one exist? + val = {"x": "y", "y": "x"}[orient] + if not set(data.columns) & {f"{val}min", f"{val}max"}: + agg = {f"{val}min": (val, "min"), f"{val}max": (val, "max")} + data = data.groupby(orient).agg(**agg).reset_index() + + cols = [orient, f"{val}min", f"{val}max"] + data = data[cols].melt(orient, value_name=val)[["x", "y"]] + segments = [d.to_numpy() for _, d in data.groupby(orient)] + return segments + + +@document_properties +@dataclass +class Dash(Paths): + """ + A line mark drawn as an oriented segment for each datapoint. + + Examples + -------- + .. include:: ../docstrings/objects.Dash.rst + + """ + width: MappableFloat = Mappable(.8, grouping=False) + + def _setup_segments(self, data, orient): + + ori = ["x", "y"].index(orient) + xys = data[["x", "y"]].to_numpy().astype(float) + segments = np.stack([xys, xys], axis=1) + segments[:, 0, ori] -= data["width"] / 2 + segments[:, 1, ori] += data["width"] / 2 + return segments diff --git a/testbed/mwaskom__seaborn/seaborn/_marks/text.py b/testbed/mwaskom__seaborn/seaborn/_marks/text.py new file mode 100644 index 0000000000000000000000000000000000000000..58d757c1acefc3c2ef6ecb8bec01c152ea08729d --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_marks/text.py @@ -0,0 +1,76 @@ +from __future__ import annotations +from collections import defaultdict +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl +from matplotlib.transforms import ScaledTranslation + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableFloat, + MappableString, + MappableColor, + resolve_properties, + resolve_color, + document_properties, +) + + +@document_properties +@dataclass +class Text(Mark): + """ + A textual mark to annotate or represent data values. + + Examples + -------- + .. include:: ../docstrings/objects.Text.rst + + """ + text: MappableString = Mappable("") + color: MappableColor = Mappable("k") + alpha: MappableFloat = Mappable(1) + fontsize: MappableFloat = Mappable(rc="font.size") + halign: MappableString = Mappable("center") + valign: MappableString = Mappable("center_baseline") + offset: MappableFloat = Mappable(4) + + def _plot(self, split_gen, scales, orient): + + ax_data = defaultdict(list) + + for keys, data, ax in split_gen(): + + vals = resolve_properties(self, keys, scales) + color = resolve_color(self, keys, "", scales) + + halign = vals["halign"] + valign = vals["valign"] + fontsize = vals["fontsize"] + offset = vals["offset"] / 72 + + offset_trans = ScaledTranslation( + {"right": -offset, "left": +offset}.get(halign, 0), + {"top": -offset, "bottom": +offset, "baseline": +offset}.get(valign, 0), + ax.figure.dpi_scale_trans, + ) + + for row in data.to_dict("records"): + artist = mpl.text.Text( + x=row["x"], + y=row["y"], + text=str(row.get("text", vals["text"])), + color=color, + fontsize=fontsize, + horizontalalignment=halign, + verticalalignment=valign, + transform=ax.transData + offset_trans, + **self.artist_kws, + ) + ax.add_artist(artist) + ax_data[ax].append([row["x"], row["y"]]) + + for ax, ax_vals in ax_data.items(): + ax.update_datalim(np.array(ax_vals)) diff --git a/testbed/mwaskom__seaborn/seaborn/_oldcore.py b/testbed/mwaskom__seaborn/seaborn/_oldcore.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a38b8a7e84069ec24eb30393eedf01e985bb03 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_oldcore.py @@ -0,0 +1,1767 @@ +import warnings +import itertools +from copy import copy +from functools import partial +from collections import UserString +from collections.abc import Iterable, Sequence, Mapping +from numbers import Number +from datetime import datetime + +import numpy as np +import pandas as pd +import matplotlib as mpl + +from ._decorators import ( + share_init_params_with_map, +) +from .palettes import ( + QUAL_PALETTES, + color_palette, +) +from .utils import ( + _check_argument, + get_color_cycle, + remove_na, +) + + +class SemanticMapping: + """Base class for mapping data values to plot attributes.""" + + # -- Default attributes that all SemanticMapping subclasses must set + + # Whether the mapping is numeric, categorical, or datetime + map_type = None + + # Ordered list of unique values in the input data + levels = None + + # A mapping from the data values to corresponding plot attributes + lookup_table = None + + def __init__(self, plotter): + + # TODO Putting this here so we can continue to use a lot of the + # logic that's built into the library, but the idea of this class + # is to move towards semantic mappings that are agnostic about the + # kind of plot they're going to be used to draw. + # Fully achieving that is going to take some thinking. + self.plotter = plotter + + def map(cls, plotter, *args, **kwargs): + # This method is assigned the __init__ docstring + method_name = f"_{cls.__name__[:-7].lower()}_map" + setattr(plotter, method_name, cls(plotter, *args, **kwargs)) + return plotter + + def _check_list_length(self, levels, values, variable): + """Input check when values are provided as a list.""" + # Copied from _core/properties; eventually will be replaced for that. + message = "" + if len(levels) > len(values): + message = " ".join([ + f"\nThe {variable} list has fewer values ({len(values)})", + f"than needed ({len(levels)}) and will cycle, which may", + "produce an uninterpretable plot." + ]) + values = [x for _, x in zip(levels, itertools.cycle(values))] + + elif len(values) > len(levels): + message = " ".join([ + f"The {variable} list has more values ({len(values)})", + f"than needed ({len(levels)}), which may not be intended.", + ]) + values = values[:len(levels)] + + if message: + warnings.warn(message, UserWarning, stacklevel=6) + + return values + + def _lookup_single(self, key): + """Apply the mapping to a single data value.""" + return self.lookup_table[key] + + def __call__(self, key, *args, **kwargs): + """Get the attribute(s) values for the data key.""" + if isinstance(key, (list, np.ndarray, pd.Series)): + return [self._lookup_single(k, *args, **kwargs) for k in key] + else: + return self._lookup_single(key, *args, **kwargs) + + +@share_init_params_with_map +class HueMapping(SemanticMapping): + """Mapping that sets artist colors according to data values.""" + # A specification of the colors that should appear in the plot + palette = None + + # An object that normalizes data values to [0, 1] range for color mapping + norm = None + + # A continuous colormap object for interpolating in a numeric context + cmap = None + + def __init__( + self, plotter, palette=None, order=None, norm=None, + ): + """Map the levels of the `hue` variable to distinct colors. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("hue", pd.Series(dtype=float)) + + if data.isna().all(): + if palette is not None: + msg = "Ignoring `palette` because no `hue` variable has been assigned." + warnings.warn(msg, stacklevel=4) + else: + + map_type = self.infer_map_type( + palette, norm, plotter.input_format, plotter.var_types["hue"] + ) + + # Our goal is to end up with a dictionary mapping every unique + # value in `data` to a color. We will also keep track of the + # metadata about this mapping we will need for, e.g., a legend + + # --- Option 1: numeric mapping with a matplotlib colormap + + if map_type == "numeric": + + data = pd.to_numeric(data) + levels, lookup_table, norm, cmap = self.numeric_mapping( + data, palette, norm, + ) + + # --- Option 2: categorical mapping using seaborn palette + + elif map_type == "categorical": + + cmap = norm = None + levels, lookup_table = self.categorical_mapping( + data, palette, order, + ) + + # --- Option 3: datetime mapping + + else: + # TODO this needs actual implementation + cmap = norm = None + levels, lookup_table = self.categorical_mapping( + # Casting data to list to handle differences in the way + # pandas and numpy represent datetime64 data + list(data), palette, order, + ) + + self.map_type = map_type + self.lookup_table = lookup_table + self.palette = palette + self.levels = levels + self.norm = norm + self.cmap = cmap + + def _lookup_single(self, key): + """Get the color for a single value, using colormap to interpolate.""" + try: + # Use a value that's in the original data vector + value = self.lookup_table[key] + except KeyError: + + if self.norm is None: + # Currently we only get here in scatterplot with hue_order, + # because scatterplot does not consider hue a grouping variable + # So unused hue levels are in the data, but not the lookup table + return (0, 0, 0, 0) + + # Use the colormap to interpolate between existing datapoints + # (e.g. in the context of making a continuous legend) + try: + normed = self.norm(key) + except TypeError as err: + if np.isnan(key): + value = (0, 0, 0, 0) + else: + raise err + else: + if np.ma.is_masked(normed): + normed = np.nan + value = self.cmap(normed) + return value + + def infer_map_type(self, palette, norm, input_format, var_type): + """Determine how to implement the mapping.""" + if palette in QUAL_PALETTES: + map_type = "categorical" + elif norm is not None: + map_type = "numeric" + elif isinstance(palette, (dict, list)): + map_type = "categorical" + elif input_format == "wide": + map_type = "categorical" + else: + map_type = var_type + + return map_type + + def categorical_mapping(self, data, palette, order): + """Determine colors when the hue mapping is categorical.""" + # -- Identify the order and name of the levels + + levels = categorical_order(data, order) + n_colors = len(levels) + + # -- Identify the set of colors to use + + if isinstance(palette, dict): + + missing = set(levels) - set(palette) + if any(missing): + err = "The palette dictionary is missing keys: {}" + raise ValueError(err.format(missing)) + + lookup_table = palette + + else: + + if palette is None: + if n_colors <= len(get_color_cycle()): + colors = color_palette(None, n_colors) + else: + colors = color_palette("husl", n_colors) + elif isinstance(palette, list): + colors = self._check_list_length(levels, palette, "palette") + else: + colors = color_palette(palette, n_colors) + + lookup_table = dict(zip(levels, colors)) + + return levels, lookup_table + + def numeric_mapping(self, data, palette, norm): + """Determine colors when the hue variable is quantitative.""" + if isinstance(palette, dict): + + # The presence of a norm object overrides a dictionary of hues + # in specifying a numeric mapping, so we need to process it here. + levels = list(sorted(palette)) + colors = [palette[k] for k in sorted(palette)] + cmap = mpl.colors.ListedColormap(colors) + lookup_table = palette.copy() + + else: + + # The levels are the sorted unique values in the data + levels = list(np.sort(remove_na(data.unique()))) + + # --- Sort out the colormap to use from the palette argument + + # Default numeric palette is our default cubehelix palette + # TODO do we want to do something complicated to ensure contrast? + palette = "ch:" if palette is None else palette + + if isinstance(palette, mpl.colors.Colormap): + cmap = palette + else: + cmap = color_palette(palette, as_cmap=True) + + # Now sort out the data normalization + if norm is None: + norm = mpl.colors.Normalize() + elif isinstance(norm, tuple): + norm = mpl.colors.Normalize(*norm) + elif not isinstance(norm, mpl.colors.Normalize): + err = "``hue_norm`` must be None, tuple, or Normalize object." + raise ValueError(err) + + if not norm.scaled(): + norm(np.asarray(data.dropna())) + + lookup_table = dict(zip(levels, cmap(norm(levels)))) + + return levels, lookup_table, norm, cmap + + +@share_init_params_with_map +class SizeMapping(SemanticMapping): + """Mapping that sets artist sizes according to data values.""" + # An object that normalizes data values to [0, 1] range + norm = None + + def __init__( + self, plotter, sizes=None, order=None, norm=None, + ): + """Map the levels of the `size` variable to distinct values. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("size", pd.Series(dtype=float)) + + if data.notna().any(): + + map_type = self.infer_map_type( + norm, sizes, plotter.var_types["size"] + ) + + # --- Option 1: numeric mapping + + if map_type == "numeric": + + levels, lookup_table, norm, size_range = self.numeric_mapping( + data, sizes, norm, + ) + + # --- Option 2: categorical mapping + + elif map_type == "categorical": + + levels, lookup_table = self.categorical_mapping( + data, sizes, order, + ) + size_range = None + + # --- Option 3: datetime mapping + + # TODO this needs an actual implementation + else: + + levels, lookup_table = self.categorical_mapping( + # Casting data to list to handle differences in the way + # pandas and numpy represent datetime64 data + list(data), sizes, order, + ) + size_range = None + + self.map_type = map_type + self.levels = levels + self.norm = norm + self.sizes = sizes + self.size_range = size_range + self.lookup_table = lookup_table + + def infer_map_type(self, norm, sizes, var_type): + + if norm is not None: + map_type = "numeric" + elif isinstance(sizes, (dict, list)): + map_type = "categorical" + else: + map_type = var_type + + return map_type + + def _lookup_single(self, key): + + try: + value = self.lookup_table[key] + except KeyError: + normed = self.norm(key) + if np.ma.is_masked(normed): + normed = np.nan + value = self.size_range[0] + normed * np.ptp(self.size_range) + return value + + def categorical_mapping(self, data, sizes, order): + + levels = categorical_order(data, order) + + if isinstance(sizes, dict): + + # Dict inputs map existing data values to the size attribute + missing = set(levels) - set(sizes) + if any(missing): + err = f"Missing sizes for the following levels: {missing}" + raise ValueError(err) + lookup_table = sizes.copy() + + elif isinstance(sizes, list): + + # List inputs give size values in the same order as the levels + sizes = self._check_list_length(levels, sizes, "sizes") + lookup_table = dict(zip(levels, sizes)) + + else: + + if isinstance(sizes, tuple): + + # Tuple input sets the min, max size values + if len(sizes) != 2: + err = "A `sizes` tuple must have only 2 values" + raise ValueError(err) + + elif sizes is not None: + + err = f"Value for `sizes` not understood: {sizes}" + raise ValueError(err) + + else: + + # Otherwise, we need to get the min, max size values from + # the plotter object we are attached to. + + # TODO this is going to cause us trouble later, because we + # want to restructure things so that the plotter is generic + # across the visual representation of the data. But at this + # point, we don't know the visual representation. Likely we + # want to change the logic of this Mapping so that it gives + # points on a normalized range that then gets un-normalized + # when we know what we're drawing. But given the way the + # package works now, this way is cleanest. + sizes = self.plotter._default_size_range + + # For categorical sizes, use regularly-spaced linear steps + # between the minimum and maximum sizes. Then reverse the + # ramp so that the largest value is used for the first entry + # in size_order, etc. This is because "ordered" categories + # are often though to go in decreasing priority. + sizes = np.linspace(*sizes, len(levels))[::-1] + lookup_table = dict(zip(levels, sizes)) + + return levels, lookup_table + + def numeric_mapping(self, data, sizes, norm): + + if isinstance(sizes, dict): + # The presence of a norm object overrides a dictionary of sizes + # in specifying a numeric mapping, so we need to process it + # dictionary here + levels = list(np.sort(list(sizes))) + size_values = sizes.values() + size_range = min(size_values), max(size_values) + + else: + + # The levels here will be the unique values in the data + levels = list(np.sort(remove_na(data.unique()))) + + if isinstance(sizes, tuple): + + # For numeric inputs, the size can be parametrized by + # the minimum and maximum artist values to map to. The + # norm object that gets set up next specifies how to + # do the mapping. + + if len(sizes) != 2: + err = "A `sizes` tuple must have only 2 values" + raise ValueError(err) + + size_range = sizes + + elif sizes is not None: + + err = f"Value for `sizes` not understood: {sizes}" + raise ValueError(err) + + else: + + # When not provided, we get the size range from the plotter + # object we are attached to. See the note in the categorical + # method about how this is suboptimal for future development. + size_range = self.plotter._default_size_range + + # Now that we know the minimum and maximum sizes that will get drawn, + # we need to map the data values that we have into that range. We will + # use a matplotlib Normalize class, which is typically used for numeric + # color mapping but works fine here too. It takes data values and maps + # them into a [0, 1] interval, potentially nonlinear-ly. + + if norm is None: + # Default is a linear function between the min and max data values + norm = mpl.colors.Normalize() + elif isinstance(norm, tuple): + # It is also possible to give different limits in data space + norm = mpl.colors.Normalize(*norm) + elif not isinstance(norm, mpl.colors.Normalize): + err = f"Value for size `norm` parameter not understood: {norm}" + raise ValueError(err) + else: + # If provided with Normalize object, copy it so we can modify + norm = copy(norm) + + # Set the mapping so all output values are in [0, 1] + norm.clip = True + + # If the input range is not set, use the full range of the data + if not norm.scaled(): + norm(levels) + + # Map from data values to [0, 1] range + sizes_scaled = norm(levels) + + # Now map from the scaled range into the artist units + if isinstance(sizes, dict): + lookup_table = sizes + else: + lo, hi = size_range + sizes = lo + sizes_scaled * (hi - lo) + lookup_table = dict(zip(levels, sizes)) + + return levels, lookup_table, norm, size_range + + +@share_init_params_with_map +class StyleMapping(SemanticMapping): + """Mapping that sets artist style according to data values.""" + + # Style mapping is always treated as categorical + map_type = "categorical" + + def __init__( + self, plotter, markers=None, dashes=None, order=None, + ): + """Map the levels of the `style` variable to distinct values. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("style", pd.Series(dtype=float)) + + if data.notna().any(): + + # Cast to list to handle numpy/pandas datetime quirks + if variable_type(data) == "datetime": + data = list(data) + + # Find ordered unique values + levels = categorical_order(data, order) + + markers = self._map_attributes( + markers, levels, unique_markers(len(levels)), "markers", + ) + dashes = self._map_attributes( + dashes, levels, unique_dashes(len(levels)), "dashes", + ) + + # Build the paths matplotlib will use to draw the markers + paths = {} + filled_markers = [] + for k, m in markers.items(): + if not isinstance(m, mpl.markers.MarkerStyle): + m = mpl.markers.MarkerStyle(m) + paths[k] = m.get_path().transformed(m.get_transform()) + filled_markers.append(m.is_filled()) + + # Mixture of filled and unfilled markers will show line art markers + # in the edge color, which defaults to white. This can be handled, + # but there would be additional complexity with specifying the + # weight of the line art markers without overwhelming the filled + # ones with the edges. So for now, we will disallow mixtures. + if any(filled_markers) and not all(filled_markers): + err = "Filled and line art markers cannot be mixed" + raise ValueError(err) + + lookup_table = {} + for key in levels: + lookup_table[key] = {} + if markers: + lookup_table[key]["marker"] = markers[key] + lookup_table[key]["path"] = paths[key] + if dashes: + lookup_table[key]["dashes"] = dashes[key] + + self.levels = levels + self.lookup_table = lookup_table + + def _lookup_single(self, key, attr=None): + """Get attribute(s) for a given data point.""" + if attr is None: + value = self.lookup_table[key] + else: + value = self.lookup_table[key][attr] + return value + + def _map_attributes(self, arg, levels, defaults, attr): + """Handle the specification for a given style attribute.""" + if arg is True: + lookup_table = dict(zip(levels, defaults)) + elif isinstance(arg, dict): + missing = set(levels) - set(arg) + if missing: + err = f"These `{attr}` levels are missing values: {missing}" + raise ValueError(err) + lookup_table = arg + elif isinstance(arg, Sequence): + arg = self._check_list_length(levels, arg, attr) + lookup_table = dict(zip(levels, arg)) + elif arg: + err = f"This `{attr}` argument was not understood: {arg}" + raise ValueError(err) + else: + lookup_table = {} + + return lookup_table + + +# =========================================================================== # + + +class VectorPlotter: + """Base class for objects underlying *plot functions.""" + + _semantic_mappings = { + "hue": HueMapping, + "size": SizeMapping, + "style": StyleMapping, + } + + # TODO units is another example of a non-mapping "semantic" + # we need a general name for this and separate handling + semantics = "x", "y", "hue", "size", "style", "units" + wide_structure = { + "x": "@index", "y": "@values", "hue": "@columns", "style": "@columns", + } + flat_structure = {"x": "@index", "y": "@values"} + + _default_size_range = 1, 2 # Unused but needed in tests, ugh + + def __init__(self, data=None, variables={}): + + self._var_levels = {} + # var_ordered is relevant only for categorical axis variables, and may + # be better handled by an internal axis information object that tracks + # such information and is set up by the scale_* methods. The analogous + # information for numeric axes would be information about log scales. + self._var_ordered = {"x": False, "y": False} # alt., used DefaultDict + self.assign_variables(data, variables) + + for var, cls in self._semantic_mappings.items(): + + # Create the mapping function + map_func = partial(cls.map, plotter=self) + setattr(self, f"map_{var}", map_func) + + # Call the mapping function to initialize with default values + getattr(self, f"map_{var}")() + + @classmethod + def get_semantics(cls, kwargs, semantics=None): + """Subset a dictionary arguments with known semantic variables.""" + # TODO this should be get_variables since we have included x and y + if semantics is None: + semantics = cls.semantics + variables = {} + for key, val in kwargs.items(): + if key in semantics and val is not None: + variables[key] = val + return variables + + @property + def has_xy_data(self): + """Return True at least one of x or y is defined.""" + return bool({"x", "y"} & set(self.variables)) + + @property + def var_levels(self): + """Property interface to ordered list of variables levels. + + Each time it's accessed, it updates the var_levels dictionary with the + list of levels in the current semantic mappers. But it also allows the + dictionary to persist, so it can be used to set levels by a key. This is + used to track the list of col/row levels using an attached FacetGrid + object, but it's kind of messy and ideally fixed by improving the + faceting logic so it interfaces better with the modern approach to + tracking plot variables. + + """ + for var in self.variables: + try: + map_obj = getattr(self, f"_{var}_map") + self._var_levels[var] = map_obj.levels + except AttributeError: + pass + return self._var_levels + + def assign_variables(self, data=None, variables={}): + """Define plot variables, optionally using lookup from `data`.""" + x = variables.get("x", None) + y = variables.get("y", None) + + if x is None and y is None: + self.input_format = "wide" + plot_data, variables = self._assign_variables_wideform( + data, **variables, + ) + else: + self.input_format = "long" + plot_data, variables = self._assign_variables_longform( + data, **variables, + ) + + self.plot_data = plot_data + self.variables = variables + self.var_types = { + v: variable_type( + plot_data[v], + boolean_type="numeric" if v in "xy" else "categorical" + ) + for v in variables + } + + return self + + def _assign_variables_wideform(self, data=None, **kwargs): + """Define plot variables given wide-form data. + + Parameters + ---------- + data : flat vector or collection of vectors + Data can be a vector or mapping that is coerceable to a Series + or a sequence- or mapping-based collection of such vectors, or a + rectangular numpy array, or a Pandas DataFrame. + kwargs : variable -> data mappings + Behavior with keyword arguments is currently undefined. + + Returns + ------- + plot_data : :class:`pandas.DataFrame` + Long-form data object mapping seaborn variables (x, y, hue, ...) + to data vectors. + variables : dict + Keys are defined seaborn variables; values are names inferred from + the inputs (or None when no name can be determined). + + """ + # Raise if semantic or other variables are assigned in wide-form mode + assigned = [k for k, v in kwargs.items() if v is not None] + if any(assigned): + s = "s" if len(assigned) > 1 else "" + err = f"The following variable{s} cannot be assigned with wide-form data: " + err += ", ".join(f"`{v}`" for v in assigned) + raise ValueError(err) + + # Determine if the data object actually has any data in it + empty = data is None or not len(data) + + # Then, determine if we have "flat" data (a single vector) + if isinstance(data, dict): + values = data.values() + else: + values = np.atleast_1d(np.asarray(data, dtype=object)) + flat = not any( + isinstance(v, Iterable) and not isinstance(v, (str, bytes)) + for v in values + ) + + if empty: + + # Make an object with the structure of plot_data, but empty + plot_data = pd.DataFrame() + variables = {} + + elif flat: + + # Handle flat data by converting to pandas Series and using the + # index and/or values to define x and/or y + # (Could be accomplished with a more general to_series() interface) + flat_data = pd.Series(data).copy() + names = { + "@values": flat_data.name, + "@index": flat_data.index.name + } + + plot_data = {} + variables = {} + + for var in ["x", "y"]: + if var in self.flat_structure: + attr = self.flat_structure[var] + plot_data[var] = getattr(flat_data, attr[1:]) + variables[var] = names[self.flat_structure[var]] + + plot_data = pd.DataFrame(plot_data) + + else: + + # Otherwise assume we have some collection of vectors. + + # Handle Python sequences such that entries end up in the columns, + # not in the rows, of the intermediate wide DataFrame. + # One way to accomplish this is to convert to a dict of Series. + if isinstance(data, Sequence): + data_dict = {} + for i, var in enumerate(data): + key = getattr(var, "name", i) + # TODO is there a safer/more generic way to ensure Series? + # sort of like np.asarray, but for pandas? + data_dict[key] = pd.Series(var) + + data = data_dict + + # Pandas requires that dict values either be Series objects + # or all have the same length, but we want to allow "ragged" inputs + if isinstance(data, Mapping): + data = {key: pd.Series(val) for key, val in data.items()} + + # Otherwise, delegate to the pandas DataFrame constructor + # This is where we'd prefer to use a general interface that says + # "give me this data as a pandas DataFrame", so we can accept + # DataFrame objects from other libraries + wide_data = pd.DataFrame(data, copy=True) + + # At this point we should reduce the dataframe to numeric cols + numeric_cols = [ + k for k, v in wide_data.items() if variable_type(v) == "numeric" + ] + wide_data = wide_data[numeric_cols] + + # Now melt the data to long form + melt_kws = {"var_name": "@columns", "value_name": "@values"} + use_index = "@index" in self.wide_structure.values() + if use_index: + melt_kws["id_vars"] = "@index" + try: + orig_categories = wide_data.columns.categories + orig_ordered = wide_data.columns.ordered + wide_data.columns = wide_data.columns.add_categories("@index") + except AttributeError: + category_columns = False + else: + category_columns = True + wide_data["@index"] = wide_data.index.to_series() + + plot_data = wide_data.melt(**melt_kws) + + if use_index and category_columns: + plot_data["@columns"] = pd.Categorical(plot_data["@columns"], + orig_categories, + orig_ordered) + + # Assign names corresponding to plot semantics + for var, attr in self.wide_structure.items(): + plot_data[var] = plot_data[attr] + + # Define the variable names + variables = {} + for var, attr in self.wide_structure.items(): + obj = getattr(wide_data, attr[1:]) + variables[var] = getattr(obj, "name", None) + + # Remove redundant columns from plot_data + plot_data = plot_data[list(variables)] + + return plot_data, variables + + def _assign_variables_longform(self, data=None, **kwargs): + """Define plot variables given long-form data and/or vector inputs. + + Parameters + ---------- + data : dict-like collection of vectors + Input data where variable names map to vector values. + kwargs : variable -> data mappings + Keys are seaborn variables (x, y, hue, ...) and values are vectors + in any format that can construct a :class:`pandas.DataFrame` or + names of columns or index levels in ``data``. + + Returns + ------- + plot_data : :class:`pandas.DataFrame` + Long-form data object mapping seaborn variables (x, y, hue, ...) + to data vectors. + variables : dict + Keys are defined seaborn variables; values are names inferred from + the inputs (or None when no name can be determined). + + Raises + ------ + ValueError + When variables are strings that don't appear in ``data``. + + """ + plot_data = {} + variables = {} + + # Data is optional; all variables can be defined as vectors + if data is None: + data = {} + + # TODO should we try a data.to_dict() or similar here to more + # generally accept objects with that interface? + # Note that dict(df) also works for pandas, and gives us what we + # want, whereas DataFrame.to_dict() gives a nested dict instead of + # a dict of series. + + # Variables can also be extracted from the index attribute + # TODO is this the most general way to enable it? + # There is no index.to_dict on multiindex, unfortunately + try: + index = data.index.to_frame() + except AttributeError: + index = {} + + # The caller will determine the order of variables in plot_data + for key, val in kwargs.items(): + + # First try to treat the argument as a key for the data collection. + # But be flexible about what can be used as a key. + # Usually it will be a string, but allow numbers or tuples too when + # taking from the main data object. Only allow strings to reference + # fields in the index, because otherwise there is too much ambiguity. + try: + val_as_data_key = ( + val in data + or (isinstance(val, (str, bytes)) and val in index) + ) + except (KeyError, TypeError): + val_as_data_key = False + + if val_as_data_key: + + # We know that __getitem__ will work + + if val in data: + plot_data[key] = data[val] + elif val in index: + plot_data[key] = index[val] + variables[key] = val + + elif isinstance(val, (str, bytes)): + + # This looks like a column name but we don't know what it means! + + err = f"Could not interpret value `{val}` for parameter `{key}`" + raise ValueError(err) + + else: + + # Otherwise, assume the value is itself data + + # Raise when data object is present and a vector can't matched + if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series): + if np.ndim(val) and len(data) != len(val): + val_cls = val.__class__.__name__ + err = ( + f"Length of {val_cls} vectors must match length of `data`" + f" when both are used, but `data` has length {len(data)}" + f" and the vector passed to `{key}` has length {len(val)}." + ) + raise ValueError(err) + + plot_data[key] = val + + # Try to infer the name of the variable + variables[key] = getattr(val, "name", None) + + # Construct a tidy plot DataFrame. This will convert a number of + # types automatically, aligning on index in case of pandas objects + plot_data = pd.DataFrame(plot_data) + + # Reduce the variables dictionary to fields with valid data + variables = { + var: name + for var, name in variables.items() + if plot_data[var].notnull().any() + } + + return plot_data, variables + + def iter_data( + self, grouping_vars=None, *, + reverse=False, from_comp_data=False, + by_facet=True, allow_empty=False, dropna=True, + ): + """Generator for getting subsets of data defined by semantic variables. + + Also injects "col" and "row" into grouping semantics. + + Parameters + ---------- + grouping_vars : string or list of strings + Semantic variables that define the subsets of data. + reverse : bool + If True, reverse the order of iteration. + from_comp_data : bool + If True, use self.comp_data rather than self.plot_data + by_facet : bool + If True, add faceting variables to the set of grouping variables. + allow_empty : bool + If True, yield an empty dataframe when no observations exist for + combinations of grouping variables. + dropna : bool + If True, remove rows with missing data. + + Yields + ------ + sub_vars : dict + Keys are semantic names, values are the level of that semantic. + sub_data : :class:`pandas.DataFrame` + Subset of ``plot_data`` for this combination of semantic values. + + """ + # TODO should this default to using all (non x/y?) semantics? + # or define grouping vars somewhere? + if grouping_vars is None: + grouping_vars = [] + elif isinstance(grouping_vars, str): + grouping_vars = [grouping_vars] + elif isinstance(grouping_vars, tuple): + grouping_vars = list(grouping_vars) + + # Always insert faceting variables + if by_facet: + facet_vars = {"col", "row"} + grouping_vars.extend( + facet_vars & set(self.variables) - set(grouping_vars) + ) + + # Reduce to the semantics used in this plot + grouping_vars = [ + var for var in grouping_vars if var in self.variables + ] + + if from_comp_data: + data = self.comp_data + else: + data = self.plot_data + + if dropna: + data = data.dropna() + + levels = self.var_levels.copy() + if from_comp_data: + for axis in {"x", "y"} & set(grouping_vars): + if self.var_types[axis] == "categorical": + if self._var_ordered[axis]: + # If the axis is ordered, then the axes in a possible + # facet grid are by definition "shared", or there is a + # single axis with a unique cat -> idx mapping. + # So we can just take the first converter object. + converter = self.converters[axis].iloc[0] + levels[axis] = converter.convert_units(levels[axis]) + else: + # Otherwise, the mappings may not be unique, but we can + # use the unique set of index values in comp_data. + levels[axis] = np.sort(data[axis].unique()) + elif self.var_types[axis] == "datetime": + levels[axis] = mpl.dates.date2num(levels[axis]) + elif self.var_types[axis] == "numeric" and self._log_scaled(axis): + levels[axis] = np.log10(levels[axis]) + + if grouping_vars: + + grouped_data = data.groupby( + grouping_vars, sort=False, as_index=False + ) + + grouping_keys = [] + for var in grouping_vars: + grouping_keys.append(levels.get(var, [])) + + iter_keys = itertools.product(*grouping_keys) + if reverse: + iter_keys = reversed(list(iter_keys)) + + for key in iter_keys: + + # Pandas fails with singleton tuple inputs + pd_key = key[0] if len(key) == 1 else key + + try: + data_subset = grouped_data.get_group(pd_key) + except KeyError: + # XXX we are adding this to allow backwards compatibility + # with the empty artists that old categorical plots would + # add (before 0.12), which we may decide to break, in which + # case this option could be removed + data_subset = data.loc[[]] + + if data_subset.empty and not allow_empty: + continue + + sub_vars = dict(zip(grouping_vars, key)) + + yield sub_vars, data_subset.copy() + + else: + + yield {}, data.copy() + + @property + def comp_data(self): + """Dataframe with numeric x and y, after unit conversion and log scaling.""" + if not hasattr(self, "ax"): + # Probably a good idea, but will need a bunch of tests updated + # Most of these tests should just use the external interface + # Then this can be re-enabled. + # raise AttributeError("No Axes attached to plotter") + return self.plot_data + + if not hasattr(self, "_comp_data"): + + comp_data = ( + self.plot_data + .copy(deep=False) + .drop(["x", "y"], axis=1, errors="ignore") + ) + + for var in "yx": + if var not in self.variables: + continue + + parts = [] + grouped = self.plot_data[var].groupby(self.converters[var], sort=False) + for converter, orig in grouped: + with pd.option_context('mode.use_inf_as_na', True): + orig = orig.dropna() + if var in self.var_levels: + # TODO this should happen in some centralized location + # it is similar to GH2419, but more complicated because + # supporting `order` in categorical plots is tricky + orig = orig[orig.isin(self.var_levels[var])] + comp = pd.to_numeric(converter.convert_units(orig)) + if converter.get_scale() == "log": + comp = np.log10(comp) + parts.append(pd.Series(comp, orig.index, name=orig.name)) + if parts: + comp_col = pd.concat(parts) + else: + comp_col = pd.Series(dtype=float, name=var) + comp_data.insert(0, var, comp_col) + + self._comp_data = comp_data + + return self._comp_data + + def _get_axes(self, sub_vars): + """Return an Axes object based on existence of row/col variables.""" + row = sub_vars.get("row", None) + col = sub_vars.get("col", None) + if row is not None and col is not None: + return self.facets.axes_dict[(row, col)] + elif row is not None: + return self.facets.axes_dict[row] + elif col is not None: + return self.facets.axes_dict[col] + elif self.ax is None: + return self.facets.ax + else: + return self.ax + + def _attach( + self, + obj, + allowed_types=None, + log_scale=None, + ): + """Associate the plotter with an Axes manager and initialize its units. + + Parameters + ---------- + obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid` + Structural object that we will eventually plot onto. + allowed_types : str or list of str + If provided, raise when either the x or y variable does not have + one of the declared seaborn types. + log_scale : bool, number, or pair of bools or numbers + If not False, set the axes to use log scaling, with the given + base or defaulting to 10. If a tuple, interpreted as separate + arguments for the x and y axes. + + """ + from .axisgrid import FacetGrid + if isinstance(obj, FacetGrid): + self.ax = None + self.facets = obj + ax_list = obj.axes.flatten() + if obj.col_names is not None: + self.var_levels["col"] = obj.col_names + if obj.row_names is not None: + self.var_levels["row"] = obj.row_names + else: + self.ax = obj + self.facets = None + ax_list = [obj] + + # Identify which "axis" variables we have defined + axis_variables = set("xy").intersection(self.variables) + + # -- Verify the types of our x and y variables here. + # This doesn't really make complete sense being here here, but it's a fine + # place for it, given the current system. + # (Note that for some plots, there might be more complicated restrictions) + # e.g. the categorical plots have their own check that as specific to the + # non-categorical axis. + if allowed_types is None: + allowed_types = ["numeric", "datetime", "categorical"] + elif isinstance(allowed_types, str): + allowed_types = [allowed_types] + + for var in axis_variables: + var_type = self.var_types[var] + if var_type not in allowed_types: + err = ( + f"The {var} variable is {var_type}, but one of " + f"{allowed_types} is required" + ) + raise TypeError(err) + + # -- Get axis objects for each row in plot_data for type conversions and scaling + + facet_dim = {"x": "col", "y": "row"} + + self.converters = {} + for var in axis_variables: + other_var = {"x": "y", "y": "x"}[var] + + converter = pd.Series(index=self.plot_data.index, name=var, dtype=object) + share_state = getattr(self.facets, f"_share{var}", True) + + # Simplest cases are that we have a single axes, all axes are shared, + # or sharing is only on the orthogonal facet dimension. In these cases, + # all datapoints get converted the same way, so use the first axis + if share_state is True or share_state == facet_dim[other_var]: + converter.loc[:] = getattr(ax_list[0], f"{var}axis") + + else: + + # Next simplest case is when no axes are shared, and we can + # use the axis objects within each facet + if share_state is False: + for axes_vars, axes_data in self.iter_data(): + ax = self._get_axes(axes_vars) + converter.loc[axes_data.index] = getattr(ax, f"{var}axis") + + # In the more complicated case, the axes are shared within each + # "file" of the facetgrid. In that case, we need to subset the data + # for that file and assign it the first axis in the slice of the grid + else: + + names = getattr(self.facets, f"{share_state}_names") + for i, level in enumerate(names): + idx = (i, 0) if share_state == "row" else (0, i) + axis = getattr(self.facets.axes[idx], f"{var}axis") + converter.loc[self.plot_data[share_state] == level] = axis + + # Store the converter vector, which we use elsewhere (e.g comp_data) + self.converters[var] = converter + + # Now actually update the matplotlib objects to do the conversion we want + grouped = self.plot_data[var].groupby(self.converters[var], sort=False) + for converter, seed_data in grouped: + if self.var_types[var] == "categorical": + if self._var_ordered[var]: + order = self.var_levels[var] + else: + order = None + seed_data = categorical_order(seed_data, order) + converter.update_units(seed_data) + + # -- Set numerical axis scales + + # First unpack the log_scale argument + if log_scale is None: + scalex = scaley = False + else: + # Allow single value or x, y tuple + try: + scalex, scaley = log_scale + except TypeError: + scalex = log_scale if "x" in self.variables else False + scaley = log_scale if "y" in self.variables else False + + # Now use it + for axis, scale in zip("xy", (scalex, scaley)): + if scale: + for ax in ax_list: + set_scale = getattr(ax, f"set_{axis}scale") + if scale is True: + set_scale("log") + else: + set_scale("log", base=scale) + + # For categorical y, we want the "first" level to be at the top of the axis + if self.var_types.get("y", None) == "categorical": + for ax in ax_list: + try: + ax.yaxis.set_inverted(True) + except AttributeError: # mpl < 3.1 + if not ax.yaxis_inverted(): + ax.invert_yaxis() + + # TODO -- Add axes labels + + def _log_scaled(self, axis): + """Return True if specified axis is log scaled on all attached axes.""" + if not hasattr(self, "ax"): + return False + + if self.ax is None: + axes_list = self.facets.axes.flatten() + else: + axes_list = [self.ax] + + log_scaled = [] + for ax in axes_list: + data_axis = getattr(ax, f"{axis}axis") + log_scaled.append(data_axis.get_scale() == "log") + + if any(log_scaled) and not all(log_scaled): + raise RuntimeError("Axis scaling is not consistent") + + return any(log_scaled) + + def _add_axis_labels(self, ax, default_x="", default_y=""): + """Add axis labels if not present, set visibility to match ticklabels.""" + # TODO ax could default to None and use attached axes if present + # but what to do about the case of facets? Currently using FacetGrid's + # set_axis_labels method, which doesn't add labels to the interior even + # when the axes are not shared. Maybe that makes sense? + if not ax.get_xlabel(): + x_visible = any(t.get_visible() for t in ax.get_xticklabels()) + ax.set_xlabel(self.variables.get("x", default_x), visible=x_visible) + if not ax.get_ylabel(): + y_visible = any(t.get_visible() for t in ax.get_yticklabels()) + ax.set_ylabel(self.variables.get("y", default_y), visible=y_visible) + + # XXX If the scale_* methods are going to modify the plot_data structure, they + # can't be called twice. That means that if they are called twice, they should + # raise. Alternatively, we could store an original version of plot_data and each + # time they are called they operate on the store, not the current state. + + def scale_native(self, axis, *args, **kwargs): + + # Default, defer to matplotlib + + raise NotImplementedError + + def scale_numeric(self, axis, *args, **kwargs): + + # Feels needed to completeness, what should it do? + # Perhaps handle log scaling? Set the ticker/formatter/limits? + + raise NotImplementedError + + def scale_datetime(self, axis, *args, **kwargs): + + # Use pd.to_datetime to convert strings or numbers to datetime objects + # Note, use day-resolution for numeric->datetime to match matplotlib + + raise NotImplementedError + + def scale_categorical(self, axis, order=None, formatter=None): + """ + Enforce categorical (fixed-scale) rules for the data on given axis. + + Parameters + ---------- + axis : "x" or "y" + Axis of the plot to operate on. + order : list + Order that unique values should appear in. + formatter : callable + Function mapping values to a string representation. + + Returns + ------- + self + + """ + # This method both modifies the internal representation of the data + # (converting it to string) and sets some attributes on self. It might be + # a good idea to have a separate object attached to self that contains the + # information in those attributes (i.e. whether to enforce variable order + # across facets, the order to use) similar to the SemanticMapping objects + # we have for semantic variables. That object could also hold the converter + # objects that get used, if we can decouple those from an existing axis + # (cf. https://github.com/matplotlib/matplotlib/issues/19229). + # There are some interactions with faceting information that would need + # to be thought through, since the converts to use depend on facets. + # If we go that route, these methods could become "borrowed" methods similar + # to what happens with the alternate semantic mapper constructors, although + # that approach is kind of fussy and confusing. + + # TODO this method could also set the grid state? Since we like to have no + # grid on the categorical axis by default. Again, a case where we'll need to + # store information until we use it, so best to have a way to collect the + # attributes that this method sets. + + # TODO if we are going to set visual properties of the axes with these methods, + # then we could do the steps currently in CategoricalPlotter._adjust_cat_axis + + # TODO another, and distinct idea, is to expose a cut= param here + + _check_argument("axis", ["x", "y"], axis) + + # Categorical plots can be "univariate" in which case they get an anonymous + # category label on the opposite axis. + if axis not in self.variables: + self.variables[axis] = None + self.var_types[axis] = "categorical" + self.plot_data[axis] = "" + + # If the "categorical" variable has a numeric type, sort the rows so that + # the default result from categorical_order has those values sorted after + # they have been coerced to strings. The reason for this is so that later + # we can get facet-wise orders that are correct. + # XXX Should this also sort datetimes? + # It feels more consistent, but technically will be a default change + # If so, should also change categorical_order to behave that way + if self.var_types[axis] == "numeric": + self.plot_data = self.plot_data.sort_values(axis, kind="mergesort") + + # Now get a reference to the categorical data vector + cat_data = self.plot_data[axis] + + # Get the initial categorical order, which we do before string + # conversion to respect the original types of the order list. + # Track whether the order is given explicitly so that we can know + # whether or not to use the order constructed here downstream + self._var_ordered[axis] = order is not None or cat_data.dtype.name == "category" + order = pd.Index(categorical_order(cat_data, order)) + + # Then convert data to strings. This is because in matplotlib, + # "categorical" data really mean "string" data, so doing this artists + # will be drawn on the categorical axis with a fixed scale. + # TODO implement formatter here; check that it returns strings? + if formatter is not None: + cat_data = cat_data.map(formatter) + order = order.map(formatter) + else: + cat_data = cat_data.astype(str) + order = order.astype(str) + + # Update the levels list with the type-converted order variable + self.var_levels[axis] = order + + # Now ensure that seaborn will use categorical rules internally + self.var_types[axis] = "categorical" + + # Put the string-typed categorical vector back into the plot_data structure + self.plot_data[axis] = cat_data + + return self + + +class VariableType(UserString): + """ + Prevent comparisons elsewhere in the library from using the wrong name. + + Errors are simple assertions because users should not be able to trigger + them. If that changes, they should be more verbose. + + """ + # TODO we can replace this with typing.Literal on Python 3.8+ + allowed = "numeric", "datetime", "categorical" + + def __init__(self, data): + assert data in self.allowed, data + super().__init__(data) + + def __eq__(self, other): + assert other in self.allowed, other + return self.data == other + + +def variable_type(vector, boolean_type="numeric"): + """ + Determine whether a vector contains numeric, categorical, or datetime data. + + This function differs from the pandas typing API in two ways: + + - Python sequences or object-typed PyData objects are considered numeric if + all of their entries are numeric. + - String or mixed-type data are considered categorical even if not + explicitly represented as a :class:`pandas.api.types.CategoricalDtype`. + + Parameters + ---------- + vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence + Input data to test. + boolean_type : 'numeric' or 'categorical' + Type to use for vectors containing only 0s and 1s (and NAs). + + Returns + ------- + var_type : 'numeric', 'categorical', or 'datetime' + Name identifying the type of data in the vector. + """ + + # If a categorical dtype is set, infer categorical + if pd.api.types.is_categorical_dtype(vector): + return VariableType("categorical") + + # Special-case all-na data, which is always "numeric" + if pd.isna(vector).all(): + return VariableType("numeric") + + # Special-case binary/boolean data, allow caller to determine + # This triggers a numpy warning when vector has strings/objects + # https://github.com/numpy/numpy/issues/6784 + # Because we reduce with .all(), we are agnostic about whether the + # comparison returns a scalar or vector, so we will ignore the warning. + # It triggers a separate DeprecationWarning when the vector has datetimes: + # https://github.com/numpy/numpy/issues/13548 + # This is considered a bug by numpy and will likely go away. + with warnings.catch_warnings(): + warnings.simplefilter( + action='ignore', category=(FutureWarning, DeprecationWarning) + ) + if np.isin(vector, [0, 1, np.nan]).all(): + return VariableType(boolean_type) + + # Defer to positive pandas tests + if pd.api.types.is_numeric_dtype(vector): + return VariableType("numeric") + + if pd.api.types.is_datetime64_dtype(vector): + return VariableType("datetime") + + # --- If we get to here, we need to check the entries + + # Check for a collection where everything is a number + + def all_numeric(x): + for x_i in x: + if not isinstance(x_i, Number): + return False + return True + + if all_numeric(vector): + return VariableType("numeric") + + # Check for a collection where everything is a datetime + + def all_datetime(x): + for x_i in x: + if not isinstance(x_i, (datetime, np.datetime64)): + return False + return True + + if all_datetime(vector): + return VariableType("datetime") + + # Otherwise, our final fallback is to consider things categorical + + return VariableType("categorical") + + +def infer_orient(x=None, y=None, orient=None, require_numeric=True): + """Determine how the plot should be oriented based on the data. + + For historical reasons, the convention is to call a plot "horizontally" + or "vertically" oriented based on the axis representing its dependent + variable. Practically, this is used when determining the axis for + numerical aggregation. + + Parameters + ---------- + x, y : Vector data or None + Positional data vectors for the plot. + orient : string or None + Specified orientation, which must start with "v" or "h" if not None. + require_numeric : bool + If set, raise when the implied dependent variable is not numeric. + + Returns + ------- + orient : "v" or "h" + + Raises + ------ + ValueError: When `orient` is not None and does not start with "h" or "v" + TypeError: When dependent variable is not numeric, with `require_numeric` + + """ + + x_type = None if x is None else variable_type(x) + y_type = None if y is None else variable_type(y) + + nonnumeric_dv_error = "{} orientation requires numeric `{}` variable." + single_var_warning = "{} orientation ignored with only `{}` specified." + + if x is None: + if str(orient).startswith("h"): + warnings.warn(single_var_warning.format("Horizontal", "y")) + if require_numeric and y_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) + return "v" + + elif y is None: + if str(orient).startswith("v"): + warnings.warn(single_var_warning.format("Vertical", "x")) + if require_numeric and x_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) + return "h" + + elif str(orient).startswith("v"): + if require_numeric and y_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) + return "v" + + elif str(orient).startswith("h"): + if require_numeric and x_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) + return "h" + + elif orient is not None: + err = ( + "`orient` must start with 'v' or 'h' or be None, " + f"but `{repr(orient)}` was passed." + ) + raise ValueError(err) + + elif x_type != "categorical" and y_type == "categorical": + return "h" + + elif x_type != "numeric" and y_type == "numeric": + return "v" + + elif x_type == "numeric" and y_type != "numeric": + return "h" + + elif require_numeric and "numeric" not in (x_type, y_type): + err = "Neither the `x` nor `y` variable appears to be numeric." + raise TypeError(err) + + else: + return "v" + + +def unique_dashes(n): + """Build an arbitrarily long list of unique dash styles for lines. + + Parameters + ---------- + n : int + Number of unique dash specs to generate. + + Returns + ------- + dashes : list of strings or tuples + Valid arguments for the ``dashes`` parameter on + :class:`matplotlib.lines.Line2D`. The first spec is a solid + line (``""``), the remainder are sequences of long and short + dashes. + + """ + # Start with dash specs that are well distinguishable + dashes = [ + "", + (4, 1.5), + (1, 1), + (3, 1.25, 1.5, 1.25), + (5, 1, 1, 1), + ] + + # Now programmatically build as many as we need + p = 3 + while len(dashes) < n: + + # Take combinations of long and short dashes + a = itertools.combinations_with_replacement([3, 1.25], p) + b = itertools.combinations_with_replacement([4, 1], p) + + # Interleave the combinations, reversing one of the streams + segment_list = itertools.chain(*zip( + list(a)[1:-1][::-1], + list(b)[1:-1] + )) + + # Now insert the gaps + for segments in segment_list: + gap = min(segments) + spec = tuple(itertools.chain(*((seg, gap) for seg in segments))) + dashes.append(spec) + + p += 1 + + return dashes[:n] + + +def unique_markers(n): + """Build an arbitrarily long list of unique marker styles for points. + + Parameters + ---------- + n : int + Number of unique marker specs to generate. + + Returns + ------- + markers : list of string or tuples + Values for defining :class:`matplotlib.markers.MarkerStyle` objects. + All markers will be filled. + + """ + # Start with marker specs that are well distinguishable + markers = [ + "o", + "X", + (4, 0, 45), + "P", + (4, 0, 0), + (4, 1, 0), + "^", + (4, 1, 45), + "v", + ] + + # Now generate more from regular polygons of increasing order + s = 5 + while len(markers) < n: + a = 360 / (s + 1) / 2 + markers.extend([ + (s + 1, 1, a), + (s + 1, 0, a), + (s, 1, 0), + (s, 0, 0), + ]) + s += 1 + + # Convert to MarkerStyle object, using only exactly what we need + # markers = [mpl.markers.MarkerStyle(m) for m in markers[:n]] + + return markers[:n] + + +def categorical_order(vector, order=None): + """Return a list of unique data values. + + Determine an ordered list of levels in ``values``. + + Parameters + ---------- + vector : list, array, Categorical, or Series + Vector of "categorical" values + order : list-like, optional + Desired order of category levels to override the order determined + from the ``values`` object. + + Returns + ------- + order : list + Ordered list of category levels not including null values. + + """ + if order is None: + if hasattr(vector, "categories"): + order = vector.categories + else: + try: + order = vector.cat.categories + except (TypeError, AttributeError): + + try: + order = vector.unique() + except AttributeError: + order = pd.unique(vector) + + if variable_type(vector) == "numeric": + order = np.sort(order) + + order = filter(pd.notnull, order) + return list(order) diff --git a/testbed/mwaskom__seaborn/seaborn/_statistics.py b/testbed/mwaskom__seaborn/seaborn/_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe4fbe7b2f1f821a53305a825e640124e2c3936 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_statistics.py @@ -0,0 +1,554 @@ +"""Statistical transformations for visualization. + +This module is currently private, but is being written to eventually form part +of the public API. + +The classes should behave roughly in the style of scikit-learn. + +- All data-independent parameters should be passed to the class constructor. +- Each class should implement a default transformation that is exposed through + __call__. These are currently written for vector arguments, but I think + consuming a whole `plot_data` DataFrame and return it with transformed + variables would make more sense. +- Some class have data-dependent preprocessing that should be cached and used + multiple times (think defining histogram bins off all data and then counting + observations within each bin multiple times per data subsets). These currently + have unique names, but it would be good to have a common name. Not quite + `fit`, but something similar. +- Alternatively, the transform interface could take some information about grouping + variables and do a groupby internally. +- Some classes should define alternate transforms that might make the most sense + with a different function. For example, KDE usually evaluates the distribution + on a regular grid, but it would be useful for it to transform at the actual + datapoints. Then again, this could be controlled by a parameter at the time of + class instantiation. + +""" +from numbers import Number +import numpy as np +import pandas as pd +try: + from scipy.stats import gaussian_kde + _no_scipy = False +except ImportError: + from .external.kde import gaussian_kde + _no_scipy = True + +from .algorithms import bootstrap +from .utils import _check_argument + + +class KDE: + """Univariate and bivariate kernel density estimator.""" + def __init__( + self, *, + bw_method=None, + bw_adjust=1, + gridsize=200, + cut=3, + clip=None, + cumulative=False, + ): + """Initialize the estimator with its parameters. + + Parameters + ---------- + bw_method : string, scalar, or callable, optional + Method for determining the smoothing bandwidth to use; passed to + :class:`scipy.stats.gaussian_kde`. + bw_adjust : number, optional + Factor that multiplicatively scales the value chosen using + ``bw_method``. Increasing will make the curve smoother. See Notes. + gridsize : int, optional + Number of points on each dimension of the evaluation grid. + cut : number, optional + Factor, multiplied by the smoothing bandwidth, that determines how + far the evaluation grid extends past the extreme datapoints. When + set to 0, truncate the curve at the data limits. + clip : pair of numbers or None, or a pair of such pairs + Do not evaluate the density outside of these limits. + cumulative : bool, optional + If True, estimate a cumulative distribution function. Requires scipy. + + """ + if clip is None: + clip = None, None + + self.bw_method = bw_method + self.bw_adjust = bw_adjust + self.gridsize = gridsize + self.cut = cut + self.clip = clip + self.cumulative = cumulative + + if cumulative and _no_scipy: + raise RuntimeError("Cumulative KDE evaluation requires scipy") + + self.support = None + + def _define_support_grid(self, x, bw, cut, clip, gridsize): + """Create the grid of evaluation points depending for vector x.""" + clip_lo = -np.inf if clip[0] is None else clip[0] + clip_hi = +np.inf if clip[1] is None else clip[1] + gridmin = max(x.min() - bw * cut, clip_lo) + gridmax = min(x.max() + bw * cut, clip_hi) + return np.linspace(gridmin, gridmax, gridsize) + + def _define_support_univariate(self, x, weights): + """Create a 1D grid of evaluation points.""" + kde = self._fit(x, weights) + bw = np.sqrt(kde.covariance.squeeze()) + grid = self._define_support_grid( + x, bw, self.cut, self.clip, self.gridsize + ) + return grid + + def _define_support_bivariate(self, x1, x2, weights): + """Create a 2D grid of evaluation points.""" + clip = self.clip + if clip[0] is None or np.isscalar(clip[0]): + clip = (clip, clip) + + kde = self._fit([x1, x2], weights) + bw = np.sqrt(np.diag(kde.covariance).squeeze()) + + grid1 = self._define_support_grid( + x1, bw[0], self.cut, clip[0], self.gridsize + ) + grid2 = self._define_support_grid( + x2, bw[1], self.cut, clip[1], self.gridsize + ) + + return grid1, grid2 + + def define_support(self, x1, x2=None, weights=None, cache=True): + """Create the evaluation grid for a given data set.""" + if x2 is None: + support = self._define_support_univariate(x1, weights) + else: + support = self._define_support_bivariate(x1, x2, weights) + + if cache: + self.support = support + + return support + + def _fit(self, fit_data, weights=None): + """Fit the scipy kde while adding bw_adjust logic and version check.""" + fit_kws = {"bw_method": self.bw_method} + if weights is not None: + fit_kws["weights"] = weights + + kde = gaussian_kde(fit_data, **fit_kws) + kde.set_bandwidth(kde.factor * self.bw_adjust) + + return kde + + def _eval_univariate(self, x, weights=None): + """Fit and evaluate a univariate on univariate data.""" + support = self.support + if support is None: + support = self.define_support(x, cache=False) + + kde = self._fit(x, weights) + + if self.cumulative: + s_0 = support[0] + density = np.array([ + kde.integrate_box_1d(s_0, s_i) for s_i in support + ]) + else: + density = kde(support) + + return density, support + + def _eval_bivariate(self, x1, x2, weights=None): + """Fit and evaluate a univariate on bivariate data.""" + support = self.support + if support is None: + support = self.define_support(x1, x2, cache=False) + + kde = self._fit([x1, x2], weights) + + if self.cumulative: + + grid1, grid2 = support + density = np.zeros((grid1.size, grid2.size)) + p0 = grid1.min(), grid2.min() + for i, xi in enumerate(grid1): + for j, xj in enumerate(grid2): + density[i, j] = kde.integrate_box(p0, (xi, xj)) + + else: + + xx1, xx2 = np.meshgrid(*support) + density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape) + + return density, support + + def __call__(self, x1, x2=None, weights=None): + """Fit and evaluate on univariate or bivariate data.""" + if x2 is None: + return self._eval_univariate(x1, weights) + else: + return self._eval_bivariate(x1, x2, weights) + + +# Note: we no longer use this for univariate histograms in histplot, +# preferring _stats.Hist. We'll deprecate this once we have a bivariate Stat class. +class Histogram: + """Univariate and bivariate histogram estimator.""" + def __init__( + self, + stat="count", + bins="auto", + binwidth=None, + binrange=None, + discrete=False, + cumulative=False, + ): + """Initialize the estimator with its parameters. + + Parameters + ---------- + stat : str + Aggregate statistic to compute in each bin. + + - `count`: show the number of observations in each bin + - `frequency`: show the number of observations divided by the bin width + - `probability` or `proportion`: normalize such that bar heights sum to 1 + - `percent`: normalize such that bar heights sum to 100 + - `density`: normalize such that the total area of the histogram equals 1 + + bins : str, number, vector, or a pair of such values + Generic bin parameter that can be the name of a reference rule, + the number of bins, or the breaks of the bins. + Passed to :func:`numpy.histogram_bin_edges`. + binwidth : number or pair of numbers + Width of each bin, overrides ``bins`` but can be used with + ``binrange``. + binrange : pair of numbers or a pair of pairs + Lowest and highest value for bin edges; can be used either + with ``bins`` or ``binwidth``. Defaults to data extremes. + discrete : bool or pair of bools + If True, set ``binwidth`` and ``binrange`` such that bin + edges cover integer values in the dataset. + cumulative : bool + If True, return the cumulative statistic. + + """ + stat_choices = [ + "count", "frequency", "density", "probability", "proportion", "percent", + ] + _check_argument("stat", stat_choices, stat) + + self.stat = stat + self.bins = bins + self.binwidth = binwidth + self.binrange = binrange + self.discrete = discrete + self.cumulative = cumulative + + self.bin_kws = None + + def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete): + """Inner function that takes bin parameters as arguments.""" + if binrange is None: + start, stop = x.min(), x.max() + else: + start, stop = binrange + + if discrete: + bin_edges = np.arange(start - .5, stop + 1.5) + elif binwidth is not None: + step = binwidth + bin_edges = np.arange(start, stop + step, step) + # Handle roundoff error (maybe there is a less clumsy way?) + if bin_edges.max() < stop or len(bin_edges) < 2: + bin_edges = np.append(bin_edges, bin_edges.max() + step) + else: + bin_edges = np.histogram_bin_edges( + x, bins, binrange, weights, + ) + return bin_edges + + def define_bin_params(self, x1, x2=None, weights=None, cache=True): + """Given data, return numpy.histogram parameters to define bins.""" + if x2 is None: + + bin_edges = self._define_bin_edges( + x1, weights, self.bins, self.binwidth, self.binrange, self.discrete, + ) + + if isinstance(self.bins, (str, Number)): + n_bins = len(bin_edges) - 1 + bin_range = bin_edges.min(), bin_edges.max() + bin_kws = dict(bins=n_bins, range=bin_range) + else: + bin_kws = dict(bins=bin_edges) + + else: + + bin_edges = [] + for i, x in enumerate([x1, x2]): + + # Resolve out whether bin parameters are shared + # or specific to each variable + + bins = self.bins + if not bins or isinstance(bins, (str, Number)): + pass + elif isinstance(bins[i], str): + bins = bins[i] + elif len(bins) == 2: + bins = bins[i] + + binwidth = self.binwidth + if binwidth is None: + pass + elif not isinstance(binwidth, Number): + binwidth = binwidth[i] + + binrange = self.binrange + if binrange is None: + pass + elif not isinstance(binrange[0], Number): + binrange = binrange[i] + + discrete = self.discrete + if not isinstance(discrete, bool): + discrete = discrete[i] + + # Define the bins for this variable + + bin_edges.append(self._define_bin_edges( + x, weights, bins, binwidth, binrange, discrete, + )) + + bin_kws = dict(bins=tuple(bin_edges)) + + if cache: + self.bin_kws = bin_kws + + return bin_kws + + def _eval_bivariate(self, x1, x2, weights): + """Inner function for histogram of two variables.""" + bin_kws = self.bin_kws + if bin_kws is None: + bin_kws = self.define_bin_params(x1, x2, cache=False) + + density = self.stat == "density" + + hist, *bin_edges = np.histogram2d( + x1, x2, **bin_kws, weights=weights, density=density + ) + + area = np.outer( + np.diff(bin_edges[0]), + np.diff(bin_edges[1]), + ) + + if self.stat == "probability" or self.stat == "proportion": + hist = hist.astype(float) / hist.sum() + elif self.stat == "percent": + hist = hist.astype(float) / hist.sum() * 100 + elif self.stat == "frequency": + hist = hist.astype(float) / area + + if self.cumulative: + if self.stat in ["density", "frequency"]: + hist = (hist * area).cumsum(axis=0).cumsum(axis=1) + else: + hist = hist.cumsum(axis=0).cumsum(axis=1) + + return hist, bin_edges + + def _eval_univariate(self, x, weights): + """Inner function for histogram of one variable.""" + bin_kws = self.bin_kws + if bin_kws is None: + bin_kws = self.define_bin_params(x, weights=weights, cache=False) + + density = self.stat == "density" + hist, bin_edges = np.histogram( + x, **bin_kws, weights=weights, density=density, + ) + + if self.stat == "probability" or self.stat == "proportion": + hist = hist.astype(float) / hist.sum() + elif self.stat == "percent": + hist = hist.astype(float) / hist.sum() * 100 + elif self.stat == "frequency": + hist = hist.astype(float) / np.diff(bin_edges) + + if self.cumulative: + if self.stat in ["density", "frequency"]: + hist = (hist * np.diff(bin_edges)).cumsum() + else: + hist = hist.cumsum() + + return hist, bin_edges + + def __call__(self, x1, x2=None, weights=None): + """Count the occurrences in each bin, maybe normalize.""" + if x2 is None: + return self._eval_univariate(x1, weights) + else: + return self._eval_bivariate(x1, x2, weights) + + +class ECDF: + """Univariate empirical cumulative distribution estimator.""" + def __init__(self, stat="proportion", complementary=False): + """Initialize the class with its parameters + + Parameters + ---------- + stat : {{"proportion", "count"}} + Distribution statistic to compute. + complementary : bool + If True, use the complementary CDF (1 - CDF) + + """ + _check_argument("stat", ["count", "proportion"], stat) + self.stat = stat + self.complementary = complementary + + def _eval_bivariate(self, x1, x2, weights): + """Inner function for ECDF of two variables.""" + raise NotImplementedError("Bivariate ECDF is not implemented") + + def _eval_univariate(self, x, weights): + """Inner function for ECDF of one variable.""" + sorter = x.argsort() + x = x[sorter] + weights = weights[sorter] + y = weights.cumsum() + + if self.stat == "proportion": + y = y / y.max() + + x = np.r_[-np.inf, x] + y = np.r_[0, y] + + if self.complementary: + y = y.max() - y + + return y, x + + def __call__(self, x1, x2=None, weights=None): + """Return proportion or count of observations below each sorted datapoint.""" + x1 = np.asarray(x1) + if weights is None: + weights = np.ones_like(x1) + else: + weights = np.asarray(weights) + + if x2 is None: + return self._eval_univariate(x1, weights) + else: + return self._eval_bivariate(x1, x2, weights) + + +class EstimateAggregator: + + def __init__(self, estimator, errorbar=None, **boot_kws): + """ + Data aggregator that produces an estimate and error bar interval. + + Parameters + ---------- + estimator : callable or string + Function (or method name) that maps a vector to a scalar. + errorbar : string, (string, number) tuple, or callable + Name of errorbar method (either "ci", "pi", "se", or "sd"), or a tuple + with a method name and a level parameter, or a function that maps from a + vector to a (min, max) interval. + boot_kws + Additional keywords are passed to bootstrap when error_method is "ci". + + """ + self.estimator = estimator + + method, level = _validate_errorbar_arg(errorbar) + self.error_method = method + self.error_level = level + + self.boot_kws = boot_kws + + def __call__(self, data, var): + """Aggregate over `var` column of `data` with estimate and error interval.""" + vals = data[var] + if callable(self.estimator): + # You would think we could pass to vals.agg, and yet: + # https://github.com/mwaskom/seaborn/issues/2943 + estimate = self.estimator(vals) + else: + estimate = vals.agg(self.estimator) + + # Options that produce no error bars + if self.error_method is None: + err_min = err_max = np.nan + elif len(data) <= 1: + err_min = err_max = np.nan + + # Generic errorbars from user-supplied function + elif callable(self.error_method): + err_min, err_max = self.error_method(vals) + + # Parametric options + elif self.error_method == "sd": + half_interval = vals.std() * self.error_level + err_min, err_max = estimate - half_interval, estimate + half_interval + elif self.error_method == "se": + half_interval = vals.sem() * self.error_level + err_min, err_max = estimate - half_interval, estimate + half_interval + + # Nonparametric options + elif self.error_method == "pi": + err_min, err_max = _percentile_interval(vals, self.error_level) + elif self.error_method == "ci": + units = data.get("units", None) + boots = bootstrap(vals, units=units, func=self.estimator, **self.boot_kws) + err_min, err_max = _percentile_interval(boots, self.error_level) + + return pd.Series({var: estimate, f"{var}min": err_min, f"{var}max": err_max}) + + +def _percentile_interval(data, width): + """Return a percentile interval from data of a given width.""" + edge = (100 - width) / 2 + percentiles = edge, 100 - edge + return np.nanpercentile(data, percentiles) + + +def _validate_errorbar_arg(arg): + """Check type and value of errorbar argument and assign default level.""" + DEFAULT_LEVELS = { + "ci": 95, + "pi": 95, + "se": 1, + "sd": 1, + } + + usage = "`errorbar` must be a callable, string, or (string, number) tuple" + + if arg is None: + return None, None + elif callable(arg): + return arg, None + elif isinstance(arg, str): + method = arg + level = DEFAULT_LEVELS.get(method, None) + else: + try: + method, level = arg + except (ValueError, TypeError) as err: + raise err.__class__(usage) from err + + _check_argument("errorbar", list(DEFAULT_LEVELS), method) + if level is not None and not isinstance(level, Number): + raise TypeError(usage) + + return method, level diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/__init__.py b/testbed/mwaskom__seaborn/seaborn/_stats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/aggregation.py b/testbed/mwaskom__seaborn/seaborn/_stats/aggregation.py new file mode 100644 index 0000000000000000000000000000000000000000..d175273e78b166bf947d5a4c6b985e05ab53070f --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/aggregation.py @@ -0,0 +1,118 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import ClassVar, Callable + +import pandas as pd +from pandas import DataFrame + +from seaborn._core.scales import Scale +from seaborn._core.groupby import GroupBy +from seaborn._stats.base import Stat +from seaborn._statistics import EstimateAggregator +from seaborn._core.typing import Vector + + +@dataclass +class Agg(Stat): + """ + Aggregate data along the value axis using given method. + + Parameters + ---------- + func : str or callable + Name of a :class:`pandas.Series` method or a vector -> scalar function. + + See Also + -------- + objects.Est : Aggregation with error bars. + + Examples + -------- + .. include:: ../docstrings/objects.Agg.rst + + """ + func: str | Callable[[Vector], float] = "mean" + + group_by_orient: ClassVar[bool] = True + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + var = {"x": "y", "y": "x"}.get(orient) + res = ( + groupby + .agg(data, {var: self.func}) + .dropna(subset=[var]) + .reset_index(drop=True) + ) + return res + + +@dataclass +class Est(Stat): + """ + Calculate a point estimate and error bar interval. + + For additional information about the various `errorbar` choices, see + the :doc:`errorbar tutorial
`. + + Parameters + ---------- + func : str or callable + Name of a :class:`numpy.ndarray` method or a vector -> scalar function. + errorbar : str, (str, float) tuple, or callable + Name of errorbar method (one of "ci", "pi", "se" or "sd"), or a tuple + with a method name ane a level parameter, or a function that maps from a + vector to a (min, max) interval. + n_boot : int + Number of bootstrap samples to draw for "ci" errorbars. + seed : int + Seed for the PRNG used to draw bootstrap samples. + + Examples + -------- + .. include:: ../docstrings/objects.Est.rst + + """ + func: str | Callable[[Vector], float] = "mean" + errorbar: str | tuple[str, float] = ("ci", 95) + n_boot: int = 1000 + seed: int | None = None + + group_by_orient: ClassVar[bool] = True + + def _process( + self, data: DataFrame, var: str, estimator: EstimateAggregator + ) -> DataFrame: + # Needed because GroupBy.apply assumes func is DataFrame -> DataFrame + # which we could probably make more general to allow Series return + res = estimator(data, var) + return pd.DataFrame([res]) + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + boot_kws = {"n_boot": self.n_boot, "seed": self.seed} + engine = EstimateAggregator(self.func, self.errorbar, **boot_kws) + + var = {"x": "y", "y": "x"}[orient] + res = ( + groupby + .apply(data, self._process, var, engine) + .dropna(subset=[var]) + .reset_index(drop=True) + ) + + res = res.fillna({f"{var}min": res[var], f"{var}max": res[var]}) + + return res + + +@dataclass +class Rolling(Stat): + ... + + def __call__(self, data, groupby, orient, scales): + ... diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/base.py b/testbed/mwaskom__seaborn/seaborn/_stats/base.py new file mode 100644 index 0000000000000000000000000000000000000000..b80b228165406f2103f00ce9bb0143bf16c02002 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/base.py @@ -0,0 +1,65 @@ +"""Base module for statistical transformations.""" +from __future__ import annotations +from collections.abc import Iterable +from dataclasses import dataclass +from typing import ClassVar, Any +import warnings + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from pandas import DataFrame + from seaborn._core.groupby import GroupBy + from seaborn._core.scales import Scale + + +@dataclass +class Stat: + """Base class for objects that apply statistical transformations.""" + + # The class supports a partial-function application pattern. The object is + # initialized with desired parameters and the result is a callable that + # accepts and returns dataframes. + + # The statistical transformation logic should not add any state to the instance + # beyond what is defined with the initialization parameters. + + # Subclasses can declare whether the orient dimension should be used in grouping + # TODO consider whether this should be a parameter. Motivating example: + # use the same KDE class violin plots and univariate density estimation. + # In the former case, we would expect separate densities for each unique + # value on the orient axis, but we would not in the latter case. + group_by_orient: ClassVar[bool] = False + + def _check_param_one_of(self, param: str, options: Iterable[Any]) -> None: + """Raise when parameter value is not one of a specified set.""" + value = getattr(self, param) + if value not in options: + *most, last = options + option_str = ", ".join(f"{x!r}" for x in most[:-1]) + f" or {last!r}" + err = " ".join([ + f"The `{param}` parameter for `{self.__class__.__name__}` must be", + f"one of {option_str}; not {value!r}.", + ]) + raise ValueError(err) + + def _check_grouping_vars( + self, param: str, data_vars: list[str], stacklevel: int = 2, + ) -> None: + """Warn if vars are named in parameter without being present in the data.""" + param_vars = getattr(self, param) + undefined = set(param_vars) - set(data_vars) + if undefined: + param = f"{self.__class__.__name__}.{param}" + names = ", ".join(f"{x!r}" for x in undefined) + msg = f"Undefined variable(s) passed for {param}: {names}." + warnings.warn(msg, stacklevel=stacklevel) + + def __call__( + self, + data: DataFrame, + groupby: GroupBy, + orient: str, + scales: dict[str, Scale], + ) -> DataFrame: + """Apply statistical transform to data subgroups and return combined result.""" + return data diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/counting.py b/testbed/mwaskom__seaborn/seaborn/_stats/counting.py new file mode 100644 index 0000000000000000000000000000000000000000..3faac5fb361784713c03710b03795957f98998c3 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/counting.py @@ -0,0 +1,232 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import ClassVar + +import numpy as np +import pandas as pd +from pandas import DataFrame + +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale +from seaborn._stats.base import Stat + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from numpy.typing import ArrayLike + + +@dataclass +class Count(Stat): + """ + Count distinct observations within groups. + + See Also + -------- + Hist : A more fully-featured transform including binning and/or normalization. + + Examples + -------- + .. include:: ../docstrings/objects.Count.rst + + """ + group_by_orient: ClassVar[bool] = True + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + var = {"x": "y", "y": "x"}.get(orient) + data[var] = data[orient] + res = ( + groupby + .agg(data, {var: len}) + .dropna(subset=["x", "y"]) + .reset_index(drop=True) + ) + return res + + +@dataclass +class Hist(Stat): + """ + Bin observations, count them, and optionally normalize or cumulate. + + Parameters + ---------- + stat : str + Aggregate statistic to compute in each bin: + + - `count`: the number of observations + - `density`: normalize so that the total area of the histogram equals 1 + - `percent`: normalize so that bar heights sum to 100 + - `probability` or `proportion`: normalize so that bar heights sum to 1 + - `frequency`: divide the number of observations by the bin width + + bins : str, int, or ArrayLike + Generic parameter that can be the name of a reference rule, the number + of bins, or the bin breaks. Passed to :func:`numpy.histogram_bin_edges`. + binwidth : float + Width of each bin; overrides `bins` but can be used with `binrange`. + binrange : (min, max) + Lowest and highest value for bin edges; can be used with either + `bins` (when a number) or `binwidth`. Defaults to data extremes. + common_norm : bool or list of variables + When not `False`, the normalization is applied across groups. Use + `True` to normalize across all groups, or pass variable name(s) that + define normalization groups. + common_bins : bool or list of variables + When not `False`, the same bins are used for all groups. Use `True` to + share bins across all groups, or pass variable name(s) to share within. + cumulative : bool + If True, cumulate the bin values. + discrete : bool + If True, set `binwidth` and `binrange` so that bins have unit width and + are centered on integer values + + Notes + ----- + The choice of bins for computing and plotting a histogram can exert + substantial influence on the insights that one is able to draw from the + visualization. If the bins are too large, they may erase important features. + On the other hand, bins that are too small may be dominated by random + variability, obscuring the shape of the true underlying distribution. The + default bin size is determined using a reference rule that depends on the + sample size and variance. This works well in many cases, (i.e., with + "well-behaved" data) but it fails in others. It is always a good to try + different bin sizes to be sure that you are not missing something important. + This function allows you to specify bins in several different ways, such as + by setting the total number of bins to use, the width of each bin, or the + specific locations where the bins should break. + + Examples + -------- + .. include:: ../docstrings/objects.Hist.rst + + """ + stat: str = "count" + bins: str | int | ArrayLike = "auto" + binwidth: float | None = None + binrange: tuple[float, float] | None = None + common_norm: bool | list[str] = True + common_bins: bool | list[str] = True + cumulative: bool = False + discrete: bool = False + + def __post_init__(self): + + stat_options = [ + "count", "density", "percent", "probability", "proportion", "frequency" + ] + self._check_param_one_of("stat", stat_options) + + def _define_bin_edges(self, vals, weight, bins, binwidth, binrange, discrete): + """Inner function that takes bin parameters as arguments.""" + vals = vals.dropna() + + if binrange is None: + start, stop = vals.min(), vals.max() + else: + start, stop = binrange + + if discrete: + bin_edges = np.arange(start - .5, stop + 1.5) + elif binwidth is not None: + step = binwidth + bin_edges = np.arange(start, stop + step, step) + else: + bin_edges = np.histogram_bin_edges(vals, bins, binrange, weight) + + # TODO warning or cap on too many bins? + + return bin_edges + + def _define_bin_params(self, data, orient, scale_type): + """Given data, return numpy.histogram parameters to define bins.""" + vals = data[orient] + weights = data.get("weight", None) + + # TODO We'll want this for ordinal / discrete scales too + # (Do we need discrete as a parameter or just infer from scale?) + discrete = self.discrete or scale_type == "nominal" + + bin_edges = self._define_bin_edges( + vals, weights, self.bins, self.binwidth, self.binrange, discrete, + ) + + if isinstance(self.bins, (str, int)): + n_bins = len(bin_edges) - 1 + bin_range = bin_edges.min(), bin_edges.max() + bin_kws = dict(bins=n_bins, range=bin_range) + else: + bin_kws = dict(bins=bin_edges) + + return bin_kws + + def _get_bins_and_eval(self, data, orient, groupby, scale_type): + + bin_kws = self._define_bin_params(data, orient, scale_type) + return groupby.apply(data, self._eval, orient, bin_kws) + + def _eval(self, data, orient, bin_kws): + + vals = data[orient] + weights = data.get("weight", None) + + density = self.stat == "density" + hist, edges = np.histogram(vals, **bin_kws, weights=weights, density=density) + + width = np.diff(edges) + center = edges[:-1] + width / 2 + + return pd.DataFrame({orient: center, "count": hist, "space": width}) + + def _normalize(self, data): + + hist = data["count"] + if self.stat == "probability" or self.stat == "proportion": + hist = hist.astype(float) / hist.sum() + elif self.stat == "percent": + hist = hist.astype(float) / hist.sum() * 100 + elif self.stat == "frequency": + hist = hist.astype(float) / data["space"] + + if self.cumulative: + if self.stat in ["density", "frequency"]: + hist = (hist * data["space"]).cumsum() + else: + hist = hist.cumsum() + + return data.assign(**{self.stat: hist}) + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + scale_type = scales[orient].__class__.__name__.lower() + grouping_vars = [str(v) for v in data if v in groupby.order] + if not grouping_vars or self.common_bins is True: + bin_kws = self._define_bin_params(data, orient, scale_type) + data = groupby.apply(data, self._eval, orient, bin_kws) + else: + if self.common_bins is False: + bin_groupby = GroupBy(grouping_vars) + else: + bin_groupby = GroupBy(self.common_bins) + self._check_grouping_vars("common_bins", grouping_vars) + + data = bin_groupby.apply( + data, self._get_bins_and_eval, orient, groupby, scale_type, + ) + + if not grouping_vars or self.common_norm is True: + data = self._normalize(data) + else: + if self.common_norm is False: + norm_groupby = GroupBy(grouping_vars) + else: + norm_groupby = GroupBy(self.common_norm) + self._check_grouping_vars("common_norm", grouping_vars) + data = norm_groupby.apply(data, self._normalize) + + other = {"x": "y", "y": "x"}[orient] + return data.assign(**{other: data[self.stat]}) diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/density.py b/testbed/mwaskom__seaborn/seaborn/_stats/density.py new file mode 100644 index 0000000000000000000000000000000000000000..e461387651556a28ded23d6583d78e8fff8e38b3 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/density.py @@ -0,0 +1,214 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import Any, Callable + +import numpy as np +from numpy import ndarray +import pandas as pd +from pandas import DataFrame +try: + from scipy.stats import gaussian_kde + _no_scipy = False +except ImportError: + from seaborn.external.kde import gaussian_kde + _no_scipy = True + +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale +from seaborn._stats.base import Stat + + +@dataclass +class KDE(Stat): + """ + Compute a univariate kernel density estimate. + + Parameters + ---------- + bw_adjust : float + Factor that multiplicatively scales the value chosen using + `bw_method`. Increasing will make the curve smoother. See Notes. + bw_method : string, scalar, or callable + Method for determining the smoothing bandwidth to use. Passed directly + to :class:`scipy.stats.gaussian_kde`; see there for options. + common_norm : bool or list of variables + If `True`, normalize so that the areas of all curves sums to 1. + If `False`, normalize each curve independently. If a list, defines + variable(s) to group by and normalize within. + common_grid : bool or list of variables + If `True`, all curves will share the same evaluation grid. + If `False`, each evaluation grid is independent. If a list, defines + variable(s) to group by and share a grid within. + gridsize : int or None + Number of points in the evaluation grid. If None, the density is + evaluated at the original datapoints. + cut : float + Factor, multiplied by the kernel bandwidth, that determines how far + the evaluation grid extends past the extreme datapoints. When set to 0, + the curve is truncated at the data limits. + cumulative : bool + If True, estimate a cumulative distribution function. Requires scipy. + + Notes + ----- + The *bandwidth*, or standard deviation of the smoothing kernel, is an + important parameter. Much like histogram bin width, using the wrong + bandwidth can produce a distorted representation. Over-smoothing can erase + true features, while under-smoothing can create false ones. The default + uses a rule-of-thumb that works best for distributions that are roughly + bell-shaped. It is a good idea to check the default by varying `bw_adjust`. + + Because the smoothing is performed with a Gaussian kernel, the estimated + density curve can extend to values that may not make sense. For example, the + curve may be drawn over negative values when data that are naturally + positive. The `cut` parameter can be used to control the evaluation range, + but datasets that have many observations close to a natural boundary may be + better served by a different method. + + Similar distortions may arise when a dataset is naturally discrete or "spiky" + (containing many repeated observations of the same value). KDEs will always + produce a smooth curve, which could be misleading. + + The units on the density axis are a common source of confusion. While kernel + density estimation produces a probability distribution, the height of the curve + at each point gives a density, not a probability. A probability can be obtained + only by integrating the density across a range. The curve is normalized so + that the integral over all possible values is 1, meaning that the scale of + the density axis depends on the data values. + + If scipy is installed, its cython-accelerated implementation will be used. + + Examples + -------- + .. include:: ../docstrings/objects.KDE.rst + + """ + bw_adjust: float = 1 + bw_method: str | float | Callable[[gaussian_kde], float] = "scott" + common_norm: bool | list[str] = True + common_grid: bool | list[str] = True + gridsize: int | None = 200 + cut: float = 3 + cumulative: bool = False + + def __post_init__(self): + + if self.cumulative and _no_scipy: + raise RuntimeError("Cumulative KDE evaluation requires scipy") + + def _check_var_list_or_boolean(self, param: str, grouping_vars: Any) -> None: + """Do input checks on grouping parameters.""" + value = getattr(self, param) + if not ( + isinstance(value, bool) + or (isinstance(value, list) and all(isinstance(v, str) for v in value)) + ): + param_name = f"{self.__class__.__name__}.{param}" + raise TypeError(f"{param_name} must be a boolean or list of strings.") + self._check_grouping_vars(param, grouping_vars, stacklevel=3) + + def _fit(self, data: DataFrame, orient: str) -> gaussian_kde: + """Fit and return a KDE object.""" + # TODO need to handle singular data + + fit_kws: dict[str, Any] = {"bw_method": self.bw_method} + if "weight" in data: + fit_kws["weights"] = data["weight"] + kde = gaussian_kde(data[orient], **fit_kws) + kde.set_bandwidth(kde.factor * self.bw_adjust) + + return kde + + def _get_support(self, data: DataFrame, orient: str) -> ndarray: + """Define the grid that the KDE will be evaluated on.""" + if self.gridsize is None: + return data[orient].to_numpy() + + kde = self._fit(data, orient) + bw = np.sqrt(kde.covariance.squeeze()) + gridmin = data[orient].min() - bw * self.cut + gridmax = data[orient].max() + bw * self.cut + return np.linspace(gridmin, gridmax, self.gridsize) + + def _fit_and_evaluate( + self, data: DataFrame, orient: str, support: ndarray + ) -> DataFrame: + """Transform single group by fitting a KDE and evaluating on a support grid.""" + empty = pd.DataFrame(columns=[orient, "weight", "density"], dtype=float) + if len(data) < 2: + return empty + try: + kde = self._fit(data, orient) + except np.linalg.LinAlgError: + return empty + + if self.cumulative: + s_0 = support[0] + density = np.array([kde.integrate_box_1d(s_0, s_i) for s_i in support]) + else: + density = kde(support) + + weight = data["weight"].sum() + return pd.DataFrame({orient: support, "weight": weight, "density": density}) + + def _transform( + self, data: DataFrame, orient: str, grouping_vars: list[str] + ) -> DataFrame: + """Transform multiple groups by fitting KDEs and evaluating.""" + empty = pd.DataFrame(columns=[*data.columns, "density"], dtype=float) + if len(data) < 2: + return empty + try: + support = self._get_support(data, orient) + except np.linalg.LinAlgError: + return empty + + grouping_vars = [x for x in grouping_vars if data[x].nunique() > 1] + if not grouping_vars: + return self._fit_and_evaluate(data, orient, support) + groupby = GroupBy(grouping_vars) + return groupby.apply(data, self._fit_and_evaluate, orient, support) + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + if "weight" not in data: + data = data.assign(weight=1) + data = data.dropna(subset=[orient, "weight"]) + + # Transform each group separately + grouping_vars = [str(v) for v in data if v in groupby.order] + if not grouping_vars or self.common_grid is True: + res = self._transform(data, orient, grouping_vars) + else: + if self.common_grid is False: + grid_vars = grouping_vars + else: + self._check_var_list_or_boolean("common_grid", grouping_vars) + grid_vars = [v for v in self.common_grid if v in grouping_vars] + + res = ( + GroupBy(grid_vars) + .apply(data, self._transform, orient, grouping_vars) + ) + + # Normalize, potentially within groups + if not grouping_vars or self.common_norm is True: + res = res.assign(group_weight=data["weight"].sum()) + else: + if self.common_norm is False: + norm_vars = grouping_vars + else: + self._check_var_list_or_boolean("common_norm", grouping_vars) + norm_vars = [v for v in self.common_norm if v in grouping_vars] + + res = res.join( + data.groupby(norm_vars)["weight"].sum().rename("group_weight"), + on=norm_vars, + ) + + res["density"] *= res.eval("weight / group_weight") + value = {"x": "y", "y": "x"}[orient] + res[value] = res["density"] + return res.drop(["weight", "group_weight"], axis=1) diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/order.py b/testbed/mwaskom__seaborn/seaborn/_stats/order.py new file mode 100644 index 0000000000000000000000000000000000000000..c37c0985238efde6386e61055fca2d2f3ff2cc10 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/order.py @@ -0,0 +1,78 @@ + +from __future__ import annotations +from dataclasses import dataclass +from typing import ClassVar, cast +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +import numpy as np +from pandas import DataFrame + +from seaborn._core.scales import Scale +from seaborn._core.groupby import GroupBy +from seaborn._stats.base import Stat +from seaborn.utils import _version_predates + + +# From https://github.com/numpy/numpy/blob/main/numpy/lib/function_base.pyi +_MethodKind = Literal[ + "inverted_cdf", + "averaged_inverted_cdf", + "closest_observation", + "interpolated_inverted_cdf", + "hazen", + "weibull", + "linear", + "median_unbiased", + "normal_unbiased", + "lower", + "higher", + "midpoint", + "nearest", +] + + +@dataclass +class Perc(Stat): + """ + Replace observations with percentile values. + + Parameters + ---------- + k : list of numbers or int + If a list of numbers, this gives the percentiles (in [0, 100]) to compute. + If an integer, compute `k` evenly-spaced percentiles between 0 and 100. + For example, `k=5` computes the 0, 25, 50, 75, and 100th percentiles. + method : str + Method for interpolating percentiles between observed datapoints. + See :func:`numpy.percentile` for valid options and more information. + + Examples + -------- + .. include:: ../docstrings/objects.Perc.rst + + """ + k: int | list[float] = 5 + method: str = "linear" + + group_by_orient: ClassVar[bool] = True + + def _percentile(self, data: DataFrame, var: str) -> DataFrame: + + k = list(np.linspace(0, 100, self.k)) if isinstance(self.k, int) else self.k + method = cast(_MethodKind, self.method) + values = data[var].dropna() + if _version_predates(np, "1.22"): + res = np.percentile(values, k, interpolation=method) # type: ignore + else: + res = np.percentile(data[var].dropna(), k, method=method) + return DataFrame({var: res, "percentile": k}) + + def __call__( + self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], + ) -> DataFrame: + + var = {"x": "y", "y": "x"}[orient] + return groupby.apply(data, self._percentile, var) diff --git a/testbed/mwaskom__seaborn/seaborn/_stats/regression.py b/testbed/mwaskom__seaborn/seaborn/_stats/regression.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec81a4e5c6ae4eca0baad56b23a5cc1e21a9399 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_stats/regression.py @@ -0,0 +1,50 @@ +from __future__ import annotations +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +from seaborn._stats.base import Stat + + +@dataclass +class PolyFit(Stat): + """ + Fit a polynomial of the given order and resample data onto predicted curve. + """ + # This is a provisional class that is useful for building out functionality. + # It may or may not change substantially in form or dissappear as we think + # through the organization of the stats subpackage. + + order: int = 2 + gridsize: int = 100 + + def _fit_predict(self, data): + + x = data["x"] + y = data["y"] + if x.nunique() <= self.order: + # TODO warn? + xx = yy = [] + else: + p = np.polyfit(x, y, self.order) + xx = np.linspace(x.min(), x.max(), self.gridsize) + yy = np.polyval(p, xx) + + return pd.DataFrame(dict(x=xx, y=yy)) + + # TODO we should have a way of identifying the method that will be applied + # and then only define __call__ on a base-class of stats with this pattern + + def __call__(self, data, groupby, orient, scales): + + return ( + groupby + .apply(data.dropna(subset=["x", "y"]), self._fit_predict) + ) + + +@dataclass +class OLSFit(Stat): + + ... diff --git a/testbed/mwaskom__seaborn/seaborn/_testing.py b/testbed/mwaskom__seaborn/seaborn/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f821cbe26f44a720cc8863fe6a863d61a275dd --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/_testing.py @@ -0,0 +1,90 @@ +import numpy as np +import matplotlib as mpl +from matplotlib.colors import to_rgb, to_rgba +from numpy.testing import assert_array_equal + + +USE_PROPS = [ + "alpha", + "edgecolor", + "facecolor", + "fill", + "hatch", + "height", + "linestyle", + "linewidth", + "paths", + "xy", + "xydata", + "sizes", + "zorder", +] + + +def assert_artists_equal(list1, list2): + + assert len(list1) == len(list2) + for a1, a2 in zip(list1, list2): + assert a1.__class__ == a2.__class__ + prop1 = a1.properties() + prop2 = a2.properties() + for key in USE_PROPS: + if key not in prop1: + continue + v1 = prop1[key] + v2 = prop2[key] + if key == "paths": + for p1, p2 in zip(v1, v2): + assert_array_equal(p1.vertices, p2.vertices) + assert_array_equal(p1.codes, p2.codes) + elif key == "color": + v1 = mpl.colors.to_rgba(v1) + v2 = mpl.colors.to_rgba(v2) + assert v1 == v2 + elif isinstance(v1, np.ndarray): + assert_array_equal(v1, v2) + else: + assert v1 == v2 + + +def assert_legends_equal(leg1, leg2): + + assert leg1.get_title().get_text() == leg2.get_title().get_text() + for t1, t2 in zip(leg1.get_texts(), leg2.get_texts()): + assert t1.get_text() == t2.get_text() + + assert_artists_equal( + leg1.get_patches(), leg2.get_patches(), + ) + assert_artists_equal( + leg1.get_lines(), leg2.get_lines(), + ) + + +def assert_plots_equal(ax1, ax2, labels=True): + + assert_artists_equal(ax1.patches, ax2.patches) + assert_artists_equal(ax1.lines, ax2.lines) + assert_artists_equal(ax1.collections, ax2.collections) + + if labels: + assert ax1.get_xlabel() == ax2.get_xlabel() + assert ax1.get_ylabel() == ax2.get_ylabel() + + +def assert_colors_equal(a, b, check_alpha=True): + + def handle_array(x): + + if isinstance(x, np.ndarray): + if x.ndim > 1: + x = np.unique(x, axis=0).squeeze() + if x.ndim > 1: + raise ValueError("Color arrays must be 1 dimensional") + return x + + a = handle_array(a) + b = handle_array(b) + + f = to_rgba if check_alpha else to_rgb + assert f(a) == f(b) diff --git a/testbed/mwaskom__seaborn/seaborn/algorithms.py b/testbed/mwaskom__seaborn/seaborn/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..2e34b9dd9cdffb5d82f56674fac4896de91a4d0a --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/algorithms.py @@ -0,0 +1,120 @@ +"""Algorithms to support fitting routines in seaborn plotting functions.""" +import numpy as np +import warnings + + +def bootstrap(*args, **kwargs): + """Resample one or more arrays with replacement and store aggregate values. + + Positional arguments are a sequence of arrays to bootstrap along the first + axis and pass to a summary function. + + Keyword arguments: + n_boot : int, default=10000 + Number of iterations + axis : int, default=None + Will pass axis to ``func`` as a keyword argument. + units : array, default=None + Array of sampling unit IDs. When used the bootstrap resamples units + and then observations within units instead of individual + datapoints. + func : string or callable, default="mean" + Function to call on the args that are passed in. If string, uses as + name of function in the numpy namespace. If nans are present in the + data, will try to use nan-aware version of named function. + seed : Generator | SeedSequence | RandomState | int | None + Seed for the random number generator; useful if you want + reproducible resamples. + + Returns + ------- + boot_dist: array + array of bootstrapped statistic values + + """ + # Ensure list of arrays are same length + if len(np.unique(list(map(len, args)))) > 1: + raise ValueError("All input arrays must have the same length") + n = len(args[0]) + + # Default keyword arguments + n_boot = kwargs.get("n_boot", 10000) + func = kwargs.get("func", "mean") + axis = kwargs.get("axis", None) + units = kwargs.get("units", None) + random_seed = kwargs.get("random_seed", None) + if random_seed is not None: + msg = "`random_seed` has been renamed to `seed` and will be removed" + warnings.warn(msg) + seed = kwargs.get("seed", random_seed) + if axis is None: + func_kwargs = dict() + else: + func_kwargs = dict(axis=axis) + + # Initialize the resampler + if isinstance(seed, np.random.RandomState): + rng = seed + else: + rng = np.random.default_rng(seed) + + # Coerce to arrays + args = list(map(np.asarray, args)) + if units is not None: + units = np.asarray(units) + + if isinstance(func, str): + + # Allow named numpy functions + f = getattr(np, func) + + # Try to use nan-aware version of function if necessary + missing_data = np.isnan(np.sum(np.column_stack(args))) + + if missing_data and not func.startswith("nan"): + nanf = getattr(np, f"nan{func}", None) + if nanf is None: + msg = f"Data contain nans but no nan-aware version of `{func}` found" + warnings.warn(msg, UserWarning) + else: + f = nanf + + else: + f = func + + # Handle numpy changes + try: + integers = rng.integers + except AttributeError: + integers = rng.randint + + # Do the bootstrap + if units is not None: + return _structured_bootstrap(args, n_boot, units, f, + func_kwargs, integers) + + boot_dist = [] + for i in range(int(n_boot)): + resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype + sample = [a.take(resampler, axis=0) for a in args] + boot_dist.append(f(*sample, **func_kwargs)) + return np.array(boot_dist) + + +def _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers): + """Resample units instead of datapoints.""" + unique_units = np.unique(units) + n_units = len(unique_units) + + args = [[a[units == unit] for unit in unique_units] for a in args] + + boot_dist = [] + for i in range(int(n_boot)): + resampler = integers(0, n_units, n_units, dtype=np.intp) + sample = [[a[i] for i in resampler] for a in args] + lengths = map(len, sample[0]) + resampler = [integers(0, n, n, dtype=np.intp) for n in lengths] + sample = [[c.take(r, axis=0) for c, r in zip(a, resampler)] for a in sample] + sample = list(map(np.concatenate, sample)) + boot_dist.append(func(*sample, **func_kwargs)) + return np.array(boot_dist) diff --git a/testbed/mwaskom__seaborn/seaborn/axisgrid.py b/testbed/mwaskom__seaborn/seaborn/axisgrid.py new file mode 100644 index 0000000000000000000000000000000000000000..a57836999d059b39ec447b9af7c01fbf58923b20 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/axisgrid.py @@ -0,0 +1,2400 @@ +from __future__ import annotations +from itertools import product +from inspect import signature +import warnings +from textwrap import dedent + +import numpy as np +import pandas as pd +import matplotlib as mpl +import matplotlib.pyplot as plt + +from ._oldcore import VectorPlotter, variable_type, categorical_order +from ._compat import share_axis +from . import utils +from .utils import ( + adjust_legend_subtitles, _check_argument, _draw_figure, _disable_autolayout +) +from .palettes import color_palette, blend_palette +from ._docstrings import ( + DocstringComponents, + _core_docs, +) + +__all__ = ["FacetGrid", "PairGrid", "JointGrid", "pairplot", "jointplot"] + + +_param_docs = DocstringComponents.from_nested_components( + core=_core_docs["params"], +) + + +class _BaseGrid: + """Base class for grids of subplots.""" + + def set(self, **kwargs): + """Set attributes on each subplot Axes.""" + for ax in self.axes.flat: + if ax is not None: # Handle removed axes + ax.set(**kwargs) + return self + + @property + def fig(self): + """DEPRECATED: prefer the `figure` property.""" + # Grid.figure is preferred because it matches the Axes attribute name. + # But as the maintanace burden on having this property is minimal, + # let's be slow about formally deprecating it. For now just note its deprecation + # in the docstring; add a warning in version 0.13, and eventually remove it. + return self._figure + + @property + def figure(self): + """Access the :class:`matplotlib.figure.Figure` object underlying the grid.""" + return self._figure + + def apply(self, func, *args, **kwargs): + """ + Pass the grid to a user-supplied function and return self. + + The `func` must accept an object of this type for its first + positional argument. Additional arguments are passed through. + The return value of `func` is ignored; this method returns self. + See the `pipe` method if you want the return value. + + Added in v0.12.0. + + """ + func(self, *args, **kwargs) + return self + + def pipe(self, func, *args, **kwargs): + """ + Pass the grid to a user-supplied function and return its value. + + The `func` must accept an object of this type for its first + positional argument. Additional arguments are passed through. + The return value of `func` becomes the return value of this method. + See the `apply` method if you want to return self instead. + + Added in v0.12.0. + + """ + return func(self, *args, **kwargs) + + def savefig(self, *args, **kwargs): + """ + Save an image of the plot. + + This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches="tight" + by default. Parameters are passed through to the matplotlib function. + + """ + kwargs = kwargs.copy() + kwargs.setdefault("bbox_inches", "tight") + self.figure.savefig(*args, **kwargs) + + +class Grid(_BaseGrid): + """A grid that can have multiple subplots and an external legend.""" + _margin_titles = False + _legend_out = True + + def __init__(self): + + self._tight_layout_rect = [0, 0, 1, 1] + self._tight_layout_pad = None + + # This attribute is set externally and is a hack to handle newer functions that + # don't add proxy artists onto the Axes. We need an overall cleaner approach. + self._extract_legend_handles = False + + def tight_layout(self, *args, **kwargs): + """Call fig.tight_layout within rect that exclude the legend.""" + kwargs = kwargs.copy() + kwargs.setdefault("rect", self._tight_layout_rect) + if self._tight_layout_pad is not None: + kwargs.setdefault("pad", self._tight_layout_pad) + self._figure.tight_layout(*args, **kwargs) + return self + + def add_legend(self, legend_data=None, title=None, label_order=None, + adjust_subtitles=False, **kwargs): + """Draw a legend, maybe placing it outside axes and resizing the figure. + + Parameters + ---------- + legend_data : dict + Dictionary mapping label names (or two-element tuples where the + second element is a label name) to matplotlib artist handles. The + default reads from ``self._legend_data``. + title : string + Title for the legend. The default reads from ``self._hue_var``. + label_order : list of labels + The order that the legend entries should appear in. The default + reads from ``self.hue_names``. + adjust_subtitles : bool + If True, modify entries with invisible artists to left-align + the labels and set the font size to that of a title. + kwargs : key, value pairings + Other keyword arguments are passed to the underlying legend methods + on the Figure or Axes object. + + Returns + ------- + self : Grid instance + Returns self for easy chaining. + + """ + # Find the data for the legend + if legend_data is None: + legend_data = self._legend_data + if label_order is None: + if self.hue_names is None: + label_order = list(legend_data.keys()) + else: + label_order = list(map(utils.to_utf8, self.hue_names)) + + blank_handle = mpl.patches.Patch(alpha=0, linewidth=0) + handles = [legend_data.get(l, blank_handle) for l in label_order] + title = self._hue_var if title is None else title + title_size = mpl.rcParams["legend.title_fontsize"] + + # Unpack nested labels from a hierarchical legend + labels = [] + for entry in label_order: + if isinstance(entry, tuple): + _, label = entry + else: + label = entry + labels.append(label) + + # Set default legend kwargs + kwargs.setdefault("scatterpoints", 1) + + if self._legend_out: + + kwargs.setdefault("frameon", False) + kwargs.setdefault("loc", "center right") + + # Draw a full-figure legend outside the grid + figlegend = self._figure.legend(handles, labels, **kwargs) + + self._legend = figlegend + figlegend.set_title(title, prop={"size": title_size}) + + if adjust_subtitles: + adjust_legend_subtitles(figlegend) + + # Draw the plot to set the bounding boxes correctly + _draw_figure(self._figure) + + # Calculate and set the new width of the figure so the legend fits + legend_width = figlegend.get_window_extent().width / self._figure.dpi + fig_width, fig_height = self._figure.get_size_inches() + self._figure.set_size_inches(fig_width + legend_width, fig_height) + + # Draw the plot again to get the new transformations + _draw_figure(self._figure) + + # Now calculate how much space we need on the right side + legend_width = figlegend.get_window_extent().width / self._figure.dpi + space_needed = legend_width / (fig_width + legend_width) + margin = .04 if self._margin_titles else .01 + self._space_needed = margin + space_needed + right = 1 - self._space_needed + + # Place the subplot axes to give space for the legend + self._figure.subplots_adjust(right=right) + self._tight_layout_rect[2] = right + + else: + # Draw a legend in the first axis + ax = self.axes.flat[0] + kwargs.setdefault("loc", "best") + + leg = ax.legend(handles, labels, **kwargs) + leg.set_title(title, prop={"size": title_size}) + self._legend = leg + + if adjust_subtitles: + adjust_legend_subtitles(leg) + + return self + + def _update_legend_data(self, ax): + """Extract the legend data from an axes object and save it.""" + data = {} + + # Get data directly from the legend, which is necessary + # for newer functions that don't add labeled proxy artists + if ax.legend_ is not None and self._extract_legend_handles: + handles = ax.legend_.legendHandles + labels = [t.get_text() for t in ax.legend_.texts] + data.update({l: h for h, l in zip(handles, labels)}) + + handles, labels = ax.get_legend_handles_labels() + data.update({l: h for h, l in zip(handles, labels)}) + + self._legend_data.update(data) + + # Now clear the legend + ax.legend_ = None + + def _get_palette(self, data, hue, hue_order, palette): + """Get a list of colors for the hue variable.""" + if hue is None: + palette = color_palette(n_colors=1) + + else: + hue_names = categorical_order(data[hue], hue_order) + n_colors = len(hue_names) + + # By default use either the current color palette or HUSL + if palette is None: + current_palette = utils.get_color_cycle() + if n_colors > len(current_palette): + colors = color_palette("husl", n_colors) + else: + colors = color_palette(n_colors=n_colors) + + # Allow for palette to map from hue variable names + elif isinstance(palette, dict): + color_names = [palette[h] for h in hue_names] + colors = color_palette(color_names, n_colors) + + # Otherwise act as if we just got a list of colors + else: + colors = color_palette(palette, n_colors) + + palette = color_palette(colors, n_colors) + + return palette + + @property + def legend(self): + """The :class:`matplotlib.legend.Legend` object, if present.""" + try: + return self._legend + except AttributeError: + return None + + def tick_params(self, axis='both', **kwargs): + """Modify the ticks, tick labels, and gridlines. + + Parameters + ---------- + axis : {'x', 'y', 'both'} + The axis on which to apply the formatting. + kwargs : keyword arguments + Additional keyword arguments to pass to + :meth:`matplotlib.axes.Axes.tick_params`. + + Returns + ------- + self : Grid instance + Returns self for easy chaining. + + """ + for ax in self.figure.axes: + ax.tick_params(axis=axis, **kwargs) + return self + + +_facet_docs = dict( + + data=dedent("""\ + data : DataFrame + Tidy ("long-form") dataframe where each column is a variable and each + row is an observation.\ + """), + rowcol=dedent("""\ + row, col : vectors or keys in ``data`` + Variables that define subsets to plot on different facets.\ + """), + rowcol_order=dedent("""\ + {row,col}_order : vector of strings + Specify the order in which levels of the ``row`` and/or ``col`` variables + appear in the grid of subplots.\ + """), + col_wrap=dedent("""\ + col_wrap : int + "Wrap" the column variable at this width, so that the column facets + span multiple rows. Incompatible with a ``row`` facet.\ + """), + share_xy=dedent("""\ + share{x,y} : bool, 'col', or 'row' optional + If true, the facets will share y axes across columns and/or x axes + across rows.\ + """), + height=dedent("""\ + height : scalar + Height (in inches) of each facet. See also: ``aspect``.\ + """), + aspect=dedent("""\ + aspect : scalar + Aspect ratio of each facet, so that ``aspect * height`` gives the width + of each facet in inches.\ + """), + palette=dedent("""\ + palette : palette name, list, or dict + Colors to use for the different levels of the ``hue`` variable. Should + be something that can be interpreted by :func:`color_palette`, or a + dictionary mapping hue levels to matplotlib colors.\ + """), + legend_out=dedent("""\ + legend_out : bool + If ``True``, the figure size will be extended, and the legend will be + drawn outside the plot on the center right.\ + """), + margin_titles=dedent("""\ + margin_titles : bool + If ``True``, the titles for the row variable are drawn to the right of + the last column. This option is experimental and may not work in all + cases.\ + """), + facet_kws=dedent("""\ + facet_kws : dict + Additional parameters passed to :class:`FacetGrid`. + """), +) + + +class FacetGrid(Grid): + """Multi-plot grid for plotting conditional relationships.""" + + def __init__( + self, data, *, + row=None, col=None, hue=None, col_wrap=None, + sharex=True, sharey=True, height=3, aspect=1, palette=None, + row_order=None, col_order=None, hue_order=None, hue_kws=None, + dropna=False, legend_out=True, despine=True, + margin_titles=False, xlim=None, ylim=None, subplot_kws=None, + gridspec_kws=None, + ): + + super().__init__() + + # Determine the hue facet layer information + hue_var = hue + if hue is None: + hue_names = None + else: + hue_names = categorical_order(data[hue], hue_order) + + colors = self._get_palette(data, hue, hue_order, palette) + + # Set up the lists of names for the row and column facet variables + if row is None: + row_names = [] + else: + row_names = categorical_order(data[row], row_order) + + if col is None: + col_names = [] + else: + col_names = categorical_order(data[col], col_order) + + # Additional dict of kwarg -> list of values for mapping the hue var + hue_kws = hue_kws if hue_kws is not None else {} + + # Make a boolean mask that is True anywhere there is an NA + # value in one of the faceting variables, but only if dropna is True + none_na = np.zeros(len(data), bool) + if dropna: + row_na = none_na if row is None else data[row].isnull() + col_na = none_na if col is None else data[col].isnull() + hue_na = none_na if hue is None else data[hue].isnull() + not_na = ~(row_na | col_na | hue_na) + else: + not_na = ~none_na + + # Compute the grid shape + ncol = 1 if col is None else len(col_names) + nrow = 1 if row is None else len(row_names) + self._n_facets = ncol * nrow + + self._col_wrap = col_wrap + if col_wrap is not None: + if row is not None: + err = "Cannot use `row` and `col_wrap` together." + raise ValueError(err) + ncol = col_wrap + nrow = int(np.ceil(len(col_names) / col_wrap)) + self._ncol = ncol + self._nrow = nrow + + # Calculate the base figure size + # This can get stretched later by a legend + # TODO this doesn't account for axis labels + figsize = (ncol * height * aspect, nrow * height) + + # Validate some inputs + if col_wrap is not None: + margin_titles = False + + # Build the subplot keyword dictionary + subplot_kws = {} if subplot_kws is None else subplot_kws.copy() + gridspec_kws = {} if gridspec_kws is None else gridspec_kws.copy() + if xlim is not None: + subplot_kws["xlim"] = xlim + if ylim is not None: + subplot_kws["ylim"] = ylim + + # --- Initialize the subplot grid + + with _disable_autolayout(): + fig = plt.figure(figsize=figsize) + + if col_wrap is None: + + kwargs = dict(squeeze=False, + sharex=sharex, sharey=sharey, + subplot_kw=subplot_kws, + gridspec_kw=gridspec_kws) + + axes = fig.subplots(nrow, ncol, **kwargs) + + if col is None and row is None: + axes_dict = {} + elif col is None: + axes_dict = dict(zip(row_names, axes.flat)) + elif row is None: + axes_dict = dict(zip(col_names, axes.flat)) + else: + facet_product = product(row_names, col_names) + axes_dict = dict(zip(facet_product, axes.flat)) + + else: + + # If wrapping the col variable we need to make the grid ourselves + if gridspec_kws: + warnings.warn("`gridspec_kws` ignored when using `col_wrap`") + + n_axes = len(col_names) + axes = np.empty(n_axes, object) + axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws) + if sharex: + subplot_kws["sharex"] = axes[0] + if sharey: + subplot_kws["sharey"] = axes[0] + for i in range(1, n_axes): + axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws) + + axes_dict = dict(zip(col_names, axes)) + + # --- Set up the class attributes + + # Attributes that are part of the public API but accessed through + # a property so that Sphinx adds them to the auto class doc + self._figure = fig + self._axes = axes + self._axes_dict = axes_dict + self._legend = None + + # Public attributes that aren't explicitly documented + # (It's not obvious that having them be public was a good idea) + self.data = data + self.row_names = row_names + self.col_names = col_names + self.hue_names = hue_names + self.hue_kws = hue_kws + + # Next the private variables + self._nrow = nrow + self._row_var = row + self._ncol = ncol + self._col_var = col + + self._margin_titles = margin_titles + self._margin_titles_texts = [] + self._col_wrap = col_wrap + self._hue_var = hue_var + self._colors = colors + self._legend_out = legend_out + self._legend_data = {} + self._x_var = None + self._y_var = None + self._sharex = sharex + self._sharey = sharey + self._dropna = dropna + self._not_na = not_na + + # --- Make the axes look good + + self.set_titles() + self.tight_layout() + + if despine: + self.despine() + + if sharex in [True, 'col']: + for ax in self._not_bottom_axes: + for label in ax.get_xticklabels(): + label.set_visible(False) + ax.xaxis.offsetText.set_visible(False) + ax.xaxis.label.set_visible(False) + + if sharey in [True, 'row']: + for ax in self._not_left_axes: + for label in ax.get_yticklabels(): + label.set_visible(False) + ax.yaxis.offsetText.set_visible(False) + ax.yaxis.label.set_visible(False) + + __init__.__doc__ = dedent("""\ + Initialize the matplotlib figure and FacetGrid object. + + This class maps a dataset onto multiple axes arrayed in a grid of rows + and columns that correspond to *levels* of variables in the dataset. + The plots it produces are often called "lattice", "trellis", or + "small-multiple" graphics. + + It can also represent levels of a third variable with the ``hue`` + parameter, which plots different subsets of data in different colors. + This uses color to resolve elements on a third dimension, but only + draws subsets on top of each other and will not tailor the ``hue`` + parameter for the specific visualization the way that axes-level + functions that accept ``hue`` will. + + The basic workflow is to initialize the :class:`FacetGrid` object with + the dataset and the variables that are used to structure the grid. Then + one or more plotting functions can be applied to each subset by calling + :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe`. Finally, the + plot can be tweaked with other methods to do things like change the + axis labels, use different ticks, or add a legend. See the detailed + code examples below for more information. + + .. warning:: + + When using seaborn functions that infer semantic mappings from a + dataset, care must be taken to synchronize those mappings across + facets (e.g., by defining the ``hue`` mapping with a palette dict or + setting the data type of the variables to ``category``). In most cases, + it will be better to use a figure-level function (e.g. :func:`relplot` + or :func:`catplot`) than to use :class:`FacetGrid` directly. + + See the :ref:`tutorial ` for more information. + + Parameters + ---------- + {data} + row, col, hue : strings + Variables that define subsets of the data, which will be drawn on + separate facets in the grid. See the ``{{var}}_order`` parameters to + control the order of levels of this variable. + {col_wrap} + {share_xy} + {height} + {aspect} + {palette} + {{row,col,hue}}_order : lists + Order for the levels of the faceting variables. By default, this + will be the order that the levels appear in ``data`` or, if the + variables are pandas categoricals, the category order. + hue_kws : dictionary of param -> list of values mapping + Other keyword arguments to insert into the plotting call to let + other plot attributes vary across levels of the hue variable (e.g. + the markers in a scatterplot). + {legend_out} + despine : boolean + Remove the top and right spines from the plots. + {margin_titles} + {{x, y}}lim: tuples + Limits for each of the axes on each facet (only relevant when + share{{x, y}} is True). + subplot_kws : dict + Dictionary of keyword arguments passed to matplotlib subplot(s) + methods. + gridspec_kws : dict + Dictionary of keyword arguments passed to + :class:`matplotlib.gridspec.GridSpec` + (via :meth:`matplotlib.figure.Figure.subplots`). + Ignored if ``col_wrap`` is not ``None``. + + See Also + -------- + PairGrid : Subplot grid for plotting pairwise relationships + relplot : Combine a relational plot and a :class:`FacetGrid` + displot : Combine a distribution plot and a :class:`FacetGrid` + catplot : Combine a categorical plot and a :class:`FacetGrid` + lmplot : Combine a regression plot and a :class:`FacetGrid` + + Examples + -------- + + .. note:: + + These examples use seaborn functions to demonstrate some of the + advanced features of the class, but in most cases you will want + to use figue-level functions (e.g. :func:`displot`, :func:`relplot`) + to make the plots shown here. + + .. include:: ../docstrings/FacetGrid.rst + + """).format(**_facet_docs) + + def facet_data(self): + """Generator for name indices and data subsets for each facet. + + Yields + ------ + (i, j, k), data_ijk : tuple of ints, DataFrame + The ints provide an index into the {row, col, hue}_names attribute, + and the dataframe contains a subset of the full data corresponding + to each facet. The generator yields subsets that correspond with + the self.axes.flat iterator, or self.axes[i, j] when `col_wrap` + is None. + + """ + data = self.data + + # Construct masks for the row variable + if self.row_names: + row_masks = [data[self._row_var] == n for n in self.row_names] + else: + row_masks = [np.repeat(True, len(self.data))] + + # Construct masks for the column variable + if self.col_names: + col_masks = [data[self._col_var] == n for n in self.col_names] + else: + col_masks = [np.repeat(True, len(self.data))] + + # Construct masks for the hue variable + if self.hue_names: + hue_masks = [data[self._hue_var] == n for n in self.hue_names] + else: + hue_masks = [np.repeat(True, len(self.data))] + + # Here is the main generator loop + for (i, row), (j, col), (k, hue) in product(enumerate(row_masks), + enumerate(col_masks), + enumerate(hue_masks)): + data_ijk = data[row & col & hue & self._not_na] + yield (i, j, k), data_ijk + + def map(self, func, *args, **kwargs): + """Apply a plotting function to each facet's subset of the data. + + Parameters + ---------- + func : callable + A plotting function that takes data and keyword arguments. It + must plot to the currently active matplotlib Axes and take a + `color` keyword argument. If faceting on the `hue` dimension, + it must also take a `label` keyword argument. + args : strings + Column names in self.data that identify variables with data to + plot. The data for each variable is passed to `func` in the + order the variables are specified in the call. + kwargs : keyword arguments + All keyword arguments are passed to the plotting function. + + Returns + ------- + self : object + Returns self. + + """ + # If color was a keyword argument, grab it here + kw_color = kwargs.pop("color", None) + + # How we use the function depends on where it comes from + func_module = str(getattr(func, "__module__", "")) + + # Check for categorical plots without order information + if func_module == "seaborn.categorical": + if "order" not in kwargs: + warning = ("Using the {} function without specifying " + "`order` is likely to produce an incorrect " + "plot.".format(func.__name__)) + warnings.warn(warning) + if len(args) == 3 and "hue_order" not in kwargs: + warning = ("Using the {} function without specifying " + "`hue_order` is likely to produce an incorrect " + "plot.".format(func.__name__)) + warnings.warn(warning) + + # Iterate over the data subsets + for (row_i, col_j, hue_k), data_ijk in self.facet_data(): + + # If this subset is null, move on + if not data_ijk.values.size: + continue + + # Get the current axis + modify_state = not func_module.startswith("seaborn") + ax = self.facet_axis(row_i, col_j, modify_state) + + # Decide what color to plot with + kwargs["color"] = self._facet_color(hue_k, kw_color) + + # Insert the other hue aesthetics if appropriate + for kw, val_list in self.hue_kws.items(): + kwargs[kw] = val_list[hue_k] + + # Insert a label in the keyword arguments for the legend + if self._hue_var is not None: + kwargs["label"] = utils.to_utf8(self.hue_names[hue_k]) + + # Get the actual data we are going to plot with + plot_data = data_ijk[list(args)] + if self._dropna: + plot_data = plot_data.dropna() + plot_args = [v for k, v in plot_data.items()] + + # Some matplotlib functions don't handle pandas objects correctly + if func_module.startswith("matplotlib"): + plot_args = [v.values for v in plot_args] + + # Draw the plot + self._facet_plot(func, ax, plot_args, kwargs) + + # Finalize the annotations and layout + self._finalize_grid(args[:2]) + + return self + + def map_dataframe(self, func, *args, **kwargs): + """Like ``.map`` but passes args as strings and inserts data in kwargs. + + This method is suitable for plotting with functions that accept a + long-form DataFrame as a `data` keyword argument and access the + data in that DataFrame using string variable names. + + Parameters + ---------- + func : callable + A plotting function that takes data and keyword arguments. Unlike + the `map` method, a function used here must "understand" Pandas + objects. It also must plot to the currently active matplotlib Axes + and take a `color` keyword argument. If faceting on the `hue` + dimension, it must also take a `label` keyword argument. + args : strings + Column names in self.data that identify variables with data to + plot. The data for each variable is passed to `func` in the + order the variables are specified in the call. + kwargs : keyword arguments + All keyword arguments are passed to the plotting function. + + Returns + ------- + self : object + Returns self. + + """ + + # If color was a keyword argument, grab it here + kw_color = kwargs.pop("color", None) + + # Iterate over the data subsets + for (row_i, col_j, hue_k), data_ijk in self.facet_data(): + + # If this subset is null, move on + if not data_ijk.values.size: + continue + + # Get the current axis + modify_state = not str(func.__module__).startswith("seaborn") + ax = self.facet_axis(row_i, col_j, modify_state) + + # Decide what color to plot with + kwargs["color"] = self._facet_color(hue_k, kw_color) + + # Insert the other hue aesthetics if appropriate + for kw, val_list in self.hue_kws.items(): + kwargs[kw] = val_list[hue_k] + + # Insert a label in the keyword arguments for the legend + if self._hue_var is not None: + kwargs["label"] = self.hue_names[hue_k] + + # Stick the facet dataframe into the kwargs + if self._dropna: + data_ijk = data_ijk.dropna() + kwargs["data"] = data_ijk + + # Draw the plot + self._facet_plot(func, ax, args, kwargs) + + # For axis labels, prefer to use positional args for backcompat + # but also extract the x/y kwargs and use if no corresponding arg + axis_labels = [kwargs.get("x", None), kwargs.get("y", None)] + for i, val in enumerate(args[:2]): + axis_labels[i] = val + self._finalize_grid(axis_labels) + + return self + + def _facet_color(self, hue_index, kw_color): + + color = self._colors[hue_index] + if kw_color is not None: + return kw_color + elif color is not None: + return color + + def _facet_plot(self, func, ax, plot_args, plot_kwargs): + + # Draw the plot + if str(func.__module__).startswith("seaborn"): + plot_kwargs = plot_kwargs.copy() + semantics = ["x", "y", "hue", "size", "style"] + for key, val in zip(semantics, plot_args): + plot_kwargs[key] = val + plot_args = [] + plot_kwargs["ax"] = ax + func(*plot_args, **plot_kwargs) + + # Sort out the supporting information + self._update_legend_data(ax) + + def _finalize_grid(self, axlabels): + """Finalize the annotations and layout.""" + self.set_axis_labels(*axlabels) + self.tight_layout() + + def facet_axis(self, row_i, col_j, modify_state=True): + """Make the axis identified by these indices active and return it.""" + + # Calculate the actual indices of the axes to plot on + if self._col_wrap is not None: + ax = self.axes.flat[col_j] + else: + ax = self.axes[row_i, col_j] + + # Get a reference to the axes object we want, and make it active + if modify_state: + plt.sca(ax) + return ax + + def despine(self, **kwargs): + """Remove axis spines from the facets.""" + utils.despine(self._figure, **kwargs) + return self + + def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs): + """Set axis labels on the left column and bottom row of the grid.""" + if x_var is not None: + self._x_var = x_var + self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs) + if y_var is not None: + self._y_var = y_var + self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs) + + return self + + def set_xlabels(self, label=None, clear_inner=True, **kwargs): + """Label the x axis on the bottom row of the grid.""" + if label is None: + label = self._x_var + for ax in self._bottom_axes: + ax.set_xlabel(label, **kwargs) + if clear_inner: + for ax in self._not_bottom_axes: + ax.set_xlabel("") + return self + + def set_ylabels(self, label=None, clear_inner=True, **kwargs): + """Label the y axis on the left column of the grid.""" + if label is None: + label = self._y_var + for ax in self._left_axes: + ax.set_ylabel(label, **kwargs) + if clear_inner: + for ax in self._not_left_axes: + ax.set_ylabel("") + return self + + def set_xticklabels(self, labels=None, step=None, **kwargs): + """Set x axis tick labels of the grid.""" + for ax in self.axes.flat: + curr_ticks = ax.get_xticks() + ax.set_xticks(curr_ticks) + if labels is None: + curr_labels = [l.get_text() for l in ax.get_xticklabels()] + if step is not None: + xticks = ax.get_xticks()[::step] + curr_labels = curr_labels[::step] + ax.set_xticks(xticks) + ax.set_xticklabels(curr_labels, **kwargs) + else: + ax.set_xticklabels(labels, **kwargs) + return self + + def set_yticklabels(self, labels=None, **kwargs): + """Set y axis tick labels on the left column of the grid.""" + for ax in self.axes.flat: + curr_ticks = ax.get_yticks() + ax.set_yticks(curr_ticks) + if labels is None: + curr_labels = [l.get_text() for l in ax.get_yticklabels()] + ax.set_yticklabels(curr_labels, **kwargs) + else: + ax.set_yticklabels(labels, **kwargs) + return self + + def set_titles(self, template=None, row_template=None, col_template=None, + **kwargs): + """Draw titles either above each facet or on the grid margins. + + Parameters + ---------- + template : string + Template for all titles with the formatting keys {col_var} and + {col_name} (if using a `col` faceting variable) and/or {row_var} + and {row_name} (if using a `row` faceting variable). + row_template: + Template for the row variable when titles are drawn on the grid + margins. Must have {row_var} and {row_name} formatting keys. + col_template: + Template for the column variable when titles are drawn on the grid + margins. Must have {col_var} and {col_name} formatting keys. + + Returns + ------- + self: object + Returns self. + + """ + args = dict(row_var=self._row_var, col_var=self._col_var) + kwargs["size"] = kwargs.pop("size", mpl.rcParams["axes.labelsize"]) + + # Establish default templates + if row_template is None: + row_template = "{row_var} = {row_name}" + if col_template is None: + col_template = "{col_var} = {col_name}" + if template is None: + if self._row_var is None: + template = col_template + elif self._col_var is None: + template = row_template + else: + template = " | ".join([row_template, col_template]) + + row_template = utils.to_utf8(row_template) + col_template = utils.to_utf8(col_template) + template = utils.to_utf8(template) + + if self._margin_titles: + + # Remove any existing title texts + for text in self._margin_titles_texts: + text.remove() + self._margin_titles_texts = [] + + if self.row_names is not None: + # Draw the row titles on the right edge of the grid + for i, row_name in enumerate(self.row_names): + ax = self.axes[i, -1] + args.update(dict(row_name=row_name)) + title = row_template.format(**args) + text = ax.annotate( + title, xy=(1.02, .5), xycoords="axes fraction", + rotation=270, ha="left", va="center", + **kwargs + ) + self._margin_titles_texts.append(text) + + if self.col_names is not None: + # Draw the column titles as normal titles + for j, col_name in enumerate(self.col_names): + args.update(dict(col_name=col_name)) + title = col_template.format(**args) + self.axes[0, j].set_title(title, **kwargs) + + return self + + # Otherwise title each facet with all the necessary information + if (self._row_var is not None) and (self._col_var is not None): + for i, row_name in enumerate(self.row_names): + for j, col_name in enumerate(self.col_names): + args.update(dict(row_name=row_name, col_name=col_name)) + title = template.format(**args) + self.axes[i, j].set_title(title, **kwargs) + elif self.row_names is not None and len(self.row_names): + for i, row_name in enumerate(self.row_names): + args.update(dict(row_name=row_name)) + title = template.format(**args) + self.axes[i, 0].set_title(title, **kwargs) + elif self.col_names is not None and len(self.col_names): + for i, col_name in enumerate(self.col_names): + args.update(dict(col_name=col_name)) + title = template.format(**args) + # Index the flat array so col_wrap works + self.axes.flat[i].set_title(title, **kwargs) + return self + + def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws): + """Add a reference line(s) to each facet. + + Parameters + ---------- + x, y : numeric + Value(s) to draw the line(s) at. + color : :mod:`matplotlib color ` + Specifies the color of the reference line(s). Pass ``color=None`` to + use ``hue`` mapping. + linestyle : str + Specifies the style of the reference line(s). + line_kws : key, value mappings + Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` + when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` + is not None. + + Returns + ------- + :class:`FacetGrid` instance + Returns ``self`` for easy method chaining. + + """ + line_kws['color'] = color + line_kws['linestyle'] = linestyle + + if x is not None: + self.map(plt.axvline, x=x, **line_kws) + + if y is not None: + self.map(plt.axhline, y=y, **line_kws) + + return self + + # ------ Properties that are part of the public API and documented by Sphinx + + @property + def axes(self): + """An array of the :class:`matplotlib.axes.Axes` objects in the grid.""" + return self._axes + + @property + def ax(self): + """The :class:`matplotlib.axes.Axes` when no faceting variables are assigned.""" + if self.axes.shape == (1, 1): + return self.axes[0, 0] + else: + err = ( + "Use the `.axes` attribute when facet variables are assigned." + ) + raise AttributeError(err) + + @property + def axes_dict(self): + """A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`. + + If only one of ``row`` or ``col`` is assigned, each key is a string + representing a level of that variable. If both facet dimensions are + assigned, each key is a ``({row_level}, {col_level})`` tuple. + + """ + return self._axes_dict + + # ------ Private properties, that require some computation to get + + @property + def _inner_axes(self): + """Return a flat array of the inner axes.""" + if self._col_wrap is None: + return self.axes[:-1, 1:].flat + else: + axes = [] + n_empty = self._nrow * self._ncol - self._n_facets + for i, ax in enumerate(self.axes): + append = ( + i % self._ncol + and i < (self._ncol * (self._nrow - 1)) + and i < (self._ncol * (self._nrow - 1) - n_empty) + ) + if append: + axes.append(ax) + return np.array(axes, object).flat + + @property + def _left_axes(self): + """Return a flat array of the left column of axes.""" + if self._col_wrap is None: + return self.axes[:, 0].flat + else: + axes = [] + for i, ax in enumerate(self.axes): + if not i % self._ncol: + axes.append(ax) + return np.array(axes, object).flat + + @property + def _not_left_axes(self): + """Return a flat array of axes that aren't on the left column.""" + if self._col_wrap is None: + return self.axes[:, 1:].flat + else: + axes = [] + for i, ax in enumerate(self.axes): + if i % self._ncol: + axes.append(ax) + return np.array(axes, object).flat + + @property + def _bottom_axes(self): + """Return a flat array of the bottom row of axes.""" + if self._col_wrap is None: + return self.axes[-1, :].flat + else: + axes = [] + n_empty = self._nrow * self._ncol - self._n_facets + for i, ax in enumerate(self.axes): + append = ( + i >= (self._ncol * (self._nrow - 1)) + or i >= (self._ncol * (self._nrow - 1) - n_empty) + ) + if append: + axes.append(ax) + return np.array(axes, object).flat + + @property + def _not_bottom_axes(self): + """Return a flat array of axes that aren't on the bottom row.""" + if self._col_wrap is None: + return self.axes[:-1, :].flat + else: + axes = [] + n_empty = self._nrow * self._ncol - self._n_facets + for i, ax in enumerate(self.axes): + append = ( + i < (self._ncol * (self._nrow - 1)) + and i < (self._ncol * (self._nrow - 1) - n_empty) + ) + if append: + axes.append(ax) + return np.array(axes, object).flat + + +class PairGrid(Grid): + """Subplot grid for plotting pairwise relationships in a dataset. + + This object maps each variable in a dataset onto a column and row in a + grid of multiple axes. Different axes-level plotting functions can be + used to draw bivariate plots in the upper and lower triangles, and the + marginal distribution of each variable can be shown on the diagonal. + + Several different common plots can be generated in a single line using + :func:`pairplot`. Use :class:`PairGrid` when you need more flexibility. + + See the :ref:`tutorial ` for more information. + + """ + def __init__( + self, data, *, hue=None, vars=None, x_vars=None, y_vars=None, + hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True, + height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False, + ): + """Initialize the plot figure and PairGrid object. + + Parameters + ---------- + data : DataFrame + Tidy (long-form) dataframe where each column is a variable and + each row is an observation. + hue : string (variable name) + Variable in ``data`` to map plot aspects to different colors. This + variable will be excluded from the default x and y variables. + vars : list of variable names + Variables within ``data`` to use, otherwise use every column with + a numeric datatype. + {x, y}_vars : lists of variable names + Variables within ``data`` to use separately for the rows and + columns of the figure; i.e. to make a non-square plot. + hue_order : list of strings + Order for the levels of the hue variable in the palette + palette : dict or seaborn color palette + Set of colors for mapping the ``hue`` variable. If a dict, keys + should be values in the ``hue`` variable. + hue_kws : dictionary of param -> list of values mapping + Other keyword arguments to insert into the plotting call to let + other plot attributes vary across levels of the hue variable (e.g. + the markers in a scatterplot). + corner : bool + If True, don't add axes to the upper (off-diagonal) triangle of the + grid, making this a "corner" plot. + height : scalar + Height (in inches) of each facet. + aspect : scalar + Aspect * height gives the width (in inches) of each facet. + layout_pad : scalar + Padding between axes; passed to ``fig.tight_layout``. + despine : boolean + Remove the top and right spines from the plots. + dropna : boolean + Drop missing values from the data before plotting. + + See Also + -------- + pairplot : Easily drawing common uses of :class:`PairGrid`. + FacetGrid : Subplot grid for plotting conditional relationships. + + Examples + -------- + + .. include:: ../docstrings/PairGrid.rst + + """ + + super().__init__() + + # Sort out the variables that define the grid + numeric_cols = self._find_numeric_cols(data) + if hue in numeric_cols: + numeric_cols.remove(hue) + if vars is not None: + x_vars = list(vars) + y_vars = list(vars) + if x_vars is None: + x_vars = numeric_cols + if y_vars is None: + y_vars = numeric_cols + + if np.isscalar(x_vars): + x_vars = [x_vars] + if np.isscalar(y_vars): + y_vars = [y_vars] + + self.x_vars = x_vars = list(x_vars) + self.y_vars = y_vars = list(y_vars) + self.square_grid = self.x_vars == self.y_vars + + if not x_vars: + raise ValueError("No variables found for grid columns.") + if not y_vars: + raise ValueError("No variables found for grid rows.") + + # Create the figure and the array of subplots + figsize = len(x_vars) * height * aspect, len(y_vars) * height + + with _disable_autolayout(): + fig = plt.figure(figsize=figsize) + + axes = fig.subplots(len(y_vars), len(x_vars), + sharex="col", sharey="row", + squeeze=False) + + # Possibly remove upper axes to make a corner grid + # Note: setting up the axes is usually the most time-intensive part + # of using the PairGrid. We are foregoing the speed improvement that + # we would get by just not setting up the hidden axes so that we can + # avoid implementing fig.subplots ourselves. But worth thinking about. + self._corner = corner + if corner: + hide_indices = np.triu_indices_from(axes, 1) + for i, j in zip(*hide_indices): + axes[i, j].remove() + axes[i, j] = None + + self._figure = fig + self.axes = axes + self.data = data + + # Save what we are going to do with the diagonal + self.diag_sharey = diag_sharey + self.diag_vars = None + self.diag_axes = None + + self._dropna = dropna + + # Label the axes + self._add_axis_labels() + + # Sort out the hue variable + self._hue_var = hue + if hue is None: + self.hue_names = hue_order = ["_nolegend_"] + self.hue_vals = pd.Series(["_nolegend_"] * len(data), + index=data.index) + else: + # We need hue_order and hue_names because the former is used to control + # the order of drawing and the latter is used to control the order of + # the legend. hue_names can become string-typed while hue_order must + # retain the type of the input data. This is messy but results from + # the fact that PairGrid can implement the hue-mapping logic itself + # (and was originally written exclusively that way) but now can delegate + # to the axes-level functions, while always handling legend creation. + # See GH2307 + hue_names = hue_order = categorical_order(data[hue], hue_order) + if dropna: + # Filter NA from the list of unique hue names + hue_names = list(filter(pd.notnull, hue_names)) + self.hue_names = hue_names + self.hue_vals = data[hue] + + # Additional dict of kwarg -> list of values for mapping the hue var + self.hue_kws = hue_kws if hue_kws is not None else {} + + self._orig_palette = palette + self._hue_order = hue_order + self.palette = self._get_palette(data, hue, hue_order, palette) + self._legend_data = {} + + # Make the plot look nice + for ax in axes[:-1, :].flat: + if ax is None: + continue + for label in ax.get_xticklabels(): + label.set_visible(False) + ax.xaxis.offsetText.set_visible(False) + ax.xaxis.label.set_visible(False) + + for ax in axes[:, 1:].flat: + if ax is None: + continue + for label in ax.get_yticklabels(): + label.set_visible(False) + ax.yaxis.offsetText.set_visible(False) + ax.yaxis.label.set_visible(False) + + self._tight_layout_rect = [.01, .01, .99, .99] + self._tight_layout_pad = layout_pad + self._despine = despine + if despine: + utils.despine(fig=fig) + self.tight_layout(pad=layout_pad) + + def map(self, func, **kwargs): + """Plot with the same function in every subplot. + + Parameters + ---------- + func : callable plotting function + Must take x, y arrays as positional arguments and draw onto the + "currently active" matplotlib Axes. Also needs to accept kwargs + called ``color`` and ``label``. + + """ + row_indices, col_indices = np.indices(self.axes.shape) + indices = zip(row_indices.flat, col_indices.flat) + self._map_bivariate(func, indices, **kwargs) + + return self + + def map_lower(self, func, **kwargs): + """Plot with a bivariate function on the lower diagonal subplots. + + Parameters + ---------- + func : callable plotting function + Must take x, y arrays as positional arguments and draw onto the + "currently active" matplotlib Axes. Also needs to accept kwargs + called ``color`` and ``label``. + + """ + indices = zip(*np.tril_indices_from(self.axes, -1)) + self._map_bivariate(func, indices, **kwargs) + return self + + def map_upper(self, func, **kwargs): + """Plot with a bivariate function on the upper diagonal subplots. + + Parameters + ---------- + func : callable plotting function + Must take x, y arrays as positional arguments and draw onto the + "currently active" matplotlib Axes. Also needs to accept kwargs + called ``color`` and ``label``. + + """ + indices = zip(*np.triu_indices_from(self.axes, 1)) + self._map_bivariate(func, indices, **kwargs) + return self + + def map_offdiag(self, func, **kwargs): + """Plot with a bivariate function on the off-diagonal subplots. + + Parameters + ---------- + func : callable plotting function + Must take x, y arrays as positional arguments and draw onto the + "currently active" matplotlib Axes. Also needs to accept kwargs + called ``color`` and ``label``. + + """ + if self.square_grid: + self.map_lower(func, **kwargs) + if not self._corner: + self.map_upper(func, **kwargs) + else: + indices = [] + for i, (y_var) in enumerate(self.y_vars): + for j, (x_var) in enumerate(self.x_vars): + if x_var != y_var: + indices.append((i, j)) + self._map_bivariate(func, indices, **kwargs) + return self + + def map_diag(self, func, **kwargs): + """Plot with a univariate function on each diagonal subplot. + + Parameters + ---------- + func : callable plotting function + Must take an x array as a positional argument and draw onto the + "currently active" matplotlib Axes. Also needs to accept kwargs + called ``color`` and ``label``. + + """ + # Add special diagonal axes for the univariate plot + if self.diag_axes is None: + diag_vars = [] + diag_axes = [] + for i, y_var in enumerate(self.y_vars): + for j, x_var in enumerate(self.x_vars): + if x_var == y_var: + + # Make the density axes + diag_vars.append(x_var) + ax = self.axes[i, j] + diag_ax = ax.twinx() + diag_ax.set_axis_off() + diag_axes.append(diag_ax) + + # Work around matplotlib bug + # https://github.com/matplotlib/matplotlib/issues/15188 + if not plt.rcParams.get("ytick.left", True): + for tick in ax.yaxis.majorTicks: + tick.tick1line.set_visible(False) + + # Remove main y axis from density axes in a corner plot + if self._corner: + ax.yaxis.set_visible(False) + if self._despine: + utils.despine(ax=ax, left=True) + # TODO add optional density ticks (on the right) + # when drawing a corner plot? + + if self.diag_sharey and diag_axes: + for ax in diag_axes[1:]: + share_axis(diag_axes[0], ax, "y") + + self.diag_vars = np.array(diag_vars, np.object_) + self.diag_axes = np.array(diag_axes, np.object_) + + if "hue" not in signature(func).parameters: + return self._map_diag_iter_hue(func, **kwargs) + + # Loop over diagonal variables and axes, making one plot in each + for var, ax in zip(self.diag_vars, self.diag_axes): + + plot_kwargs = kwargs.copy() + if str(func.__module__).startswith("seaborn"): + plot_kwargs["ax"] = ax + else: + plt.sca(ax) + + vector = self.data[var] + if self._hue_var is not None: + hue = self.data[self._hue_var] + else: + hue = None + + if self._dropna: + not_na = vector.notna() + if hue is not None: + not_na &= hue.notna() + vector = vector[not_na] + if hue is not None: + hue = hue[not_na] + + plot_kwargs.setdefault("hue", hue) + plot_kwargs.setdefault("hue_order", self._hue_order) + plot_kwargs.setdefault("palette", self._orig_palette) + func(x=vector, **plot_kwargs) + ax.legend_ = None + + self._add_axis_labels() + return self + + def _map_diag_iter_hue(self, func, **kwargs): + """Put marginal plot on each diagonal axes, iterating over hue.""" + # Plot on each of the diagonal axes + fixed_color = kwargs.pop("color", None) + + for var, ax in zip(self.diag_vars, self.diag_axes): + hue_grouped = self.data[var].groupby(self.hue_vals) + + plot_kwargs = kwargs.copy() + if str(func.__module__).startswith("seaborn"): + plot_kwargs["ax"] = ax + else: + plt.sca(ax) + + for k, label_k in enumerate(self._hue_order): + + # Attempt to get data for this level, allowing for empty + try: + data_k = hue_grouped.get_group(label_k) + except KeyError: + data_k = pd.Series([], dtype=float) + + if fixed_color is None: + color = self.palette[k] + else: + color = fixed_color + + if self._dropna: + data_k = utils.remove_na(data_k) + + if str(func.__module__).startswith("seaborn"): + func(x=data_k, label=label_k, color=color, **plot_kwargs) + else: + func(data_k, label=label_k, color=color, **plot_kwargs) + + self._add_axis_labels() + + return self + + def _map_bivariate(self, func, indices, **kwargs): + """Draw a bivariate plot on the indicated axes.""" + # This is a hack to handle the fact that new distribution plots don't add + # their artists onto the axes. This is probably superior in general, but + # we'll need a better way to handle it in the axisgrid functions. + from .distributions import histplot, kdeplot + if func is histplot or func is kdeplot: + self._extract_legend_handles = True + + kws = kwargs.copy() # Use copy as we insert other kwargs + for i, j in indices: + x_var = self.x_vars[j] + y_var = self.y_vars[i] + ax = self.axes[i, j] + if ax is None: # i.e. we are in corner mode + continue + self._plot_bivariate(x_var, y_var, ax, func, **kws) + self._add_axis_labels() + + if "hue" in signature(func).parameters: + self.hue_names = list(self._legend_data) + + def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs): + """Draw a bivariate plot on the specified axes.""" + if "hue" not in signature(func).parameters: + self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs) + return + + kwargs = kwargs.copy() + if str(func.__module__).startswith("seaborn"): + kwargs["ax"] = ax + else: + plt.sca(ax) + + if x_var == y_var: + axes_vars = [x_var] + else: + axes_vars = [x_var, y_var] + + if self._hue_var is not None and self._hue_var not in axes_vars: + axes_vars.append(self._hue_var) + + data = self.data[axes_vars] + if self._dropna: + data = data.dropna() + + x = data[x_var] + y = data[y_var] + if self._hue_var is None: + hue = None + else: + hue = data.get(self._hue_var) + + if "hue" not in kwargs: + kwargs.update({ + "hue": hue, "hue_order": self._hue_order, "palette": self._orig_palette, + }) + func(x=x, y=y, **kwargs) + + self._update_legend_data(ax) + + def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs): + """Draw a bivariate plot while iterating over hue subsets.""" + kwargs = kwargs.copy() + if str(func.__module__).startswith("seaborn"): + kwargs["ax"] = ax + else: + plt.sca(ax) + + if x_var == y_var: + axes_vars = [x_var] + else: + axes_vars = [x_var, y_var] + + hue_grouped = self.data.groupby(self.hue_vals) + for k, label_k in enumerate(self._hue_order): + + kws = kwargs.copy() + + # Attempt to get data for this level, allowing for empty + try: + data_k = hue_grouped.get_group(label_k) + except KeyError: + data_k = pd.DataFrame(columns=axes_vars, + dtype=float) + + if self._dropna: + data_k = data_k[axes_vars].dropna() + + x = data_k[x_var] + y = data_k[y_var] + + for kw, val_list in self.hue_kws.items(): + kws[kw] = val_list[k] + kws.setdefault("color", self.palette[k]) + if self._hue_var is not None: + kws["label"] = label_k + + if str(func.__module__).startswith("seaborn"): + func(x=x, y=y, **kws) + else: + func(x, y, **kws) + + self._update_legend_data(ax) + + def _add_axis_labels(self): + """Add labels to the left and bottom Axes.""" + for ax, label in zip(self.axes[-1, :], self.x_vars): + ax.set_xlabel(label) + for ax, label in zip(self.axes[:, 0], self.y_vars): + ax.set_ylabel(label) + + def _find_numeric_cols(self, data): + """Find which variables in a DataFrame are numeric.""" + numeric_cols = [] + for col in data: + if variable_type(data[col]) == "numeric": + numeric_cols.append(col) + return numeric_cols + + +class JointGrid(_BaseGrid): + """Grid for drawing a bivariate plot with marginal univariate plots. + + Many plots can be drawn by using the figure-level interface :func:`jointplot`. + Use this class directly when you need more flexibility. + + """ + + def __init__( + self, data=None, *, + x=None, y=None, hue=None, + height=6, ratio=5, space=.2, + palette=None, hue_order=None, hue_norm=None, + dropna=False, xlim=None, ylim=None, marginal_ticks=False, + ): + + # Set up the subplot grid + f = plt.figure(figsize=(height, height)) + gs = plt.GridSpec(ratio + 1, ratio + 1) + + ax_joint = f.add_subplot(gs[1:, :-1]) + ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint) + ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint) + + self._figure = f + self.ax_joint = ax_joint + self.ax_marg_x = ax_marg_x + self.ax_marg_y = ax_marg_y + + # Turn off tick visibility for the measure axis on the marginal plots + plt.setp(ax_marg_x.get_xticklabels(), visible=False) + plt.setp(ax_marg_y.get_yticklabels(), visible=False) + plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False) + plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False) + + # Turn off the ticks on the density axis for the marginal plots + if not marginal_ticks: + plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False) + plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False) + plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False) + plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False) + plt.setp(ax_marg_x.get_yticklabels(), visible=False) + plt.setp(ax_marg_y.get_xticklabels(), visible=False) + plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False) + plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False) + ax_marg_x.yaxis.grid(False) + ax_marg_y.xaxis.grid(False) + + # Process the input variables + p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue)) + plot_data = p.plot_data.loc[:, p.plot_data.notna().any()] + + # Possibly drop NA + if dropna: + plot_data = plot_data.dropna() + + def get_var(var): + vector = plot_data.get(var, None) + if vector is not None: + vector = vector.rename(p.variables.get(var, None)) + return vector + + self.x = get_var("x") + self.y = get_var("y") + self.hue = get_var("hue") + + for axis in "xy": + name = p.variables.get(axis, None) + if name is not None: + getattr(ax_joint, f"set_{axis}label")(name) + + if xlim is not None: + ax_joint.set_xlim(xlim) + if ylim is not None: + ax_joint.set_ylim(ylim) + + # Store the semantic mapping parameters for axes-level functions + self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm) + + # Make the grid look nice + utils.despine(f) + if not marginal_ticks: + utils.despine(ax=ax_marg_x, left=True) + utils.despine(ax=ax_marg_y, bottom=True) + for axes in [ax_marg_x, ax_marg_y]: + for axis in [axes.xaxis, axes.yaxis]: + axis.label.set_visible(False) + f.tight_layout() + f.subplots_adjust(hspace=space, wspace=space) + + def _inject_kwargs(self, func, kws, params): + """Add params to kws if they are accepted by func.""" + func_params = signature(func).parameters + for key, val in params.items(): + if key in func_params: + kws.setdefault(key, val) + + def plot(self, joint_func, marginal_func, **kwargs): + """Draw the plot by passing functions for joint and marginal axes. + + This method passes the ``kwargs`` dictionary to both functions. If you + need more control, call :meth:`JointGrid.plot_joint` and + :meth:`JointGrid.plot_marginals` directly with specific parameters. + + Parameters + ---------- + joint_func, marginal_func : callables + Functions to draw the bivariate and univariate plots. See methods + referenced above for information about the required characteristics + of these functions. + kwargs + Additional keyword arguments are passed to both functions. + + Returns + ------- + :class:`JointGrid` instance + Returns ``self`` for easy method chaining. + + """ + self.plot_marginals(marginal_func, **kwargs) + self.plot_joint(joint_func, **kwargs) + return self + + def plot_joint(self, func, **kwargs): + """Draw a bivariate plot on the joint axes of the grid. + + Parameters + ---------- + func : plotting callable + If a seaborn function, it should accept ``x`` and ``y``. Otherwise, + it must accept ``x`` and ``y`` vectors of data as the first two + positional arguments, and it must plot on the "current" axes. + If ``hue`` was defined in the class constructor, the function must + accept ``hue`` as a parameter. + kwargs + Keyword argument are passed to the plotting function. + + Returns + ------- + :class:`JointGrid` instance + Returns ``self`` for easy method chaining. + + """ + kwargs = kwargs.copy() + if str(func.__module__).startswith("seaborn"): + kwargs["ax"] = self.ax_joint + else: + plt.sca(self.ax_joint) + if self.hue is not None: + kwargs["hue"] = self.hue + self._inject_kwargs(func, kwargs, self._hue_params) + + if str(func.__module__).startswith("seaborn"): + func(x=self.x, y=self.y, **kwargs) + else: + func(self.x, self.y, **kwargs) + + return self + + def plot_marginals(self, func, **kwargs): + """Draw univariate plots on each marginal axes. + + Parameters + ---------- + func : plotting callable + If a seaborn function, it should accept ``x`` and ``y`` and plot + when only one of them is defined. Otherwise, it must accept a vector + of data as the first positional argument and determine its orientation + using the ``vertical`` parameter, and it must plot on the "current" axes. + If ``hue`` was defined in the class constructor, it must accept ``hue`` + as a parameter. + kwargs + Keyword argument are passed to the plotting function. + + Returns + ------- + :class:`JointGrid` instance + Returns ``self`` for easy method chaining. + + """ + seaborn_func = ( + str(func.__module__).startswith("seaborn") + # deprecated distplot has a legacy API, special case it + and not func.__name__ == "distplot" + ) + func_params = signature(func).parameters + kwargs = kwargs.copy() + if self.hue is not None: + kwargs["hue"] = self.hue + self._inject_kwargs(func, kwargs, self._hue_params) + + if "legend" in func_params: + kwargs.setdefault("legend", False) + + if "orientation" in func_params: + # e.g. plt.hist + orient_kw_x = {"orientation": "vertical"} + orient_kw_y = {"orientation": "horizontal"} + elif "vertical" in func_params: + # e.g. sns.distplot (also how did this get backwards?) + orient_kw_x = {"vertical": False} + orient_kw_y = {"vertical": True} + + if seaborn_func: + func(x=self.x, ax=self.ax_marg_x, **kwargs) + else: + plt.sca(self.ax_marg_x) + func(self.x, **orient_kw_x, **kwargs) + + if seaborn_func: + func(y=self.y, ax=self.ax_marg_y, **kwargs) + else: + plt.sca(self.ax_marg_y) + func(self.y, **orient_kw_y, **kwargs) + + self.ax_marg_x.yaxis.get_label().set_visible(False) + self.ax_marg_y.xaxis.get_label().set_visible(False) + + return self + + def refline( + self, *, x=None, y=None, joint=True, marginal=True, + color='.5', linestyle='--', **line_kws + ): + """Add a reference line(s) to joint and/or marginal axes. + + Parameters + ---------- + x, y : numeric + Value(s) to draw the line(s) at. + joint, marginal : bools + Whether to add the reference line(s) to the joint/marginal axes. + color : :mod:`matplotlib color ` + Specifies the color of the reference line(s). + linestyle : str + Specifies the style of the reference line(s). + line_kws : key, value mappings + Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` + when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` + is not None. + + Returns + ------- + :class:`JointGrid` instance + Returns ``self`` for easy method chaining. + + """ + line_kws['color'] = color + line_kws['linestyle'] = linestyle + + if x is not None: + if joint: + self.ax_joint.axvline(x, **line_kws) + if marginal: + self.ax_marg_x.axvline(x, **line_kws) + + if y is not None: + if joint: + self.ax_joint.axhline(y, **line_kws) + if marginal: + self.ax_marg_y.axhline(y, **line_kws) + + return self + + def set_axis_labels(self, xlabel="", ylabel="", **kwargs): + """Set axis labels on the bivariate axes. + + Parameters + ---------- + xlabel, ylabel : strings + Label names for the x and y variables. + kwargs : key, value mappings + Other keyword arguments are passed to the following functions: + + - :meth:`matplotlib.axes.Axes.set_xlabel` + - :meth:`matplotlib.axes.Axes.set_ylabel` + + Returns + ------- + :class:`JointGrid` instance + Returns ``self`` for easy method chaining. + + """ + self.ax_joint.set_xlabel(xlabel, **kwargs) + self.ax_joint.set_ylabel(ylabel, **kwargs) + return self + + +JointGrid.__init__.__doc__ = """\ +Set up the grid of subplots and store data internally for easy plotting. + +Parameters +---------- +{params.core.data} +{params.core.xy} +height : number + Size of each side of the figure in inches (it will be square). +ratio : number + Ratio of joint axes height to marginal axes height. +space : number + Space between the joint and marginal axes +dropna : bool + If True, remove missing observations before plotting. +{{x, y}}lim : pairs of numbers + Set axis limits to these values before plotting. +marginal_ticks : bool + If False, suppress ticks on the count/density axis of the marginal plots. +{params.core.hue} + Note: unlike in :class:`FacetGrid` or :class:`PairGrid`, the axes-level + functions must support ``hue`` to use it in :class:`JointGrid`. +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} + +See Also +-------- +{seealso.jointplot} +{seealso.pairgrid} +{seealso.pairplot} + +Examples +-------- + +.. include:: ../docstrings/JointGrid.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +def pairplot( + data, *, + hue=None, hue_order=None, palette=None, + vars=None, x_vars=None, y_vars=None, + kind="scatter", diag_kind="auto", markers=None, + height=2.5, aspect=1, corner=False, dropna=False, + plot_kws=None, diag_kws=None, grid_kws=None, size=None, +): + """Plot pairwise relationships in a dataset. + + By default, this function will create a grid of Axes such that each numeric + variable in ``data`` will by shared across the y-axes across a single row and + the x-axes across a single column. The diagonal plots are treated + differently: a univariate distribution plot is drawn to show the marginal + distribution of the data in each column. + + It is also possible to show a subset of variables or plot different + variables on the rows and columns. + + This is a high-level interface for :class:`PairGrid` that is intended to + make it easy to draw a few common styles. You should use :class:`PairGrid` + directly if you need more flexibility. + + Parameters + ---------- + data : `pandas.DataFrame` + Tidy (long-form) dataframe where each column is a variable and + each row is an observation. + hue : name of variable in ``data`` + Variable in ``data`` to map plot aspects to different colors. + hue_order : list of strings + Order for the levels of the hue variable in the palette + palette : dict or seaborn color palette + Set of colors for mapping the ``hue`` variable. If a dict, keys + should be values in the ``hue`` variable. + vars : list of variable names + Variables within ``data`` to use, otherwise use every column with + a numeric datatype. + {x, y}_vars : lists of variable names + Variables within ``data`` to use separately for the rows and + columns of the figure; i.e. to make a non-square plot. + kind : {'scatter', 'kde', 'hist', 'reg'} + Kind of plot to make. + diag_kind : {'auto', 'hist', 'kde', None} + Kind of plot for the diagonal subplots. If 'auto', choose based on + whether or not ``hue`` is used. + markers : single matplotlib marker code or list + Either the marker to use for all scatterplot points or a list of markers + with a length the same as the number of levels in the hue variable so that + differently colored points will also have different scatterplot + markers. + height : scalar + Height (in inches) of each facet. + aspect : scalar + Aspect * height gives the width (in inches) of each facet. + corner : bool + If True, don't add axes to the upper (off-diagonal) triangle of the + grid, making this a "corner" plot. + dropna : boolean + Drop missing values from the data before plotting. + {plot, diag, grid}_kws : dicts + Dictionaries of keyword arguments. ``plot_kws`` are passed to the + bivariate plotting function, ``diag_kws`` are passed to the univariate + plotting function, and ``grid_kws`` are passed to the :class:`PairGrid` + constructor. + + Returns + ------- + grid : :class:`PairGrid` + Returns the underlying :class:`PairGrid` instance for further tweaking. + + See Also + -------- + PairGrid : Subplot grid for more flexible plotting of pairwise relationships. + JointGrid : Grid for plotting joint and marginal distributions of two variables. + + Examples + -------- + + .. include:: ../docstrings/pairplot.rst + + """ + # Avoid circular import + from .distributions import histplot, kdeplot + + # Handle deprecations + if size is not None: + height = size + msg = ("The `size` parameter has been renamed to `height`; " + "please update your code.") + warnings.warn(msg, UserWarning) + + if not isinstance(data, pd.DataFrame): + raise TypeError( + f"'data' must be pandas DataFrame object, not: {type(data)}") + + plot_kws = {} if plot_kws is None else plot_kws.copy() + diag_kws = {} if diag_kws is None else diag_kws.copy() + grid_kws = {} if grid_kws is None else grid_kws.copy() + + # Resolve "auto" diag kind + if diag_kind == "auto": + if hue is None: + diag_kind = "kde" if kind == "kde" else "hist" + else: + diag_kind = "hist" if kind == "hist" else "kde" + + # Set up the PairGrid + grid_kws.setdefault("diag_sharey", diag_kind == "hist") + grid = PairGrid(data, vars=vars, x_vars=x_vars, y_vars=y_vars, hue=hue, + hue_order=hue_order, palette=palette, corner=corner, + height=height, aspect=aspect, dropna=dropna, **grid_kws) + + # Add the markers here as PairGrid has figured out how many levels of the + # hue variable are needed and we don't want to duplicate that process + if markers is not None: + if kind == "reg": + # Needed until regplot supports style + if grid.hue_names is None: + n_markers = 1 + else: + n_markers = len(grid.hue_names) + if not isinstance(markers, list): + markers = [markers] * n_markers + if len(markers) != n_markers: + raise ValueError("markers must be a singleton or a list of " + "markers for each level of the hue variable") + grid.hue_kws = {"marker": markers} + elif kind == "scatter": + if isinstance(markers, str): + plot_kws["marker"] = markers + elif hue is not None: + plot_kws["style"] = data[hue] + plot_kws["markers"] = markers + + # Draw the marginal plots on the diagonal + diag_kws = diag_kws.copy() + diag_kws.setdefault("legend", False) + if diag_kind == "hist": + grid.map_diag(histplot, **diag_kws) + elif diag_kind == "kde": + diag_kws.setdefault("fill", True) + diag_kws.setdefault("warn_singular", False) + grid.map_diag(kdeplot, **diag_kws) + + # Maybe plot on the off-diagonals + if diag_kind is not None: + plotter = grid.map_offdiag + else: + plotter = grid.map + + if kind == "scatter": + from .relational import scatterplot # Avoid circular import + plotter(scatterplot, **plot_kws) + elif kind == "reg": + from .regression import regplot # Avoid circular import + plotter(regplot, **plot_kws) + elif kind == "kde": + from .distributions import kdeplot # Avoid circular import + plot_kws.setdefault("warn_singular", False) + plotter(kdeplot, **plot_kws) + elif kind == "hist": + from .distributions import histplot # Avoid circular import + plotter(histplot, **plot_kws) + + # Add a legend + if hue is not None: + grid.add_legend() + + grid.tight_layout() + + return grid + + +def jointplot( + data=None, *, x=None, y=None, hue=None, kind="scatter", + height=6, ratio=5, space=.2, dropna=False, xlim=None, ylim=None, + color=None, palette=None, hue_order=None, hue_norm=None, marginal_ticks=False, + joint_kws=None, marginal_kws=None, + **kwargs +): + # Avoid circular imports + from .relational import scatterplot + from .regression import regplot, residplot + from .distributions import histplot, kdeplot, _freedman_diaconis_bins + + if kwargs.pop("ax", None) is not None: + msg = "Ignoring `ax`; jointplot is a figure-level function." + warnings.warn(msg, UserWarning, stacklevel=2) + + # Set up empty default kwarg dicts + joint_kws = {} if joint_kws is None else joint_kws.copy() + joint_kws.update(kwargs) + marginal_kws = {} if marginal_kws is None else marginal_kws.copy() + + # Handle deprecations of distplot-specific kwargs + distplot_keys = [ + "rug", "fit", "hist_kws", "norm_hist" "hist_kws", "rug_kws", + ] + unused_keys = [] + for key in distplot_keys: + if key in marginal_kws: + unused_keys.append(key) + marginal_kws.pop(key) + if unused_keys and kind != "kde": + msg = ( + "The marginal plotting function has changed to `histplot`," + " which does not accept the following argument(s): {}." + ).format(", ".join(unused_keys)) + warnings.warn(msg, UserWarning) + + # Validate the plot kind + plot_kinds = ["scatter", "hist", "hex", "kde", "reg", "resid"] + _check_argument("kind", plot_kinds, kind) + + # Raise early if using `hue` with a kind that does not support it + if hue is not None and kind in ["hex", "reg", "resid"]: + msg = ( + f"Use of `hue` with `kind='{kind}'` is not currently supported." + ) + raise ValueError(msg) + + # Make a colormap based off the plot color + # (Currently used only for kind="hex") + if color is None: + color = "C0" + color_rgb = mpl.colors.colorConverter.to_rgb(color) + colors = [utils.set_hls_values(color_rgb, l=l) # noqa + for l in np.linspace(1, 0, 12)] + cmap = blend_palette(colors, as_cmap=True) + + # Matplotlib's hexbin plot is not na-robust + if kind == "hex": + dropna = True + + # Initialize the JointGrid object + grid = JointGrid( + data=data, x=x, y=y, hue=hue, + palette=palette, hue_order=hue_order, hue_norm=hue_norm, + dropna=dropna, height=height, ratio=ratio, space=space, + xlim=xlim, ylim=ylim, marginal_ticks=marginal_ticks, + ) + + if grid.hue is not None: + marginal_kws.setdefault("legend", False) + + # Plot the data using the grid + if kind.startswith("scatter"): + + joint_kws.setdefault("color", color) + grid.plot_joint(scatterplot, **joint_kws) + + if grid.hue is None: + marg_func = histplot + else: + marg_func = kdeplot + marginal_kws.setdefault("warn_singular", False) + marginal_kws.setdefault("fill", True) + + marginal_kws.setdefault("color", color) + grid.plot_marginals(marg_func, **marginal_kws) + + elif kind.startswith("hist"): + + # TODO process pair parameters for bins, etc. and pass + # to both joint and marginal plots + + joint_kws.setdefault("color", color) + grid.plot_joint(histplot, **joint_kws) + + marginal_kws.setdefault("kde", False) + marginal_kws.setdefault("color", color) + + marg_x_kws = marginal_kws.copy() + marg_y_kws = marginal_kws.copy() + + pair_keys = "bins", "binwidth", "binrange" + for key in pair_keys: + if isinstance(joint_kws.get(key), tuple): + x_val, y_val = joint_kws[key] + marg_x_kws.setdefault(key, x_val) + marg_y_kws.setdefault(key, y_val) + + histplot(data=data, x=x, hue=hue, **marg_x_kws, ax=grid.ax_marg_x) + histplot(data=data, y=y, hue=hue, **marg_y_kws, ax=grid.ax_marg_y) + + elif kind.startswith("kde"): + + joint_kws.setdefault("color", color) + joint_kws.setdefault("warn_singular", False) + grid.plot_joint(kdeplot, **joint_kws) + + marginal_kws.setdefault("color", color) + if "fill" in joint_kws: + marginal_kws.setdefault("fill", joint_kws["fill"]) + + grid.plot_marginals(kdeplot, **marginal_kws) + + elif kind.startswith("hex"): + + x_bins = min(_freedman_diaconis_bins(grid.x), 50) + y_bins = min(_freedman_diaconis_bins(grid.y), 50) + gridsize = int(np.mean([x_bins, y_bins])) + + joint_kws.setdefault("gridsize", gridsize) + joint_kws.setdefault("cmap", cmap) + grid.plot_joint(plt.hexbin, **joint_kws) + + marginal_kws.setdefault("kde", False) + marginal_kws.setdefault("color", color) + grid.plot_marginals(histplot, **marginal_kws) + + elif kind.startswith("reg"): + + marginal_kws.setdefault("color", color) + marginal_kws.setdefault("kde", True) + grid.plot_marginals(histplot, **marginal_kws) + + joint_kws.setdefault("color", color) + grid.plot_joint(regplot, **joint_kws) + + elif kind.startswith("resid"): + + joint_kws.setdefault("color", color) + grid.plot_joint(residplot, **joint_kws) + + x, y = grid.ax_joint.collections[0].get_offsets().T + marginal_kws.setdefault("color", color) + histplot(x=x, hue=hue, ax=grid.ax_marg_x, **marginal_kws) + histplot(y=y, hue=hue, ax=grid.ax_marg_y, **marginal_kws) + + # Make the main axes active in the matplotlib state machine + plt.sca(grid.ax_joint) + + return grid + + +jointplot.__doc__ = """\ +Draw a plot of two variables with bivariate and univariate graphs. + +This function provides a convenient interface to the :class:`JointGrid` +class, with several canned plot kinds. This is intended to be a fairly +lightweight wrapper; if you need more flexibility, you should use +:class:`JointGrid` directly. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} + Semantic variable that is mapped to determine the color of plot elements. +kind : {{ "scatter" | "kde" | "hist" | "hex" | "reg" | "resid" }} + Kind of plot to draw. See the examples for references to the underlying functions. +height : numeric + Size of the figure (it will be square). +ratio : numeric + Ratio of joint axes height to marginal axes height. +space : numeric + Space between the joint and marginal axes +dropna : bool + If True, remove observations that are missing from ``x`` and ``y``. +{{x, y}}lim : pairs of numbers + Axis limits to set before plotting. +{params.core.color} +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +marginal_ticks : bool + If False, suppress ticks on the count/density axis of the marginal plots. +{{joint, marginal}}_kws : dicts + Additional keyword arguments for the plot components. +kwargs + Additional keyword arguments are passed to the function used to + draw the plot on the joint Axes, superseding items in the + ``joint_kws`` dictionary. + +Returns +------- +{returns.jointgrid} + +See Also +-------- +{seealso.jointgrid} +{seealso.pairgrid} +{seealso.pairplot} + +Examples +-------- + +.. include:: ../docstrings/jointplot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) diff --git a/testbed/mwaskom__seaborn/seaborn/categorical.py b/testbed/mwaskom__seaborn/seaborn/categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..e22d301b75e47cc41400ffd545e3f91bd5ad52d1 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/categorical.py @@ -0,0 +1,3546 @@ +from textwrap import dedent +from numbers import Number +import warnings +from colorsys import rgb_to_hls +from functools import partial + +import numpy as np +import pandas as pd +try: + from scipy.stats import gaussian_kde + _no_scipy = False +except ImportError: + from .external.kde import gaussian_kde + _no_scipy = True + +import matplotlib as mpl +from matplotlib.collections import PatchCollection +import matplotlib.patches as Patches +import matplotlib.pyplot as plt + +from seaborn._oldcore import ( + variable_type, + infer_orient, + categorical_order, +) +from seaborn.relational import _RelationalPlotter +from seaborn import utils +from seaborn.utils import remove_na, _normal_quantile_func, _draw_figure, _default_color +from seaborn._statistics import EstimateAggregator +from seaborn.palettes import color_palette, husl_palette, light_palette, dark_palette +from seaborn.axisgrid import FacetGrid, _facet_docs + + +__all__ = [ + "catplot", + "stripplot", "swarmplot", + "boxplot", "violinplot", "boxenplot", + "pointplot", "barplot", "countplot", +] + + +# Subclassing _RelationalPlotter for the legend machinery, +# but probably should move that more centrally +class _CategoricalPlotterNew(_RelationalPlotter): + + semantics = "x", "y", "hue", "units" + + wide_structure = {"x": "@columns", "y": "@values", "hue": "@columns"} + + # flat_structure = {"x": "@values", "y": "@values"} + flat_structure = {"y": "@values"} + + _legend_func = "scatter" + _legend_attributes = ["color"] + + def __init__( + self, + data=None, + variables={}, + order=None, + orient=None, + require_numeric=False, + legend="auto", + ): + + super().__init__(data=data, variables=variables) + + # This method takes care of some bookkeeping that is necessary because the + # original categorical plots (prior to the 2021 refactor) had some rules that + # don't fit exactly into the logic of _core. It may be wise to have a second + # round of refactoring that moves the logic deeper, but this will keep things + # relatively sensible for now. + + # For wide data, orient determines assignment to x/y differently from the + # wide_structure rules in _core. If we do decide to make orient part of the + # _core variable assignment, we'll want to figure out how to express that. + if self.input_format == "wide" and orient == "h": + self.plot_data = self.plot_data.rename(columns={"x": "y", "y": "x"}) + orig_variables = set(self.variables) + orig_x = self.variables.pop("x", None) + orig_y = self.variables.pop("y", None) + orig_x_type = self.var_types.pop("x", None) + orig_y_type = self.var_types.pop("y", None) + if "x" in orig_variables: + self.variables["y"] = orig_x + self.var_types["y"] = orig_x_type + if "y" in orig_variables: + self.variables["x"] = orig_y + self.var_types["x"] = orig_y_type + + # The concept of an "orientation" is important to the original categorical + # plots, but there's no provision for it in _core, so we need to do it here. + # Note that it could be useful for the other functions in at least two ways + # (orienting a univariate distribution plot from long-form data and selecting + # the aggregation axis in lineplot), so we may want to eventually refactor it. + self.orient = infer_orient( + x=self.plot_data.get("x", None), + y=self.plot_data.get("y", None), + orient=orient, + require_numeric=require_numeric, + ) + + self.legend = legend + + # Short-circuit in the case of an empty plot + if not self.has_xy_data: + return + + # Categorical plots can be "univariate" in which case they get an anonymous + # category label on the opposite axis. Note: this duplicates code in the core + # scale_categorical function. We need to do it here because of the next line. + if self.cat_axis not in self.variables: + self.variables[self.cat_axis] = None + self.var_types[self.cat_axis] = "categorical" + self.plot_data[self.cat_axis] = "" + + # Categorical variables have discrete levels that we need to track + cat_levels = categorical_order(self.plot_data[self.cat_axis], order) + self.var_levels[self.cat_axis] = cat_levels + + def _hue_backcompat(self, color, palette, hue_order, force_hue=False): + """Implement backwards compatibility for hue parametrization. + + Note: the force_hue parameter is used so that functions can be shown to + pass existing tests during refactoring and then tested for new behavior. + It can be removed after completion of the work. + + """ + # The original categorical functions applied a palette to the categorical axis + # by default. We want to require an explicit hue mapping, to be more consistent + # with how things work elsewhere now. I don't think there's any good way to + # do this gently -- because it's triggered by the default value of hue=None, + # users would always get a warning, unless we introduce some sentinel "default" + # argument for this change. That's possible, but asking users to set `hue=None` + # on every call is annoying. + # We are keeping the logic for implementing the old behavior in with the current + # system so that (a) we can punt on that decision and (b) we can ensure that + # refactored code passes old tests. + default_behavior = color is None or palette is not None + if force_hue and "hue" not in self.variables and default_behavior: + self._redundant_hue = True + self.plot_data["hue"] = self.plot_data[self.cat_axis] + self.variables["hue"] = self.variables[self.cat_axis] + self.var_types["hue"] = "categorical" + hue_order = self.var_levels[self.cat_axis] + + # Because we convert the categorical axis variable to string, + # we need to update a dictionary palette too + if isinstance(palette, dict): + palette = {str(k): v for k, v in palette.items()} + + else: + self._redundant_hue = False + + # Previously, categorical plots had a trick where color= could seed the palette. + # Because that's an explicit parameterization, we are going to give it one + # release cycle with a warning before removing. + if "hue" in self.variables and palette is None and color is not None: + if not isinstance(color, str): + color = mpl.colors.to_hex(color) + palette = f"dark:{color}" + msg = ( + "Setting a gradient palette using color= is deprecated and will be " + f"removed in version 0.13. Set `palette='{palette}'` for same effect." + ) + warnings.warn(msg, FutureWarning) + + return palette, hue_order + + def _palette_without_hue_backcompat(self, palette, hue_order): + """Provide one cycle where palette= implies hue= when not provided""" + if "hue" not in self.variables and palette is not None: + msg = "Passing `palette` without assigning `hue` is deprecated." + warnings.warn(msg, FutureWarning, stacklevel=3) + self.legend = False + self.plot_data["hue"] = self.plot_data[self.cat_axis] + self.variables["hue"] = self.variables.get(self.cat_axis) + self.var_types["hue"] = self.var_types.get(self.cat_axis) + hue_order = self.var_levels.get(self.cat_axis) + return hue_order + + @property + def cat_axis(self): + return {"v": "x", "h": "y"}[self.orient] + + def _get_gray(self, colors): + """Get a grayscale value that looks good with color.""" + if not len(colors): + return None + unique_colors = np.unique(colors, axis=0) + light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors] + lum = min(light_vals) * .6 + return (lum, lum, lum) + + def _adjust_cat_axis(self, ax, axis): + """Set ticks and limits for a categorical variable.""" + # Note: in theory, this could happen in _attach for all categorical axes + # But two reasons not to do that: + # - If it happens before plotting, autoscaling messes up the plot limits + # - It would change existing plots from other seaborn functions + if self.var_types[axis] != "categorical": + return + + # If both x/y data are empty, the correct way to set up the plot is + # somewhat undefined; because we don't add null category data to the plot in + # this case we don't *have* a categorical axis (yet), so best to just bail. + if self.plot_data[axis].empty: + return + + # We can infer the total number of categories (including those from previous + # plots that are not part of the plot we are currently making) from the number + # of ticks, which matplotlib sets up while doing unit conversion. This feels + # slightly risky, as if we are relying on something that may be a matplotlib + # implementation detail. But I cannot think of a better way to keep track of + # the state from previous categorical calls (see GH2516 for context) + n = len(getattr(ax, f"get_{axis}ticks")()) + + if axis == "x": + ax.xaxis.grid(False) + ax.set_xlim(-.5, n - .5, auto=None) + else: + ax.yaxis.grid(False) + # Note limits that correspond to previously-inverted y axis + ax.set_ylim(n - .5, -.5, auto=None) + + @property + def _native_width(self): + """Return unit of width separating categories on native numeric scale.""" + unique_values = np.unique(self.comp_data[self.cat_axis]) + if len(unique_values) > 1: + native_width = np.nanmin(np.diff(unique_values)) + else: + native_width = 1 + return native_width + + def _nested_offsets(self, width, dodge): + """Return offsets for each hue level for dodged plots.""" + offsets = None + if "hue" in self.variables and self._hue_map.levels is not None: + n_levels = len(self._hue_map.levels) + if dodge: + each_width = width / n_levels + offsets = np.linspace(0, width - each_width, n_levels) + offsets -= offsets.mean() + else: + offsets = np.zeros(n_levels) + return offsets + + # Note that the plotting methods here aim (in most cases) to produce the + # exact same artists as the original (pre 0.12) version of the code, so + # there is some weirdness that might not otherwise be clean or make sense in + # this context, such as adding empty artists for combinations of variables + # with no observations + + def plot_strips( + self, + jitter, + dodge, + color, + edgecolor, + plot_kws, + ): + + width = .8 * self._native_width + offsets = self._nested_offsets(width, dodge) + + if jitter is True: + jlim = 0.1 + else: + jlim = float(jitter) + if "hue" in self.variables and dodge and self._hue_map.levels is not None: + jlim /= len(self._hue_map.levels) + jlim *= self._native_width + jitterer = partial(np.random.uniform, low=-jlim, high=+jlim) + + iter_vars = [self.cat_axis] + if dodge: + iter_vars.append("hue") + + ax = self.ax + dodge_move = jitter_move = 0 + + for sub_vars, sub_data in self.iter_data(iter_vars, + from_comp_data=True, + allow_empty=True): + if offsets is not None and (offsets != 0).any(): + dodge_move = offsets[sub_data["hue"].map(self._hue_map.levels.index)] + + jitter_move = jitterer(size=len(sub_data)) if len(sub_data) > 1 else 0 + + adjusted_data = sub_data[self.cat_axis] + dodge_move + jitter_move + sub_data[self.cat_axis] = adjusted_data + + for var in "xy": + if self._log_scaled(var): + sub_data[var] = np.power(10, sub_data[var]) + + ax = self._get_axes(sub_vars) + points = ax.scatter(sub_data["x"], sub_data["y"], color=color, **plot_kws) + + if "hue" in self.variables: + points.set_facecolors(self._hue_map(sub_data["hue"])) + + if edgecolor == "gray": # XXX TODO change to "auto" + points.set_edgecolors(self._get_gray(points.get_facecolors())) + else: + points.set_edgecolors(edgecolor) + + # Finalize the axes details + if self.legend == "auto": + show_legend = not self._redundant_hue and self.input_format != "wide" + else: + show_legend = bool(self.legend) + + if show_legend: + self.add_legend_data(ax) + handles, _ = ax.get_legend_handles_labels() + if handles: + ax.legend(title=self.legend_title) + + def plot_swarms( + self, + dodge, + color, + edgecolor, + warn_thresh, + plot_kws, + ): + + width = .8 * self._native_width + offsets = self._nested_offsets(width, dodge) + + iter_vars = [self.cat_axis] + if dodge: + iter_vars.append("hue") + + ax = self.ax + point_collections = {} + dodge_move = 0 + + for sub_vars, sub_data in self.iter_data(iter_vars, + from_comp_data=True, + allow_empty=True): + + if offsets is not None: + dodge_move = offsets[sub_data["hue"].map(self._hue_map.levels.index)] + + if not sub_data.empty: + sub_data[self.cat_axis] = sub_data[self.cat_axis] + dodge_move + + for var in "xy": + if self._log_scaled(var): + sub_data[var] = np.power(10, sub_data[var]) + + ax = self._get_axes(sub_vars) + points = ax.scatter(sub_data["x"], sub_data["y"], color=color, **plot_kws) + + if "hue" in self.variables: + points.set_facecolors(self._hue_map(sub_data["hue"])) + + if edgecolor == "gray": # XXX TODO change to "auto" + points.set_edgecolors(self._get_gray(points.get_facecolors())) + else: + points.set_edgecolors(edgecolor) + + if not sub_data.empty: + point_collections[(ax, sub_data[self.cat_axis].iloc[0])] = points + + beeswarm = Beeswarm( + width=width, orient=self.orient, warn_thresh=warn_thresh, + ) + for (ax, center), points in point_collections.items(): + if points.get_offsets().shape[0] > 1: + + def draw(points, renderer, *, center=center): + + beeswarm(points, center) + + if self.orient == "h": + scalex = False + scaley = ax.get_autoscaley_on() + else: + scalex = ax.get_autoscalex_on() + scaley = False + + # This prevents us from undoing the nice categorical axis limits + # set in _adjust_cat_axis, because that method currently leave + # the autoscale flag in its original setting. It may be better + # to disable autoscaling there to avoid needing to do this. + fixed_scale = self.var_types[self.cat_axis] == "categorical" + ax.update_datalim(points.get_datalim(ax.transData)) + if not fixed_scale and (scalex or scaley): + ax.autoscale_view(scalex=scalex, scaley=scaley) + + super(points.__class__, points).draw(renderer) + + points.draw = draw.__get__(points) + + _draw_figure(ax.figure) + + # Finalize the axes details + if self.legend == "auto": + show_legend = not self._redundant_hue and self.input_format != "wide" + else: + show_legend = bool(self.legend) + + if show_legend: + self.add_legend_data(ax) + handles, _ = ax.get_legend_handles_labels() + if handles: + ax.legend(title=self.legend_title) + + +class _CategoricalFacetPlotter(_CategoricalPlotterNew): + + semantics = _CategoricalPlotterNew.semantics + ("col", "row") + + +class _CategoricalPlotter: + + width = .8 + default_palette = "light" + require_numeric = True + + def establish_variables(self, x=None, y=None, hue=None, data=None, + orient=None, order=None, hue_order=None, + units=None): + """Convert input specification into a common representation.""" + # Option 1: + # We are plotting a wide-form dataset + # ----------------------------------- + if x is None and y is None: + + # Do a sanity check on the inputs + if hue is not None: + error = "Cannot use `hue` without `x` and `y`" + raise ValueError(error) + + # No hue grouping with wide inputs + plot_hues = None + hue_title = None + hue_names = None + + # No statistical units with wide inputs + plot_units = None + + # We also won't get a axes labels here + value_label = None + group_label = None + + # Option 1a: + # The input data is a Pandas DataFrame + # ------------------------------------ + + if isinstance(data, pd.DataFrame): + + # Order the data correctly + if order is None: + order = [] + # Reduce to just numeric columns + for col in data: + if variable_type(data[col]) == "numeric": + order.append(col) + plot_data = data[order] + group_names = order + group_label = data.columns.name + + # Convert to a list of arrays, the common representation + iter_data = plot_data.items() + plot_data = [np.asarray(s, float) for k, s in iter_data] + + # Option 1b: + # The input data is an array or list + # ---------------------------------- + + else: + + # We can't reorder the data + if order is not None: + error = "Input data must be a pandas object to reorder" + raise ValueError(error) + + # The input data is an array + if hasattr(data, "shape"): + if len(data.shape) == 1: + if np.isscalar(data[0]): + plot_data = [data] + else: + plot_data = list(data) + elif len(data.shape) == 2: + nr, nc = data.shape + if nr == 1 or nc == 1: + plot_data = [data.ravel()] + else: + plot_data = [data[:, i] for i in range(nc)] + else: + error = ("Input `data` can have no " + "more than 2 dimensions") + raise ValueError(error) + + # Check if `data` is None to let us bail out here (for testing) + elif data is None: + plot_data = [[]] + + # The input data is a flat list + elif np.isscalar(data[0]): + plot_data = [data] + + # The input data is a nested list + # This will catch some things that might fail later + # but exhaustive checks are hard + else: + plot_data = data + + # Convert to a list of arrays, the common representation + plot_data = [np.asarray(d, float) for d in plot_data] + + # The group names will just be numeric indices + group_names = list(range(len(plot_data))) + + # Figure out the plotting orientation + orient = "h" if str(orient).startswith("h") else "v" + + # Option 2: + # We are plotting a long-form dataset + # ----------------------------------- + + else: + + # See if we need to get variables from `data` + if data is not None: + x = data.get(x, x) + y = data.get(y, y) + hue = data.get(hue, hue) + units = data.get(units, units) + + # Validate the inputs + for var in [x, y, hue, units]: + if isinstance(var, str): + err = f"Could not interpret input '{var}'" + raise ValueError(err) + + # Figure out the plotting orientation + orient = infer_orient( + x, y, orient, require_numeric=self.require_numeric + ) + + # Option 2a: + # We are plotting a single set of data + # ------------------------------------ + if x is None or y is None: + + # Determine where the data are + vals = y if x is None else x + + # Put them into the common representation + plot_data = [np.asarray(vals)] + + # Get a label for the value axis + if hasattr(vals, "name"): + value_label = vals.name + else: + value_label = None + + # This plot will not have group labels or hue nesting + groups = None + group_label = None + group_names = [] + plot_hues = None + hue_names = None + hue_title = None + plot_units = None + + # Option 2b: + # We are grouping the data values by another variable + # --------------------------------------------------- + else: + + # Determine which role each variable will play + if orient == "v": + vals, groups = y, x + else: + vals, groups = x, y + + # Get the categorical axis label + group_label = None + if hasattr(groups, "name"): + group_label = groups.name + + # Get the order on the categorical axis + group_names = categorical_order(groups, order) + + # Group the numeric data + plot_data, value_label = self._group_longform(vals, groups, + group_names) + + # Now handle the hue levels for nested ordering + if hue is None: + plot_hues = None + hue_title = None + hue_names = None + else: + + # Get the order of the hue levels + hue_names = categorical_order(hue, hue_order) + + # Group the hue data + plot_hues, hue_title = self._group_longform(hue, groups, + group_names) + + # Now handle the units for nested observations + if units is None: + plot_units = None + else: + plot_units, _ = self._group_longform(units, groups, + group_names) + + # Assign object attributes + # ------------------------ + self.orient = orient + self.plot_data = plot_data + self.group_label = group_label + self.value_label = value_label + self.group_names = group_names + self.plot_hues = plot_hues + self.hue_title = hue_title + self.hue_names = hue_names + self.plot_units = plot_units + + def _group_longform(self, vals, grouper, order): + """Group a long-form variable by another with correct order.""" + # Ensure that the groupby will work + if not isinstance(vals, pd.Series): + if isinstance(grouper, pd.Series): + index = grouper.index + else: + index = None + vals = pd.Series(vals, index=index) + + # Group the val data + grouped_vals = vals.groupby(grouper) + out_data = [] + for g in order: + try: + g_vals = grouped_vals.get_group(g) + except KeyError: + g_vals = np.array([]) + out_data.append(g_vals) + + # Get the vals axis label + label = vals.name + + return out_data, label + + def establish_colors(self, color, palette, saturation): + """Get a list of colors for the main component of the plots.""" + if self.hue_names is None: + n_colors = len(self.plot_data) + else: + n_colors = len(self.hue_names) + + # Determine the main colors + if color is None and palette is None: + # Determine whether the current palette will have enough values + # If not, we'll default to the husl palette so each is distinct + current_palette = utils.get_color_cycle() + if n_colors <= len(current_palette): + colors = color_palette(n_colors=n_colors) + else: + colors = husl_palette(n_colors, l=.7) # noqa + + elif palette is None: + # When passing a specific color, the interpretation depends + # on whether there is a hue variable or not. + # If so, we will make a blend palette so that the different + # levels have some amount of variation. + if self.hue_names is None: + colors = [color] * n_colors + else: + if self.default_palette == "light": + colors = light_palette(color, n_colors) + elif self.default_palette == "dark": + colors = dark_palette(color, n_colors) + else: + raise RuntimeError("No default palette specified") + else: + + # Let `palette` be a dict mapping level to color + if isinstance(palette, dict): + if self.hue_names is None: + levels = self.group_names + else: + levels = self.hue_names + palette = [palette[l] for l in levels] + + colors = color_palette(palette, n_colors) + + # Desaturate a bit because these are patches + if saturation < 1: + colors = color_palette(colors, desat=saturation) + + # Convert the colors to a common representations + rgb_colors = color_palette(colors) + + # Determine the gray color to use for the lines framing the plot + light_vals = [rgb_to_hls(*c)[1] for c in rgb_colors] + lum = min(light_vals) * .6 + gray = mpl.colors.rgb2hex((lum, lum, lum)) + + # Assign object attributes + self.colors = rgb_colors + self.gray = gray + + @property + def hue_offsets(self): + """A list of center positions for plots when hue nesting is used.""" + n_levels = len(self.hue_names) + if self.dodge: + each_width = self.width / n_levels + offsets = np.linspace(0, self.width - each_width, n_levels) + offsets -= offsets.mean() + else: + offsets = np.zeros(n_levels) + + return offsets + + @property + def nested_width(self): + """A float with the width of plot elements when hue nesting is used.""" + if self.dodge: + width = self.width / len(self.hue_names) * .98 + else: + width = self.width + return width + + def annotate_axes(self, ax): + """Add descriptive labels to an Axes object.""" + if self.orient == "v": + xlabel, ylabel = self.group_label, self.value_label + else: + xlabel, ylabel = self.value_label, self.group_label + + if xlabel is not None: + ax.set_xlabel(xlabel) + if ylabel is not None: + ax.set_ylabel(ylabel) + + group_names = self.group_names + if not group_names: + group_names = ["" for _ in range(len(self.plot_data))] + + if self.orient == "v": + ax.set_xticks(np.arange(len(self.plot_data))) + ax.set_xticklabels(group_names) + else: + ax.set_yticks(np.arange(len(self.plot_data))) + ax.set_yticklabels(group_names) + + if self.orient == "v": + ax.xaxis.grid(False) + ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None) + else: + ax.yaxis.grid(False) + ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None) + + if self.hue_names is not None: + ax.legend(loc="best", title=self.hue_title) + + def add_legend_data(self, ax, color, label): + """Add a dummy patch object so we can get legend data.""" + rect = plt.Rectangle([0, 0], 0, 0, + linewidth=self.linewidth / 2, + edgecolor=self.gray, + facecolor=color, + label=label) + ax.add_patch(rect) + + +class _BoxPlotter(_CategoricalPlotter): + + def __init__(self, x, y, hue, data, order, hue_order, + orient, color, palette, saturation, + width, dodge, fliersize, linewidth): + + self.establish_variables(x, y, hue, data, orient, order, hue_order) + self.establish_colors(color, palette, saturation) + + self.dodge = dodge + self.width = width + self.fliersize = fliersize + + if linewidth is None: + linewidth = mpl.rcParams["lines.linewidth"] + self.linewidth = linewidth + + def draw_boxplot(self, ax, kws): + """Use matplotlib to draw a boxplot on an Axes.""" + vert = self.orient == "v" + + props = {} + for obj in ["box", "whisker", "cap", "median", "flier"]: + props[obj] = kws.pop(obj + "props", {}) + + for i, group_data in enumerate(self.plot_data): + + if self.plot_hues is None: + + # Handle case where there is data at this level + if group_data.size == 0: + continue + + # Draw a single box or a set of boxes + # with a single level of grouping + box_data = np.asarray(remove_na(group_data)) + + # Handle case where there is no non-null data + if box_data.size == 0: + continue + + artist_dict = ax.boxplot(box_data, + vert=vert, + patch_artist=True, + positions=[i], + widths=self.width, + **kws) + color = self.colors[i] + self.restyle_boxplot(artist_dict, color, props) + else: + # Draw nested groups of boxes + offsets = self.hue_offsets + for j, hue_level in enumerate(self.hue_names): + + # Add a legend for this hue level + if not i: + self.add_legend_data(ax, self.colors[j], hue_level) + + # Handle case where there is data at this level + if group_data.size == 0: + continue + + hue_mask = self.plot_hues[i] == hue_level + box_data = np.asarray(remove_na(group_data[hue_mask])) + + # Handle case where there is no non-null data + if box_data.size == 0: + continue + + center = i + offsets[j] + artist_dict = ax.boxplot(box_data, + vert=vert, + patch_artist=True, + positions=[center], + widths=self.nested_width, + **kws) + self.restyle_boxplot(artist_dict, self.colors[j], props) + # Add legend data, but just for one set of boxes + + def restyle_boxplot(self, artist_dict, color, props): + """Take a drawn matplotlib boxplot and make it look nice.""" + for box in artist_dict["boxes"]: + box.update(dict(facecolor=color, + zorder=.9, + edgecolor=self.gray, + linewidth=self.linewidth)) + box.update(props["box"]) + for whisk in artist_dict["whiskers"]: + whisk.update(dict(color=self.gray, + linewidth=self.linewidth, + linestyle="-")) + whisk.update(props["whisker"]) + for cap in artist_dict["caps"]: + cap.update(dict(color=self.gray, + linewidth=self.linewidth)) + cap.update(props["cap"]) + for med in artist_dict["medians"]: + med.update(dict(color=self.gray, + linewidth=self.linewidth)) + med.update(props["median"]) + for fly in artist_dict["fliers"]: + fly.update(dict(markerfacecolor=self.gray, + marker="d", + markeredgecolor=self.gray, + markersize=self.fliersize)) + fly.update(props["flier"]) + + def plot(self, ax, boxplot_kws): + """Make the plot.""" + self.draw_boxplot(ax, boxplot_kws) + self.annotate_axes(ax) + if self.orient == "h": + ax.invert_yaxis() + + +class _ViolinPlotter(_CategoricalPlotter): + + def __init__(self, x, y, hue, data, order, hue_order, + bw, cut, scale, scale_hue, gridsize, + width, inner, split, dodge, orient, linewidth, + color, palette, saturation): + + self.establish_variables(x, y, hue, data, orient, order, hue_order) + self.establish_colors(color, palette, saturation) + self.estimate_densities(bw, cut, scale, scale_hue, gridsize) + + self.gridsize = gridsize + self.width = width + self.dodge = dodge + + if inner is not None: + if not any([inner.startswith("quart"), + inner.startswith("box"), + inner.startswith("stick"), + inner.startswith("point")]): + err = f"Inner style '{inner}' not recognized" + raise ValueError(err) + self.inner = inner + + if split and self.hue_names is not None and len(self.hue_names) != 2: + msg = "There must be exactly two hue levels to use `split`.'" + raise ValueError(msg) + self.split = split + + if linewidth is None: + linewidth = mpl.rcParams["lines.linewidth"] + self.linewidth = linewidth + + def estimate_densities(self, bw, cut, scale, scale_hue, gridsize): + """Find the support and density for all of the data.""" + # Initialize data structures to keep track of plotting data + if self.hue_names is None: + support = [] + density = [] + counts = np.zeros(len(self.plot_data)) + max_density = np.zeros(len(self.plot_data)) + else: + support = [[] for _ in self.plot_data] + density = [[] for _ in self.plot_data] + size = len(self.group_names), len(self.hue_names) + counts = np.zeros(size) + max_density = np.zeros(size) + + for i, group_data in enumerate(self.plot_data): + + # Option 1: we have a single level of grouping + # -------------------------------------------- + + if self.plot_hues is None: + + # Strip missing datapoints + kde_data = remove_na(group_data) + + # Handle special case of no data at this level + if kde_data.size == 0: + support.append(np.array([])) + density.append(np.array([1.])) + counts[i] = 0 + max_density[i] = 0 + continue + + # Handle special case of a single unique datapoint + elif np.unique(kde_data).size == 1: + support.append(np.unique(kde_data)) + density.append(np.array([1.])) + counts[i] = 1 + max_density[i] = 0 + continue + + # Fit the KDE and get the used bandwidth size + kde, bw_used = self.fit_kde(kde_data, bw) + + # Determine the support grid and get the density over it + support_i = self.kde_support(kde_data, bw_used, cut, gridsize) + density_i = kde.evaluate(support_i) + + # Update the data structures with these results + support.append(support_i) + density.append(density_i) + counts[i] = kde_data.size + max_density[i] = density_i.max() + + # Option 2: we have nested grouping by a hue variable + # --------------------------------------------------- + + else: + for j, hue_level in enumerate(self.hue_names): + + # Handle special case of no data at this category level + if not group_data.size: + support[i].append(np.array([])) + density[i].append(np.array([1.])) + counts[i, j] = 0 + max_density[i, j] = 0 + continue + + # Select out the observations for this hue level + hue_mask = self.plot_hues[i] == hue_level + + # Strip missing datapoints + kde_data = remove_na(group_data[hue_mask]) + + # Handle special case of no data at this level + if kde_data.size == 0: + support[i].append(np.array([])) + density[i].append(np.array([1.])) + counts[i, j] = 0 + max_density[i, j] = 0 + continue + + # Handle special case of a single unique datapoint + elif np.unique(kde_data).size == 1: + support[i].append(np.unique(kde_data)) + density[i].append(np.array([1.])) + counts[i, j] = 1 + max_density[i, j] = 0 + continue + + # Fit the KDE and get the used bandwidth size + kde, bw_used = self.fit_kde(kde_data, bw) + + # Determine the support grid and get the density over it + support_ij = self.kde_support(kde_data, bw_used, + cut, gridsize) + density_ij = kde.evaluate(support_ij) + + # Update the data structures with these results + support[i].append(support_ij) + density[i].append(density_ij) + counts[i, j] = kde_data.size + max_density[i, j] = density_ij.max() + + # Scale the height of the density curve. + # For a violinplot the density is non-quantitative. + # The objective here is to scale the curves relative to 1 so that + # they can be multiplied by the width parameter during plotting. + + if scale == "area": + self.scale_area(density, max_density, scale_hue) + + elif scale == "width": + self.scale_width(density) + + elif scale == "count": + self.scale_count(density, counts, scale_hue) + + else: + raise ValueError(f"scale method '{scale}' not recognized") + + # Set object attributes that will be used while plotting + self.support = support + self.density = density + + def fit_kde(self, x, bw): + """Estimate a KDE for a vector of data with flexible bandwidth.""" + kde = gaussian_kde(x, bw) + + # Extract the numeric bandwidth from the KDE object + bw_used = kde.factor + + # At this point, bw will be a numeric scale factor. + # To get the actual bandwidth of the kernel, we multiple by the + # unbiased standard deviation of the data, which we will use + # elsewhere to compute the range of the support. + bw_used = bw_used * x.std(ddof=1) + + return kde, bw_used + + def kde_support(self, x, bw, cut, gridsize): + """Define a grid of support for the violin.""" + support_min = x.min() - bw * cut + support_max = x.max() + bw * cut + return np.linspace(support_min, support_max, gridsize) + + def scale_area(self, density, max_density, scale_hue): + """Scale the relative area under the KDE curve. + + This essentially preserves the "standard" KDE scaling, but the + resulting maximum density will be 1 so that the curve can be + properly multiplied by the violin width. + + """ + if self.hue_names is None: + for d in density: + if d.size > 1: + d /= max_density.max() + else: + for i, group in enumerate(density): + for d in group: + if scale_hue: + max = max_density[i].max() + else: + max = max_density.max() + if d.size > 1: + d /= max + + def scale_width(self, density): + """Scale each density curve to the same height.""" + if self.hue_names is None: + for d in density: + d /= d.max() + else: + for group in density: + for d in group: + d /= d.max() + + def scale_count(self, density, counts, scale_hue): + """Scale each density curve by the number of observations.""" + if self.hue_names is None: + if counts.max() == 0: + d = 0 + else: + for count, d in zip(counts, density): + d /= d.max() + d *= count / counts.max() + else: + for i, group in enumerate(density): + for j, d in enumerate(group): + if counts[i].max() == 0: + d = 0 + else: + count = counts[i, j] + if scale_hue: + scaler = count / counts[i].max() + else: + scaler = count / counts.max() + d /= d.max() + d *= scaler + + @property + def dwidth(self): + + if self.hue_names is None or not self.dodge: + return self.width / 2 + elif self.split: + return self.width / 2 + else: + return self.width / (2 * len(self.hue_names)) + + def draw_violins(self, ax): + """Draw the violins onto `ax`.""" + fill_func = ax.fill_betweenx if self.orient == "v" else ax.fill_between + for i, group_data in enumerate(self.plot_data): + + kws = dict(edgecolor=self.gray, linewidth=self.linewidth) + + # Option 1: we have a single level of grouping + # -------------------------------------------- + + if self.plot_hues is None: + + support, density = self.support[i], self.density[i] + + # Handle special case of no observations in this bin + if support.size == 0: + continue + + # Handle special case of a single observation + elif support.size == 1: + val = support.item() + d = density.item() + self.draw_single_observation(ax, i, val, d) + continue + + # Draw the violin for this group + grid = np.ones(self.gridsize) * i + fill_func(support, + grid - density * self.dwidth, + grid + density * self.dwidth, + facecolor=self.colors[i], + **kws) + + # Draw the interior representation of the data + if self.inner is None: + continue + + # Get a nan-free vector of datapoints + violin_data = remove_na(group_data) + + # Draw box and whisker information + if self.inner.startswith("box"): + self.draw_box_lines(ax, violin_data, i) + + # Draw quartile lines + elif self.inner.startswith("quart"): + self.draw_quartiles(ax, violin_data, support, density, i) + + # Draw stick observations + elif self.inner.startswith("stick"): + self.draw_stick_lines(ax, violin_data, support, density, i) + + # Draw point observations + elif self.inner.startswith("point"): + self.draw_points(ax, violin_data, i) + + # Option 2: we have nested grouping by a hue variable + # --------------------------------------------------- + + else: + offsets = self.hue_offsets + for j, hue_level in enumerate(self.hue_names): + + support, density = self.support[i][j], self.density[i][j] + kws["facecolor"] = self.colors[j] + + # Add legend data, but just for one set of violins + if not i: + self.add_legend_data(ax, self.colors[j], hue_level) + + # Handle the special case where we have no observations + if support.size == 0: + continue + + # Handle the special case where we have one observation + elif support.size == 1: + val = support.item() + d = density.item() + if self.split: + d = d / 2 + at_group = i + offsets[j] + self.draw_single_observation(ax, at_group, val, d) + continue + + # Option 2a: we are drawing a single split violin + # ----------------------------------------------- + + if self.split: + + grid = np.ones(self.gridsize) * i + if j: + fill_func(support, + grid, + grid + density * self.dwidth, + **kws) + else: + fill_func(support, + grid - density * self.dwidth, + grid, + **kws) + + # Draw the interior representation of the data + if self.inner is None: + continue + + # Get a nan-free vector of datapoints + hue_mask = self.plot_hues[i] == hue_level + violin_data = remove_na(group_data[hue_mask]) + + # Draw quartile lines + if self.inner.startswith("quart"): + self.draw_quartiles(ax, violin_data, + support, density, i, + ["left", "right"][j]) + + # Draw stick observations + elif self.inner.startswith("stick"): + self.draw_stick_lines(ax, violin_data, + support, density, i, + ["left", "right"][j]) + + # The box and point interior plots are drawn for + # all data at the group level, so we just do that once + if j and any(self.plot_hues[0] == hue_level): + continue + + # Get the whole vector for this group level + violin_data = remove_na(group_data) + + # Draw box and whisker information + if self.inner.startswith("box"): + self.draw_box_lines(ax, violin_data, i) + + # Draw point observations + elif self.inner.startswith("point"): + self.draw_points(ax, violin_data, i) + + # Option 2b: we are drawing full nested violins + # ----------------------------------------------- + + else: + grid = np.ones(self.gridsize) * (i + offsets[j]) + fill_func(support, + grid - density * self.dwidth, + grid + density * self.dwidth, + **kws) + + # Draw the interior representation + if self.inner is None: + continue + + # Get a nan-free vector of datapoints + hue_mask = self.plot_hues[i] == hue_level + violin_data = remove_na(group_data[hue_mask]) + + # Draw box and whisker information + if self.inner.startswith("box"): + self.draw_box_lines(ax, violin_data, i + offsets[j]) + + # Draw quartile lines + elif self.inner.startswith("quart"): + self.draw_quartiles(ax, violin_data, + support, density, + i + offsets[j]) + + # Draw stick observations + elif self.inner.startswith("stick"): + self.draw_stick_lines(ax, violin_data, + support, density, + i + offsets[j]) + + # Draw point observations + elif self.inner.startswith("point"): + self.draw_points(ax, violin_data, i + offsets[j]) + + def draw_single_observation(self, ax, at_group, at_quant, density): + """Draw a line to mark a single observation.""" + d_width = density * self.dwidth + if self.orient == "v": + ax.plot([at_group - d_width, at_group + d_width], + [at_quant, at_quant], + color=self.gray, + linewidth=self.linewidth) + else: + ax.plot([at_quant, at_quant], + [at_group - d_width, at_group + d_width], + color=self.gray, + linewidth=self.linewidth) + + def draw_box_lines(self, ax, data, center): + """Draw boxplot information at center of the density.""" + # Compute the boxplot statistics + q25, q50, q75 = np.percentile(data, [25, 50, 75]) + whisker_lim = 1.5 * (q75 - q25) + h1 = np.min(data[data >= (q25 - whisker_lim)]) + h2 = np.max(data[data <= (q75 + whisker_lim)]) + + # Draw a boxplot using lines and a point + if self.orient == "v": + ax.plot([center, center], [h1, h2], + linewidth=self.linewidth, + color=self.gray) + ax.plot([center, center], [q25, q75], + linewidth=self.linewidth * 3, + color=self.gray) + ax.scatter(center, q50, + zorder=3, + color="white", + edgecolor=self.gray, + s=np.square(self.linewidth * 2)) + else: + ax.plot([h1, h2], [center, center], + linewidth=self.linewidth, + color=self.gray) + ax.plot([q25, q75], [center, center], + linewidth=self.linewidth * 3, + color=self.gray) + ax.scatter(q50, center, + zorder=3, + color="white", + edgecolor=self.gray, + s=np.square(self.linewidth * 2)) + + def draw_quartiles(self, ax, data, support, density, center, split=False): + """Draw the quartiles as lines at width of density.""" + q25, q50, q75 = np.percentile(data, [25, 50, 75]) + + self.draw_to_density(ax, center, q25, support, density, split, + linewidth=self.linewidth, + dashes=[self.linewidth * 1.5] * 2) + self.draw_to_density(ax, center, q50, support, density, split, + linewidth=self.linewidth, + dashes=[self.linewidth * 3] * 2) + self.draw_to_density(ax, center, q75, support, density, split, + linewidth=self.linewidth, + dashes=[self.linewidth * 1.5] * 2) + + def draw_points(self, ax, data, center): + """Draw individual observations as points at middle of the violin.""" + kws = dict(s=np.square(self.linewidth * 2), + color=self.gray, + edgecolor=self.gray) + + grid = np.ones(len(data)) * center + + if self.orient == "v": + ax.scatter(grid, data, **kws) + else: + ax.scatter(data, grid, **kws) + + def draw_stick_lines(self, ax, data, support, density, + center, split=False): + """Draw individual observations as sticks at width of density.""" + for val in data: + self.draw_to_density(ax, center, val, support, density, split, + linewidth=self.linewidth * .5) + + def draw_to_density(self, ax, center, val, support, density, split, **kws): + """Draw a line orthogonal to the value axis at width of density.""" + idx = np.argmin(np.abs(support - val)) + width = self.dwidth * density[idx] * .99 + + kws["color"] = self.gray + + if self.orient == "v": + if split == "left": + ax.plot([center - width, center], [val, val], **kws) + elif split == "right": + ax.plot([center, center + width], [val, val], **kws) + else: + ax.plot([center - width, center + width], [val, val], **kws) + else: + if split == "left": + ax.plot([val, val], [center - width, center], **kws) + elif split == "right": + ax.plot([val, val], [center, center + width], **kws) + else: + ax.plot([val, val], [center - width, center + width], **kws) + + def plot(self, ax): + """Make the violin plot.""" + self.draw_violins(ax) + self.annotate_axes(ax) + if self.orient == "h": + ax.invert_yaxis() + + +class _CategoricalStatPlotter(_CategoricalPlotter): + + require_numeric = True + + @property + def nested_width(self): + """A float with the width of plot elements when hue nesting is used.""" + if self.dodge: + width = self.width / len(self.hue_names) + else: + width = self.width + return width + + def estimate_statistic(self, estimator, errorbar, n_boot, seed): + + if self.hue_names is None: + statistic = [] + confint = [] + else: + statistic = [[] for _ in self.plot_data] + confint = [[] for _ in self.plot_data] + + var = {"v": "y", "h": "x"}[self.orient] + + agg = EstimateAggregator(estimator, errorbar, n_boot=n_boot, seed=seed) + + for i, group_data in enumerate(self.plot_data): + + # Option 1: we have a single layer of grouping + # -------------------------------------------- + if self.plot_hues is None: + + df = pd.DataFrame({var: group_data}) + if self.plot_units is not None: + df["units"] = self.plot_units[i] + + res = agg(df, var) + + statistic.append(res[var]) + if errorbar is not None: + confint.append((res[f"{var}min"], res[f"{var}max"])) + + # Option 2: we are grouping by a hue layer + # ---------------------------------------- + + else: + for hue_level in self.hue_names: + + if not self.plot_hues[i].size: + statistic[i].append(np.nan) + if errorbar is not None: + confint[i].append((np.nan, np.nan)) + continue + + hue_mask = self.plot_hues[i] == hue_level + df = pd.DataFrame({var: group_data[hue_mask]}) + if self.plot_units is not None: + df["units"] = self.plot_units[i][hue_mask] + + res = agg(df, var) + + statistic[i].append(res[var]) + if errorbar is not None: + confint[i].append((res[f"{var}min"], res[f"{var}max"])) + + # Save the resulting values for plotting + self.statistic = np.array(statistic) + self.confint = np.array(confint) + + def draw_confints(self, ax, at_group, confint, colors, + errwidth=None, capsize=None, **kws): + + if errwidth is not None: + kws.setdefault("lw", errwidth) + else: + kws.setdefault("lw", mpl.rcParams["lines.linewidth"] * 1.8) + + for at, (ci_low, ci_high), color in zip(at_group, + confint, + colors): + if self.orient == "v": + ax.plot([at, at], [ci_low, ci_high], color=color, **kws) + if capsize is not None: + ax.plot([at - capsize / 2, at + capsize / 2], + [ci_low, ci_low], color=color, **kws) + ax.plot([at - capsize / 2, at + capsize / 2], + [ci_high, ci_high], color=color, **kws) + else: + ax.plot([ci_low, ci_high], [at, at], color=color, **kws) + if capsize is not None: + ax.plot([ci_low, ci_low], + [at - capsize / 2, at + capsize / 2], + color=color, **kws) + ax.plot([ci_high, ci_high], + [at - capsize / 2, at + capsize / 2], + color=color, **kws) + + +class _BarPlotter(_CategoricalStatPlotter): + + def __init__(self, x, y, hue, data, order, hue_order, + estimator, errorbar, n_boot, units, seed, + orient, color, palette, saturation, width, + errcolor, errwidth, capsize, dodge): + """Initialize the plotter.""" + self.establish_variables(x, y, hue, data, orient, + order, hue_order, units) + self.establish_colors(color, palette, saturation) + self.estimate_statistic(estimator, errorbar, n_boot, seed) + + self.dodge = dodge + self.width = width + + self.errcolor = errcolor + self.errwidth = errwidth + self.capsize = capsize + + def draw_bars(self, ax, kws): + """Draw the bars onto `ax`.""" + # Get the right matplotlib function depending on the orientation + barfunc = ax.bar if self.orient == "v" else ax.barh + barpos = np.arange(len(self.statistic)) + + if self.plot_hues is None: + + # Draw the bars + barfunc(barpos, self.statistic, self.width, + color=self.colors, align="center", **kws) + + # Draw the confidence intervals + errcolors = [self.errcolor] * len(barpos) + self.draw_confints(ax, + barpos, + self.confint, + errcolors, + self.errwidth, + self.capsize) + + else: + + for j, hue_level in enumerate(self.hue_names): + + # Draw the bars + offpos = barpos + self.hue_offsets[j] + barfunc(offpos, self.statistic[:, j], self.nested_width, + color=self.colors[j], align="center", + label=hue_level, **kws) + + # Draw the confidence intervals + if self.confint.size: + confint = self.confint[:, j] + errcolors = [self.errcolor] * len(offpos) + self.draw_confints(ax, + offpos, + confint, + errcolors, + self.errwidth, + self.capsize) + + def plot(self, ax, bar_kws): + """Make the plot.""" + self.draw_bars(ax, bar_kws) + self.annotate_axes(ax) + if self.orient == "h": + ax.invert_yaxis() + + +class _PointPlotter(_CategoricalStatPlotter): + + default_palette = "dark" + + def __init__(self, x, y, hue, data, order, hue_order, + estimator, errorbar, n_boot, units, seed, + markers, linestyles, dodge, join, scale, + orient, color, palette, errwidth, capsize, label): + """Initialize the plotter.""" + self.establish_variables(x, y, hue, data, orient, + order, hue_order, units) + self.establish_colors(color, palette, 1) + self.estimate_statistic(estimator, errorbar, n_boot, seed) + + # Override the default palette for single-color plots + if hue is None and color is None and palette is None: + self.colors = [color_palette()[0]] * len(self.colors) + + # Don't join single-layer plots with different colors + if hue is None and palette is not None: + join = False + + # Use a good default for `dodge=True` + if dodge is True and self.hue_names is not None: + dodge = .025 * len(self.hue_names) + + # Make sure we have a marker for each hue level + if isinstance(markers, str): + markers = [markers] * len(self.colors) + self.markers = markers + + # Make sure we have a line style for each hue level + if isinstance(linestyles, str): + linestyles = [linestyles] * len(self.colors) + self.linestyles = linestyles + + # Set the other plot components + self.dodge = dodge + self.join = join + self.scale = scale + self.errwidth = errwidth + self.capsize = capsize + self.label = label + + @property + def hue_offsets(self): + """Offsets relative to the center position for each hue level.""" + if self.dodge: + offset = np.linspace(0, self.dodge, len(self.hue_names)) + offset -= offset.mean() + else: + offset = np.zeros(len(self.hue_names)) + return offset + + def draw_points(self, ax): + """Draw the main data components of the plot.""" + # Get the center positions on the categorical axis + pointpos = np.arange(len(self.statistic)) + + # Get the size of the plot elements + lw = mpl.rcParams["lines.linewidth"] * 1.8 * self.scale + mew = lw * .75 + markersize = np.pi * np.square(lw) * 2 + + if self.plot_hues is None: + + # Draw lines joining each estimate point + if self.join: + color = self.colors[0] + ls = self.linestyles[0] + if self.orient == "h": + ax.plot(self.statistic, pointpos, + color=color, ls=ls, lw=lw) + else: + ax.plot(pointpos, self.statistic, + color=color, ls=ls, lw=lw) + + # Draw the confidence intervals + self.draw_confints(ax, pointpos, self.confint, self.colors, + self.errwidth, self.capsize) + + # Draw the estimate points + marker = self.markers[0] + colors = [mpl.colors.colorConverter.to_rgb(c) for c in self.colors] + if self.orient == "h": + x, y = self.statistic, pointpos + else: + x, y = pointpos, self.statistic + ax.scatter(x, y, + linewidth=mew, marker=marker, s=markersize, + facecolor=colors, edgecolor=colors, label=self.label) + + else: + + offsets = self.hue_offsets + for j, hue_level in enumerate(self.hue_names): + + # Determine the values to plot for this level + statistic = self.statistic[:, j] + + # Determine the position on the categorical and z axes + offpos = pointpos + offsets[j] + z = j + 1 + + # Draw lines joining each estimate point + if self.join: + color = self.colors[j] + ls = self.linestyles[j] + if self.orient == "h": + ax.plot(statistic, offpos, color=color, + zorder=z, ls=ls, lw=lw) + else: + ax.plot(offpos, statistic, color=color, + zorder=z, ls=ls, lw=lw) + + # Draw the confidence intervals + if self.confint.size: + confint = self.confint[:, j] + errcolors = [self.colors[j]] * len(offpos) + self.draw_confints(ax, offpos, confint, errcolors, + self.errwidth, self.capsize, + zorder=z) + + # Draw the estimate points + n_points = len(remove_na(offpos)) + marker = self.markers[j] + color = mpl.colors.colorConverter.to_rgb(self.colors[j]) + + if self.orient == "h": + x, y = statistic, offpos + else: + x, y = offpos, statistic + + if not len(remove_na(statistic)): + x = y = [np.nan] * n_points + + ax.scatter(x, y, label=hue_level, + facecolor=color, edgecolor=color, + linewidth=mew, marker=marker, s=markersize, + zorder=z) + + def plot(self, ax): + """Make the plot.""" + self.draw_points(ax) + self.annotate_axes(ax) + if self.orient == "h": + ax.invert_yaxis() + + +class _CountPlotter(_BarPlotter): + require_numeric = False + + +class _LVPlotter(_CategoricalPlotter): + + def __init__(self, x, y, hue, data, order, hue_order, + orient, color, palette, saturation, + width, dodge, k_depth, linewidth, scale, outlier_prop, + trust_alpha, showfliers=True): + + self.width = width + self.dodge = dodge + self.saturation = saturation + + k_depth_methods = ['proportion', 'tukey', 'trustworthy', 'full'] + if not (k_depth in k_depth_methods or isinstance(k_depth, Number)): + msg = (f'k_depth must be one of {k_depth_methods} or a number, ' + f'but {k_depth} was passed.') + raise ValueError(msg) + self.k_depth = k_depth + + if linewidth is None: + linewidth = mpl.rcParams["lines.linewidth"] + self.linewidth = linewidth + + scales = ['linear', 'exponential', 'area'] + if scale not in scales: + msg = f'scale must be one of {scales}, but {scale} was passed.' + raise ValueError(msg) + self.scale = scale + + if ((outlier_prop > 1) or (outlier_prop <= 0)): + msg = f'outlier_prop {outlier_prop} not in range (0, 1]' + raise ValueError(msg) + self.outlier_prop = outlier_prop + + if not 0 < trust_alpha < 1: + msg = f'trust_alpha {trust_alpha} not in range (0, 1)' + raise ValueError(msg) + self.trust_alpha = trust_alpha + + self.showfliers = showfliers + + self.establish_variables(x, y, hue, data, orient, order, hue_order) + self.establish_colors(color, palette, saturation) + + def _lv_box_ends(self, vals): + """Get the number of data points and calculate `depth` of + letter-value plot.""" + vals = np.asarray(vals) + # Remove infinite values while handling a 'object' dtype + # that can come from pd.Float64Dtype() input + with pd.option_context('mode.use_inf_as_na', True): + vals = vals[~pd.isnull(vals)] + n = len(vals) + p = self.outlier_prop + + # Select the depth, i.e. number of boxes to draw, based on the method + if self.k_depth == 'full': + # extend boxes to 100% of the data + k = int(np.log2(n)) + 1 + elif self.k_depth == 'tukey': + # This results with 5-8 points in each tail + k = int(np.log2(n)) - 3 + elif self.k_depth == 'proportion': + k = int(np.log2(n)) - int(np.log2(n * p)) + 1 + elif self.k_depth == 'trustworthy': + point_conf = 2 * _normal_quantile_func(1 - self.trust_alpha / 2) ** 2 + k = int(np.log2(n / point_conf)) + 1 + else: + k = int(self.k_depth) # allow having k as input + # If the number happens to be less than 1, set k to 1 + if k < 1: + k = 1 + + # Calculate the upper end for each of the k boxes + upper = [100 * (1 - 0.5 ** (i + 1)) for i in range(k, 0, -1)] + # Calculate the lower end for each of the k boxes + lower = [100 * (0.5 ** (i + 1)) for i in range(k, 0, -1)] + # Stitch the box ends together + percentile_ends = [(i, j) for i, j in zip(lower, upper)] + box_ends = [np.percentile(vals, q) for q in percentile_ends] + return box_ends, k + + def _lv_outliers(self, vals, k): + """Find the outliers based on the letter value depth.""" + box_edge = 0.5 ** (k + 1) + perc_ends = (100 * box_edge, 100 * (1 - box_edge)) + edges = np.percentile(vals, perc_ends) + lower_out = vals[np.where(vals < edges[0])[0]] + upper_out = vals[np.where(vals > edges[1])[0]] + return np.concatenate((lower_out, upper_out)) + + def _width_functions(self, width_func): + # Dictionary of functions for computing the width of the boxes + width_functions = {'linear': lambda h, i, k: (i + 1.) / k, + 'exponential': lambda h, i, k: 2**(-k + i - 1), + 'area': lambda h, i, k: (1 - 2**(-k + i - 2)) / h} + return width_functions[width_func] + + def _lvplot(self, box_data, positions, + color=[255. / 256., 185. / 256., 0.], + widths=1, ax=None, box_kws=None, + flier_kws=None, + line_kws=None): + + # -- Default keyword dicts - based on + # distributions.plot_univariate_histogram + box_kws = {} if box_kws is None else box_kws.copy() + flier_kws = {} if flier_kws is None else flier_kws.copy() + line_kws = {} if line_kws is None else line_kws.copy() + + # Set the default kwargs for the boxes + box_default_kws = dict(edgecolor=self.gray, + linewidth=self.linewidth) + for k, v in box_default_kws.items(): + box_kws.setdefault(k, v) + + # Set the default kwargs for the lines denoting medians + line_default_kws = dict( + color=".15", alpha=0.45, solid_capstyle="butt", linewidth=self.linewidth + ) + for k, v in line_default_kws.items(): + line_kws.setdefault(k, v) + + # Set the default kwargs for the outliers scatterplot + flier_default_kws = dict(marker='d', color=self.gray) + for k, v in flier_default_kws.items(): + flier_kws.setdefault(k, v) + + vert = self.orient == "v" + x = positions[0] + box_data = np.asarray(box_data) + + # If we only have one data point, plot a line + if len(box_data) == 1: + line_kws.update({ + 'color': box_kws['edgecolor'], + 'linestyle': box_kws.get('linestyle', '-'), + 'linewidth': max(box_kws["linewidth"], line_kws["linewidth"]) + }) + ys = [box_data[0], box_data[0]] + xs = [x - widths / 2, x + widths / 2] + if vert: + xx, yy = xs, ys + else: + xx, yy = ys, xs + ax.plot(xx, yy, **line_kws) + else: + # Get the number of data points and calculate "depth" of + # letter-value plot + box_ends, k = self._lv_box_ends(box_data) + + # Anonymous functions for calculating the width and height + # of the letter value boxes + width = self._width_functions(self.scale) + + # Function to find height of boxes + def height(b): + return b[1] - b[0] + + # Functions to construct the letter value boxes + def vert_perc_box(x, b, i, k, w): + rect = Patches.Rectangle((x - widths * w / 2, b[0]), + widths * w, + height(b), fill=True) + return rect + + def horz_perc_box(x, b, i, k, w): + rect = Patches.Rectangle((b[0], x - widths * w / 2), + height(b), widths * w, + fill=True) + return rect + + # Scale the width of the boxes so the biggest starts at 1 + w_area = np.array([width(height(b), i, k) + for i, b in enumerate(box_ends)]) + w_area = w_area / np.max(w_area) + + # Calculate the medians + y = np.median(box_data) + + # Calculate the outliers and plot (only if showfliers == True) + outliers = [] + if self.showfliers: + outliers = self._lv_outliers(box_data, k) + hex_color = mpl.colors.rgb2hex(color) + + if vert: + box_func = vert_perc_box + xs_median = [x - widths / 2, x + widths / 2] + ys_median = [y, y] + xs_outliers = np.full(len(outliers), x) + ys_outliers = outliers + + else: + box_func = horz_perc_box + xs_median = [y, y] + ys_median = [x - widths / 2, x + widths / 2] + xs_outliers = outliers + ys_outliers = np.full(len(outliers), x) + + # Plot the medians + ax.plot( + xs_median, + ys_median, + **line_kws + ) + + # Plot outliers (if any) + if len(outliers) > 0: + ax.scatter(xs_outliers, ys_outliers, + **flier_kws + ) + + # Construct a color map from the input color + rgb = [hex_color, (1, 1, 1)] + cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb) + # Make sure that the last boxes contain hue and are not pure white + rgb = [hex_color, cmap(.85)] + cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb) + + # Update box_kws with `cmap` if not defined in dict until now + box_kws.setdefault('cmap', cmap) + + boxes = [box_func(x, b[0], i, k, b[1]) + for i, b in enumerate(zip(box_ends, w_area))] + + collection = PatchCollection(boxes, **box_kws) + + # Set the color gradation, first box will have color=hex_color + collection.set_array(np.array(np.linspace(1, 0, len(boxes)))) + + # Plot the boxes + ax.add_collection(collection) + + def draw_letter_value_plot(self, ax, box_kws=None, flier_kws=None, + line_kws=None): + """Use matplotlib to draw a letter value plot on an Axes.""" + + for i, group_data in enumerate(self.plot_data): + + if self.plot_hues is None: + + # Handle case where there is data at this level + if group_data.size == 0: + continue + + # Draw a single box or a set of boxes + # with a single level of grouping + box_data = remove_na(group_data) + + # Handle case where there is no non-null data + if box_data.size == 0: + continue + + color = self.colors[i] + + self._lvplot(box_data, + positions=[i], + color=color, + widths=self.width, + ax=ax, + box_kws=box_kws, + flier_kws=flier_kws, + line_kws=line_kws) + + else: + # Draw nested groups of boxes + offsets = self.hue_offsets + for j, hue_level in enumerate(self.hue_names): + + # Add a legend for this hue level + if not i: + self.add_legend_data(ax, self.colors[j], hue_level) + + # Handle case where there is data at this level + if group_data.size == 0: + continue + + hue_mask = self.plot_hues[i] == hue_level + box_data = remove_na(group_data[hue_mask]) + + # Handle case where there is no non-null data + if box_data.size == 0: + continue + + color = self.colors[j] + center = i + offsets[j] + self._lvplot(box_data, + positions=[center], + color=color, + widths=self.nested_width, + ax=ax, + box_kws=box_kws, + flier_kws=flier_kws, + line_kws=line_kws) + + # Autoscale the values axis to make sure all patches are visible + ax.autoscale_view(scalex=self.orient == "h", scaley=self.orient == "v") + + def plot(self, ax, box_kws, flier_kws, line_kws): + """Make the plot.""" + self.draw_letter_value_plot(ax, box_kws, flier_kws, line_kws) + self.annotate_axes(ax) + if self.orient == "h": + ax.invert_yaxis() + + +_categorical_docs = dict( + + # Shared narrative docs + categorical_narrative=dedent("""\ + .. note:: + This function always treats one of the variables as categorical and + draws data at ordinal positions (0, 1, ... n) on the relevant axis, + even when the data has a numeric or date type. + + See the :ref:`tutorial ` for more information.\ + """), + + new_categorical_narrative=dedent("""\ + .. note:: + By default, this function treats one of the variables as categorical + and draws data at ordinal positions (0, 1, ... n) on the relevant axis. + This can be disabled with the `native_scale` parameter. + + See the :ref:`tutorial ` for more information.\ + """), + + # Shared function parameters + input_params=dedent("""\ + x, y, hue : names of variables in ``data`` or vector data, optional + Inputs for plotting long-form data. See examples for interpretation.\ + """), + string_input_params=dedent("""\ + x, y, hue : names of variables in ``data`` + Inputs for plotting long-form data. See examples for interpretation.\ + """), + categorical_data=dedent("""\ + data : DataFrame, array, or list of arrays, optional + Dataset for plotting. If ``x`` and ``y`` are absent, this is + interpreted as wide-form. Otherwise it is expected to be long-form.\ + """), + long_form_data=dedent("""\ + data : DataFrame + Long-form (tidy) dataset for plotting. Each column should correspond + to a variable, and each row should correspond to an observation.\ + """), + order_vars=dedent("""\ + order, hue_order : lists of strings, optional + Order to plot the categorical levels in; otherwise the levels are + inferred from the data objects.\ + """), + stat_api_params=dedent("""\ + estimator : string or callable that maps vector -> scalar, optional + Statistical function to estimate within each categorical bin. + errorbar : string, (string, number) tuple, callable or None + Name of errorbar method (either "ci", "pi", "se", or "sd"), or a tuple + with a method name and a level parameter, or a function that maps from a + vector to a (min, max) interval, or None to hide errorbar. + n_boot : int, optional + Number of bootstrap samples used to compute confidence intervals. + units : name of variable in ``data`` or vector data, optional + Identifier of sampling units, which will be used to perform a + multilevel bootstrap and account for repeated measures design. + seed : int, numpy.random.Generator, or numpy.random.RandomState, optional + Seed or random number generator for reproducible bootstrapping.\ + """), + orient=dedent("""\ + orient : "v" | "h", optional + Orientation of the plot (vertical or horizontal). This is usually + inferred based on the type of the input variables, but it can be used + to resolve ambiguity when both `x` and `y` are numeric or when + plotting wide-form data.\ + """), + color=dedent("""\ + color : matplotlib color, optional + Single color for the elements in the plot.\ + """), + palette=dedent("""\ + palette : palette name, list, or dict, optional + Color palette that maps the hue variable. If the palette is a dictionary, + keys should be names of levels and values should be matplotlib colors.\ + """), + hue_norm=dedent("""\ + hue_norm : tuple or :class:`matplotlib.colors.Normalize` object + Normalization in data units for colormap applied to the `hue` + variable when it is numeric. Not relevant if `hue` is categorical.\ + """), + saturation=dedent("""\ + saturation : float, optional + Proportion of the original saturation to draw colors at. Large patches + often look better with slightly desaturated colors, but set this to + `1` if you want the plot colors to perfectly match the input color.\ + """), + capsize=dedent("""\ + capsize : float, optional + Width of the "caps" on error bars.\ + """), + errwidth=dedent("""\ + errwidth : float, optional + Thickness of error bar lines (and caps).\ + """), + width=dedent("""\ + width : float, optional + Width of a full element when not using hue nesting, or width of all the + elements for one level of the major grouping variable.\ + """), + dodge=dedent("""\ + dodge : bool, optional + When hue nesting is used, whether elements should be shifted along the + categorical axis.\ + """), + linewidth=dedent("""\ + linewidth : float, optional + Width of the gray lines that frame the plot elements.\ + """), + native_scale=dedent("""\ + native_scale : bool, optional + When True, numeric or datetime values on the categorical axis will maintain + their original scaling rather than being converted to fixed indices.\ + """), + formatter=dedent("""\ + formatter : callable, optional + Function for converting categorical data into strings. Affects both grouping + and tick labels.\ + """), + legend=dedent("""\ +legend : "auto", "brief", "full", or False + How to draw the legend. If "brief", numeric `hue` and `size` + variables will be represented with a sample of evenly spaced values. + If "full", every group will get an entry in the legend. If "auto", + choose between brief or full representation based on number of levels. + If `False`, no legend data is added and no legend is drawn. + """), + ax_in=dedent("""\ + ax : matplotlib Axes, optional + Axes object to draw the plot onto, otherwise uses the current Axes.\ + """), + ax_out=dedent("""\ + ax : matplotlib Axes + Returns the Axes object with the plot drawn onto it.\ + """), + + # Shared see also + boxplot=dedent("""\ + boxplot : A traditional box-and-whisker plot with a similar API.\ + """), + violinplot=dedent("""\ + violinplot : A combination of boxplot and kernel density estimation.\ + """), + stripplot=dedent("""\ + stripplot : A scatterplot where one variable is categorical. Can be used + in conjunction with other plots to show each observation.\ + """), + swarmplot=dedent("""\ + swarmplot : A categorical scatterplot where the points do not overlap. Can + be used with other plots to show each observation.\ + """), + barplot=dedent("""\ + barplot : Show point estimates and confidence intervals using bars.\ + """), + countplot=dedent("""\ + countplot : Show the counts of observations in each categorical bin.\ + """), + pointplot=dedent("""\ + pointplot : Show point estimates and confidence intervals using scatterplot + glyphs.\ + """), + catplot=dedent("""\ + catplot : Combine a categorical plot with a :class:`FacetGrid`.\ + """), + boxenplot=dedent("""\ + boxenplot : An enhanced boxplot for larger datasets.\ + """), + +) + +_categorical_docs.update(_facet_docs) + + +def boxplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + orient=None, color=None, palette=None, saturation=.75, width=.8, + dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, + **kwargs +): + + plotter = _BoxPlotter(x, y, hue, data, order, hue_order, + orient, color, palette, saturation, + width, dodge, fliersize, linewidth) + + if ax is None: + ax = plt.gca() + kwargs.update(dict(whis=whis)) + + plotter.plot(ax, kwargs) + return ax + + +boxplot.__doc__ = dedent("""\ + Draw a box plot to show distributions with respect to categories. + + A box plot (or box-and-whisker plot) shows the distribution of quantitative + data in a way that facilitates comparisons between variables or across + levels of a categorical variable. The box shows the quartiles of the + dataset while the whiskers extend to show the rest of the distribution, + except for points that are determined to be "outliers" using a method + that is a function of the inter-quartile range. + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + {orient} + {color} + {palette} + {saturation} + {width} + {dodge} + fliersize : float, optional + Size of the markers used to indicate outlier observations. + {linewidth} + whis : float, optional + Maximum length of the plot whiskers as proportion of the + interquartile range. Whiskers extend to the furthest datapoint + within that range. More extreme points are marked as outliers. + {ax_in} + kwargs : key, value mappings + Other keyword arguments are passed through to + :meth:`matplotlib.axes.Axes.boxplot`. + + Returns + ------- + {ax_out} + + See Also + -------- + {violinplot} + {stripplot} + {swarmplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/boxplot.rst + + """).format(**_categorical_docs) + + +def violinplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + bw="scott", cut=2, scale="area", scale_hue=True, gridsize=100, + width=.8, inner="box", split=False, dodge=True, orient=None, + linewidth=None, color=None, palette=None, saturation=.75, + ax=None, **kwargs, +): + + plotter = _ViolinPlotter(x, y, hue, data, order, hue_order, + bw, cut, scale, scale_hue, gridsize, + width, inner, split, dodge, orient, linewidth, + color, palette, saturation) + + if ax is None: + ax = plt.gca() + + plotter.plot(ax) + return ax + + +violinplot.__doc__ = dedent("""\ + Draw a combination of boxplot and kernel density estimate. + + A violin plot plays a similar role as a box and whisker plot. It shows the + distribution of quantitative data across several levels of one (or more) + categorical variables such that those distributions can be compared. Unlike + a box plot, in which all of the plot components correspond to actual + datapoints, the violin plot features a kernel density estimation of the + underlying distribution. + + This can be an effective and attractive way to show multiple distributions + of data at once, but keep in mind that the estimation procedure is + influenced by the sample size, and violins for relatively small samples + might look misleadingly smooth. + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + bw : {{'scott', 'silverman', float}}, optional + Either the name of a reference rule or the scale factor to use when + computing the kernel bandwidth. The actual kernel size will be + determined by multiplying the scale factor by the standard deviation of + the data within each bin. + cut : float, optional + Distance, in units of bandwidth size, to extend the density past the + extreme datapoints. Set to 0 to limit the violin range within the range + of the observed data (i.e., to have the same effect as ``trim=True`` in + ``ggplot``. + scale : {{"area", "count", "width"}}, optional + The method used to scale the width of each violin. If ``area``, each + violin will have the same area. If ``count``, the width of the violins + will be scaled by the number of observations in that bin. If ``width``, + each violin will have the same width. + scale_hue : bool, optional + When nesting violins using a ``hue`` variable, this parameter + determines whether the scaling is computed within each level of the + major grouping variable (``scale_hue=True``) or across all the violins + on the plot (``scale_hue=False``). + gridsize : int, optional + Number of points in the discrete grid used to compute the kernel + density estimate. + {width} + inner : {{"box", "quartile", "point", "stick", None}}, optional + Representation of the datapoints in the violin interior. If ``box``, + draw a miniature boxplot. If ``quartiles``, draw the quartiles of the + distribution. If ``point`` or ``stick``, show each underlying + datapoint. Using ``None`` will draw unadorned violins. + split : bool, optional + When using hue nesting with a variable that takes two levels, setting + ``split`` to True will draw half of a violin for each level. This can + make it easier to directly compare the distributions. + {dodge} + {orient} + {linewidth} + {color} + {palette} + {saturation} + {ax_in} + + Returns + ------- + {ax_out} + + See Also + -------- + {boxplot} + {stripplot} + {swarmplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/violinplot.rst + + """).format(**_categorical_docs) + + +def boxenplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + orient=None, color=None, palette=None, saturation=.75, + width=.8, dodge=True, k_depth='tukey', linewidth=None, + scale='exponential', outlier_prop=0.007, trust_alpha=0.05, + showfliers=True, + ax=None, box_kws=None, flier_kws=None, line_kws=None, +): + plotter = _LVPlotter(x, y, hue, data, order, hue_order, + orient, color, palette, saturation, + width, dodge, k_depth, linewidth, scale, + outlier_prop, trust_alpha, showfliers) + + if ax is None: + ax = plt.gca() + + plotter.plot(ax, box_kws, flier_kws, line_kws) + return ax + + +boxenplot.__doc__ = dedent("""\ + Draw an enhanced box plot for larger datasets. + + This style of plot was originally named a "letter value" plot because it + shows a large number of quantiles that are defined as "letter values". It + is similar to a box plot in plotting a nonparametric representation of a + distribution in which all features correspond to actual observations. By + plotting more quantiles, it provides more information about the shape of + the distribution, particularly in the tails. For a more extensive + explanation, you can read the paper that introduced the plot: + https://vita.had.co.nz/papers/letter-value-plot.html + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + {orient} + {color} + {palette} + {saturation} + {width} + {dodge} + k_depth : {{"tukey", "proportion", "trustworthy", "full"}} or scalar + The number of boxes, and by extension number of percentiles, to draw. + All methods are detailed in Wickham's paper. Each makes different + assumptions about the number of outliers and leverages different + statistical properties. If "proportion", draw no more than + `outlier_prop` extreme observations. If "full", draw `log(n)+1` boxes. + {linewidth} + scale : {{"exponential", "linear", "area"}}, optional + Method to use for the width of the letter value boxes. All give similar + results visually. "linear" reduces the width by a constant linear + factor, "exponential" uses the proportion of data not covered, "area" + is proportional to the percentage of data covered. + outlier_prop : float, optional + Proportion of data believed to be outliers. Must be in the range + (0, 1]. Used to determine the number of boxes to plot when + `k_depth="proportion"`. + trust_alpha : float, optional + Confidence level for a box to be plotted. Used to determine the + number of boxes to plot when `k_depth="trustworthy"`. Must be in the + range (0, 1). + showfliers : bool, optional + If False, suppress the plotting of outliers. + {ax_in} + box_kws: dict, optional + Keyword arguments for the box artists; passed to + :class:`matplotlib.patches.Rectangle`. + line_kws: dict, optional + Keyword arguments for the line denoting the median; passed to + :meth:`matplotlib.axes.Axes.plot`. + flier_kws: dict, optional + Keyword arguments for the scatter denoting the outlier observations; + passed to :meth:`matplotlib.axes.Axes.scatter`. + + Returns + ------- + {ax_out} + + See Also + -------- + {violinplot} + {boxplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/boxenplot.rst + + """).format(**_categorical_docs) + + +def stripplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + jitter=True, dodge=False, orient=None, color=None, palette=None, + size=5, edgecolor="gray", linewidth=0, + hue_norm=None, native_scale=False, formatter=None, legend="auto", + ax=None, **kwargs +): + + p = _CategoricalPlotterNew( + data=data, + variables=_CategoricalPlotterNew.get_semantics(locals()), + order=order, + orient=orient, + require_numeric=False, + legend=legend, + ) + + if ax is None: + ax = plt.gca() + + if p.var_types.get(p.cat_axis) == "categorical" or not native_scale: + p.scale_categorical(p.cat_axis, order=order, formatter=formatter) + + p._attach(ax) + + hue_order = p._palette_without_hue_backcompat(palette, hue_order) + palette, hue_order = p._hue_backcompat(color, palette, hue_order) + + color = _default_color(ax.scatter, hue, color, kwargs) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + # XXX Copying possibly bad default decisions from original code for now + kwargs.setdefault("zorder", 3) + size = kwargs.get("s", size) + + kwargs.update(dict( + s=size ** 2, + edgecolor=edgecolor, + linewidth=linewidth) + ) + + p.plot_strips( + jitter=jitter, + dodge=dodge, + color=color, + edgecolor=edgecolor, + plot_kws=kwargs, + ) + + # XXX this happens inside a plotting method in the distribution plots + # but maybe it's better out here? Alternatively, we have an open issue + # suggesting that _attach could add default axes labels, which seems smart. + p._add_axis_labels(ax) + p._adjust_cat_axis(ax, axis=p.cat_axis) + + return ax + + +stripplot.__doc__ = dedent("""\ + Draw a categorical scatterplot using jitter to reduce overplotting. + + A strip plot can be drawn on its own, but it is also a good complement + to a box or violin plot in cases where you want to show all observations + along with some representation of the underlying distribution. + + {new_categorical_narrative} + + Parameters + ---------- + {input_params} + {categorical_data} + {order_vars} + jitter : float, ``True``/``1`` is special-cased, optional + Amount of jitter (only along the categorical axis) to apply. This + can be useful when you have many points and they overlap, so that + it is easier to see the distribution. You can specify the amount + of jitter (half the width of the uniform random variable support), + or just use ``True`` for a good default. + dodge : bool, optional + When using ``hue`` nesting, setting this to ``True`` will separate + the strips for different hue levels along the categorical axis. + Otherwise, the points for each level will be plotted on top of + each other. + {orient} + {color} + {palette} + size : float, optional + Radius of the markers, in points. + edgecolor : matplotlib color, "gray" is special-cased, optional + Color of the lines around each point. If you pass ``"gray"``, the + brightness is determined by the color palette used for the body + of the points. Note that `stripplot` has `linewidth=0` by default, + so edge colors are only visible with nonzero line width. + {linewidth} + {native_scale} + {formatter} + {legend} + {ax_in} + kwargs : key, value mappings + Other keyword arguments are passed through to + :meth:`matplotlib.axes.Axes.scatter`. + + Returns + ------- + {ax_out} + + See Also + -------- + {swarmplot} + {boxplot} + {violinplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/stripplot.rst + + """).format(**_categorical_docs) + + +def swarmplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + dodge=False, orient=None, color=None, palette=None, + size=5, edgecolor="gray", linewidth=0, hue_norm=None, + native_scale=False, formatter=None, legend="auto", warn_thresh=.05, + ax=None, **kwargs +): + + p = _CategoricalPlotterNew( + data=data, + variables=_CategoricalPlotterNew.get_semantics(locals()), + order=order, + orient=orient, + require_numeric=False, + legend=legend, + ) + + if ax is None: + ax = plt.gca() + + if p.var_types.get(p.cat_axis) == "categorical" or not native_scale: + p.scale_categorical(p.cat_axis, order=order, formatter=formatter) + + p._attach(ax) + + if not p.has_xy_data: + return ax + + hue_order = p._palette_without_hue_backcompat(palette, hue_order) + palette, hue_order = p._hue_backcompat(color, palette, hue_order) + + color = _default_color(ax.scatter, hue, color, kwargs) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + # XXX Copying possibly bad default decisions from original code for now + kwargs.setdefault("zorder", 3) + size = kwargs.get("s", size) + + if linewidth is None: + linewidth = size / 10 + + kwargs.update(dict( + s=size ** 2, + linewidth=linewidth, + )) + + p.plot_swarms( + dodge=dodge, + color=color, + edgecolor=edgecolor, + warn_thresh=warn_thresh, + plot_kws=kwargs, + ) + + p._add_axis_labels(ax) + p._adjust_cat_axis(ax, axis=p.cat_axis) + + return ax + + +swarmplot.__doc__ = dedent("""\ + Draw a categorical scatterplot with points adjusted to be non-overlapping. + + This function is similar to :func:`stripplot`, but the points are adjusted + (only along the categorical axis) so that they don't overlap. This gives a + better representation of the distribution of values, but it does not scale + well to large numbers of observations. This style of plot is sometimes + called a "beeswarm". + + A swarm plot can be drawn on its own, but it is also a good complement + to a box or violin plot in cases where you want to show all observations + along with some representation of the underlying distribution. + + {new_categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + dodge : bool, optional + When using ``hue`` nesting, setting this to ``True`` will separate + the strips for different hue levels along the categorical axis. + Otherwise, the points for each level will be plotted in one swarm. + {orient} + {color} + {palette} + size : float, optional + Radius of the markers, in points. + edgecolor : matplotlib color, "gray" is special-cased, optional + Color of the lines around each point. If you pass ``"gray"``, the + brightness is determined by the color palette used for the body + of the points. + {linewidth} + {native_scale} + {formatter} + {legend} + {ax_in} + kwargs : key, value mappings + Other keyword arguments are passed through to + :meth:`matplotlib.axes.Axes.scatter`. + + Returns + ------- + {ax_out} + + See Also + -------- + {boxplot} + {violinplot} + {stripplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/swarmplot.rst + + """).format(**_categorical_docs) + + +def barplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + estimator="mean", errorbar=("ci", 95), n_boot=1000, units=None, seed=None, + orient=None, color=None, palette=None, saturation=.75, width=.8, + errcolor=".26", errwidth=None, capsize=None, dodge=True, ci="deprecated", + ax=None, + **kwargs, +): + + errorbar = utils._deprecate_ci(errorbar, ci) + + # Be backwards compatible with len passed directly, which + # does not work in Series.agg (maybe a pandas bug?) + if estimator is len: + estimator = "size" + + plotter = _BarPlotter(x, y, hue, data, order, hue_order, + estimator, errorbar, n_boot, units, seed, + orient, color, palette, saturation, + width, errcolor, errwidth, capsize, dodge) + + if ax is None: + ax = plt.gca() + + plotter.plot(ax, kwargs) + return ax + + +barplot.__doc__ = dedent("""\ + Show point estimates and errors as rectangular bars. + + A bar plot represents an estimate of central tendency for a numeric + variable with the height of each rectangle and provides some indication of + the uncertainty around that estimate using error bars. Bar plots include 0 + in the quantitative axis range, and they are a good choice when 0 is a + meaningful value for the quantitative variable, and you want to make + comparisons against it. + + For datasets where 0 is not a meaningful value, a point plot will allow you + to focus on differences between levels of one or more categorical + variables. + + It is also important to keep in mind that a bar plot shows only the mean + (or other estimator) value, but in many cases it may be more informative to + show the distribution of values at each level of the categorical variables. + In that case, other approaches such as a box or violin plot may be more + appropriate. + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + {stat_api_params} + {orient} + {color} + {palette} + {saturation} + {width} + errcolor : matplotlib color + Color used for the error bar lines. + {errwidth} + {capsize} + {dodge} + {ax_in} + kwargs : key, value mappings + Other keyword arguments are passed through to + :meth:`matplotlib.axes.Axes.bar`. + + Returns + ------- + {ax_out} + + See Also + -------- + {countplot} + {pointplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/barplot.rst + + + """).format(**_categorical_docs) + + +def pointplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + estimator="mean", errorbar=("ci", 95), n_boot=1000, units=None, seed=None, + markers="o", linestyles="-", dodge=False, join=True, scale=1, + orient=None, color=None, palette=None, errwidth=None, ci="deprecated", + capsize=None, label=None, ax=None, +): + + errorbar = utils._deprecate_ci(errorbar, ci) + + plotter = _PointPlotter(x, y, hue, data, order, hue_order, + estimator, errorbar, n_boot, units, seed, + markers, linestyles, dodge, join, scale, + orient, color, palette, errwidth, capsize, label) + + if ax is None: + ax = plt.gca() + + plotter.plot(ax) + return ax + + +pointplot.__doc__ = dedent("""\ + Show point estimates and errors using dot marks. + + A point plot represents an estimate of central tendency for a numeric + variable by the position of the dot and provides some indication of the + uncertainty around that estimate using error bars. + + Point plots can be more useful than bar plots for focusing comparisons + between different levels of one or more categorical variables. They are + particularly adept at showing interactions: how the relationship between + levels of one categorical variable changes across levels of a second + categorical variable. The lines that join each point from the same `hue` + level allow interactions to be judged by differences in slope, which is + easier for the eyes than comparing the heights of several groups of points + or bars. + + It is important to keep in mind that a point plot shows only the mean (or + other estimator) value, but in many cases it may be more informative to + show the distribution of values at each level of the categorical variables. + In that case, other approaches such as a box or violin plot may be more + appropriate. + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + {stat_api_params} + markers : string or list of strings, optional + Markers to use for each of the ``hue`` levels. + linestyles : string or list of strings, optional + Line styles to use for each of the ``hue`` levels. + dodge : bool or float, optional + Amount to separate the points for each level of the ``hue`` variable + along the categorical axis. + join : bool, optional + If ``True``, lines will be drawn between point estimates at the same + ``hue`` level. + scale : float, optional + Scale factor for the plot elements. + {orient} + {color} + {palette} + {errwidth} + {capsize} + label : string, optional + Label to represent the plot in a legend, only relevant when not using `hue`. + {ax_in} + + Returns + ------- + {ax_out} + + See Also + -------- + {barplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/pointplot.rst + + """).format(**_categorical_docs) + + +def countplot( + data=None, *, x=None, y=None, hue=None, order=None, hue_order=None, + orient=None, color=None, palette=None, saturation=.75, width=.8, + dodge=True, ax=None, **kwargs +): + + estimator = "size" + errorbar = None + n_boot = 0 + units = None + seed = None + errcolor = None + errwidth = None + capsize = None + + if x is None and y is not None: + orient = "h" + x = y + elif y is None and x is not None: + orient = "v" + y = x + elif x is not None and y is not None: + raise ValueError("Cannot pass values for both `x` and `y`") + + plotter = _CountPlotter( + x, y, hue, data, order, hue_order, + estimator, errorbar, n_boot, units, seed, + orient, color, palette, saturation, + width, errcolor, errwidth, capsize, dodge + ) + + plotter.value_label = "count" + + if ax is None: + ax = plt.gca() + + plotter.plot(ax, kwargs) + return ax + + +countplot.__doc__ = dedent("""\ + Show the counts of observations in each categorical bin using bars. + + A count plot can be thought of as a histogram across a categorical, instead + of quantitative, variable. The basic API and options are identical to those + for :func:`barplot`, so you can compare counts across nested variables. + + Note that the newer :func:`histplot` function offers more functionality, although + its default behavior is somewhat different. + + {categorical_narrative} + + Parameters + ---------- + {categorical_data} + {input_params} + {order_vars} + {orient} + {color} + {palette} + {saturation} + {dodge} + {ax_in} + kwargs : key, value mappings + Other keyword arguments are passed through to + :meth:`matplotlib.axes.Axes.bar`. + + Returns + ------- + {ax_out} + + See Also + -------- + {barplot} + {catplot} + + Examples + -------- + + .. include:: ../docstrings/countplot.rst + + """).format(**_categorical_docs) + + +def catplot( + data=None, *, x=None, y=None, hue=None, row=None, col=None, + col_wrap=None, estimator="mean", errorbar=("ci", 95), n_boot=1000, + units=None, seed=None, order=None, hue_order=None, row_order=None, + col_order=None, height=5, aspect=1, kind="strip", native_scale=False, + formatter=None, orient=None, color=None, palette=None, hue_norm=None, + legend="auto", legend_out=True, sharex=True, sharey=True, + margin_titles=False, facet_kws=None, ci="deprecated", + **kwargs +): + + # Determine the plotting function + try: + plot_func = globals()[kind + "plot"] + except KeyError: + err = f"Plot kind '{kind}' is not recognized" + raise ValueError(err) + + # Check for attempt to plot onto specific axes and warn + if "ax" in kwargs: + msg = ("catplot is a figure-level function and does not accept " + f"target axes. You may wish to try {kind}plot") + warnings.warn(msg, UserWarning) + kwargs.pop("ax") + + refactored_kinds = ["strip", "swarm"] + if kind in refactored_kinds: + + p = _CategoricalFacetPlotter( + data=data, + variables=_CategoricalFacetPlotter.get_semantics(locals()), + order=order, + orient=orient, + require_numeric=False, + legend=legend, + ) + + # XXX Copying a fair amount from displot, which is not ideal + + for var in ["row", "col"]: + # Handle faceting variables that lack name information + if var in p.variables and p.variables[var] is None: + p.variables[var] = f"_{var}_" + + # Adapt the plot_data dataframe for use with FacetGrid + data = p.plot_data.rename(columns=p.variables) + data = data.loc[:, ~data.columns.duplicated()] + + col_name = p.variables.get("col", None) + row_name = p.variables.get("row", None) + + if facet_kws is None: + facet_kws = {} + + g = FacetGrid( + data=data, row=row_name, col=col_name, + col_wrap=col_wrap, row_order=row_order, + col_order=col_order, height=height, + sharex=sharex, sharey=sharey, + aspect=aspect, + **facet_kws, + ) + + # Capture this here because scale_categorical is going to insert a (null) + # x variable even if it is empty. It's not clear whether that needs to + # happen or if disabling that is the cleaner solution. + has_xy_data = p.has_xy_data + + if not native_scale or p.var_types[p.cat_axis] == "categorical": + p.scale_categorical(p.cat_axis, order=order, formatter=formatter) + + p._attach(g) + + if not has_xy_data: + return g + + hue_order = p._palette_without_hue_backcompat(palette, hue_order) + palette, hue_order = p._hue_backcompat(color, palette, hue_order) + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + # Set a default color + # Otherwise each artist will be plotted separately and trip the color cycle + if hue is None and color is None: + color = "C0" + + if kind == "strip": + + # TODO get these defaults programmatically? + jitter = kwargs.pop("jitter", True) + dodge = kwargs.pop("dodge", False) + edgecolor = kwargs.pop("edgecolor", "gray") # XXX TODO default + + plot_kws = kwargs.copy() + + # XXX Copying possibly bad default decisions from original code for now + plot_kws.setdefault("zorder", 3) + plot_kws.setdefault("s", plot_kws.pop("size", 5) ** 2) + plot_kws.setdefault("linewidth", 0) + + p.plot_strips( + jitter=jitter, + dodge=dodge, + color=color, + edgecolor=edgecolor, + plot_kws=plot_kws, + ) + + elif kind == "swarm": + + # TODO get these defaults programmatically? + dodge = kwargs.pop("dodge", False) + edgecolor = kwargs.pop("edgecolor", "gray") # XXX TODO default + warn_thresh = kwargs.pop("warn_thresh", .05) + + plot_kws = kwargs.copy() + + # XXX Copying possibly bad default decisions from original code for now + plot_kws.setdefault("zorder", 3) + plot_kws.setdefault("s", plot_kws.pop("size", 5) ** 2) + + if plot_kws.setdefault("linewidth", 0) is None: + plot_kws["linewidth"] = np.sqrt(plot_kws["s"]) / 10 + + p.plot_swarms( + dodge=dodge, + color=color, + edgecolor=edgecolor, + warn_thresh=warn_thresh, + plot_kws=plot_kws, + ) + + # XXX best way to do this housekeeping? + for ax in g.axes.flat: + p._adjust_cat_axis(ax, axis=p.cat_axis) + + g.set_axis_labels( + p.variables.get("x", None), + p.variables.get("y", None), + ) + g.set_titles() + g.tight_layout() + + # XXX Hack to get the legend data in the right place + for ax in g.axes.flat: + g._update_legend_data(ax) + ax.legend_ = None + + if legend and (hue is not None) and (hue not in [x, row, col]): + g.add_legend(title=hue, label_order=hue_order) + + return g + + # Don't allow usage of forthcoming functionality + if native_scale is True: + err = f"native_scale not yet implemented for `kind={kind}`" + raise ValueError(err) + if formatter is not None: + err = f"formatter not yet implemented for `kind={kind}`" + raise ValueError(err) + + # Alias the input variables to determine categorical order and palette + # correctly in the case of a count plot + if kind == "count": + if x is None and y is not None: + x_, y_, orient = y, y, "h" + elif y is None and x is not None: + x_, y_, orient = x, x, "v" + else: + raise ValueError("Either `x` or `y` must be None for kind='count'") + else: + x_, y_ = x, y + + # Determine the order for the whole dataset, which will be used in all + # facets to ensure representation of all data in the final plot + plotter_class = { + "box": _BoxPlotter, + "violin": _ViolinPlotter, + "boxen": _LVPlotter, + "bar": _BarPlotter, + "point": _PointPlotter, + "count": _CountPlotter, + }[kind] + p = _CategoricalPlotter() + p.require_numeric = plotter_class.require_numeric + p.establish_variables(x_, y_, hue, data, orient, order, hue_order) + if ( + order is not None + or (sharex and p.orient == "v") + or (sharey and p.orient == "h") + ): + # Sync categorical axis between facets to have the same categories + order = p.group_names + elif color is None and hue is None: + msg = ( + "Setting `{}=False` with `color=None` may cause different levels of the " + "`{}` variable to share colors. This will change in a future version." + ) + if not sharex and p.orient == "v": + warnings.warn(msg.format("sharex", "x"), UserWarning) + if not sharey and p.orient == "h": + warnings.warn(msg.format("sharey", "y"), UserWarning) + + hue_order = p.hue_names + + # Determine the palette to use + # (FacetGrid will pass a value for ``color`` to the plotting function + # so we need to define ``palette`` to get default behavior for the + # categorical functions + p.establish_colors(color, palette, 1) + if kind != "point" or hue is not None: + palette = p.colors + + # Determine keyword arguments for the facets + facet_kws = {} if facet_kws is None else facet_kws + facet_kws.update( + data=data, row=row, col=col, + row_order=row_order, col_order=col_order, + col_wrap=col_wrap, height=height, aspect=aspect, + sharex=sharex, sharey=sharey, + legend_out=legend_out, margin_titles=margin_titles, + dropna=False, + ) + + # Determine keyword arguments for the plotting function + plot_kws = dict( + order=order, hue_order=hue_order, + orient=orient, color=color, palette=palette, + ) + plot_kws.update(kwargs) + + if kind in ["bar", "point"]: + errorbar = utils._deprecate_ci(errorbar, ci) + plot_kws.update( + estimator=estimator, errorbar=errorbar, + n_boot=n_boot, units=units, seed=seed, + ) + + # Initialize the facets + g = FacetGrid(**facet_kws) + + # Draw the plot onto the facets + g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws) + + if p.orient == "h": + g.set_axis_labels(p.value_label, p.group_label) + else: + g.set_axis_labels(p.group_label, p.value_label) + + # Special case axis labels for a count type plot + if kind == "count": + if x is None: + g.set_axis_labels(x_var="count") + if y is None: + g.set_axis_labels(y_var="count") + + if legend and (hue is not None) and (hue not in [x, row, col]): + hue_order = list(map(utils.to_utf8, hue_order)) + g.add_legend(title=hue, label_order=hue_order) + + return g + + +catplot.__doc__ = dedent("""\ + Figure-level interface for drawing categorical plots onto a FacetGrid. + + This function provides access to several axes-level functions that + show the relationship between a numerical and one or more categorical + variables using one of several visual representations. The `kind` + parameter selects the underlying axes-level function to use: + + Categorical scatterplots: + + - :func:`stripplot` (with `kind="strip"`; the default) + - :func:`swarmplot` (with `kind="swarm"`) + + Categorical distribution plots: + + - :func:`boxplot` (with `kind="box"`) + - :func:`violinplot` (with `kind="violin"`) + - :func:`boxenplot` (with `kind="boxen"`) + + Categorical estimate plots: + + - :func:`pointplot` (with `kind="point"`) + - :func:`barplot` (with `kind="bar"`) + - :func:`countplot` (with `kind="count"`) + + Extra keyword arguments are passed to the underlying function, so you + should refer to the documentation for each to see kind-specific options. + + Note that unlike when using the axes-level functions directly, data must be + passed in a long-form DataFrame with variables specified by passing strings + to `x`, `y`, `hue`, etc. + + {categorical_narrative} + + After plotting, the :class:`FacetGrid` with the plot is returned and can + be used directly to tweak supporting plot details or add other layers. + + Parameters + ---------- + {long_form_data} + {string_input_params} + row, col : names of variables in `data`, optional + Categorical variables that will determine the faceting of the grid. + {col_wrap} + {stat_api_params} + {order_vars} + row_order, col_order : lists of strings, optional + Order to organize the rows and/or columns of the grid in, otherwise the + orders are inferred from the data objects. + {height} + {aspect} + kind : str, optional + The kind of plot to draw, corresponds to the name of a categorical + axes-level plotting function. Options are: "strip", "swarm", "box", "violin", + "boxen", "point", "bar", or "count". + {native_scale} + {formatter} + {orient} + {color} + {palette} + {hue_norm} + legend : str or bool, optional + Set to `False` to disable the legend. With `strip` or `swarm` plots, + this also accepts a string, as described in the axes-level docstrings. + {legend_out} + {share_xy} + {margin_titles} + facet_kws : dict, optional + Dictionary of other keyword arguments to pass to :class:`FacetGrid`. + kwargs : key, value pairings + Other keyword arguments are passed through to the underlying plotting + function. + + Returns + ------- + g : :class:`FacetGrid` + Returns the :class:`FacetGrid` object with the plot on it for further + tweaking. + + Examples + -------- + + .. include:: ../docstrings/catplot.rst + + """).format(**_categorical_docs) + + +class Beeswarm: + """Modifies a scatterplot artist to show a beeswarm plot.""" + def __init__(self, orient="v", width=0.8, warn_thresh=.05): + + # XXX should we keep the orient parameterization or specify the swarm axis? + + self.orient = orient + self.width = width + self.warn_thresh = warn_thresh + + def __call__(self, points, center): + """Swarm `points`, a PathCollection, around the `center` position.""" + # Convert from point size (area) to diameter + + ax = points.axes + dpi = ax.figure.dpi + + # Get the original positions of the points + orig_xy_data = points.get_offsets() + + # Reset the categorical positions to the center line + cat_idx = 1 if self.orient == "h" else 0 + orig_xy_data[:, cat_idx] = center + + # Transform the data coordinates to point coordinates. + # We'll figure out the swarm positions in the latter + # and then convert back to data coordinates and replot + orig_x_data, orig_y_data = orig_xy_data.T + orig_xy = ax.transData.transform(orig_xy_data) + + # Order the variables so that x is the categorical axis + if self.orient == "h": + orig_xy = orig_xy[:, [1, 0]] + + # Add a column with each point's radius + sizes = points.get_sizes() + if sizes.size == 1: + sizes = np.repeat(sizes, orig_xy.shape[0]) + edge = points.get_linewidth().item() + radii = (np.sqrt(sizes) + edge) / 2 * (dpi / 72) + orig_xy = np.c_[orig_xy, radii] + + # Sort along the value axis to facilitate the beeswarm + sorter = np.argsort(orig_xy[:, 1]) + orig_xyr = orig_xy[sorter] + + # Adjust points along the categorical axis to prevent overlaps + new_xyr = np.empty_like(orig_xyr) + new_xyr[sorter] = self.beeswarm(orig_xyr) + + # Transform the point coordinates back to data coordinates + if self.orient == "h": + new_xy = new_xyr[:, [1, 0]] + else: + new_xy = new_xyr[:, :2] + new_x_data, new_y_data = ax.transData.inverted().transform(new_xy).T + + swarm_axis = {"h": "y", "v": "x"}[self.orient] + log_scale = getattr(ax, f"get_{swarm_axis}scale")() == "log" + + # Add gutters + if self.orient == "h": + self.add_gutters(new_y_data, center, log_scale=log_scale) + else: + self.add_gutters(new_x_data, center, log_scale=log_scale) + + # Reposition the points so they do not overlap + if self.orient == "h": + points.set_offsets(np.c_[orig_x_data, new_y_data]) + else: + points.set_offsets(np.c_[new_x_data, orig_y_data]) + + def beeswarm(self, orig_xyr): + """Adjust x position of points to avoid overlaps.""" + # In this method, `x` is always the categorical axis + # Center of the swarm, in point coordinates + midline = orig_xyr[0, 0] + + # Start the swarm with the first point + swarm = np.atleast_2d(orig_xyr[0]) + + # Loop over the remaining points + for xyr_i in orig_xyr[1:]: + + # Find the points in the swarm that could possibly + # overlap with the point we are currently placing + neighbors = self.could_overlap(xyr_i, swarm) + + # Find positions that would be valid individually + # with respect to each of the swarm neighbors + candidates = self.position_candidates(xyr_i, neighbors) + + # Sort candidates by their centrality + offsets = np.abs(candidates[:, 0] - midline) + candidates = candidates[np.argsort(offsets)] + + # Find the first candidate that does not overlap any neighbors + new_xyr_i = self.first_non_overlapping_candidate(candidates, neighbors) + + # Place it into the swarm + swarm = np.vstack([swarm, new_xyr_i]) + + return swarm + + def could_overlap(self, xyr_i, swarm): + """Return a list of all swarm points that could overlap with target.""" + # Because we work backwards through the swarm and can short-circuit, + # the for-loop is faster than vectorization + _, y_i, r_i = xyr_i + neighbors = [] + for xyr_j in reversed(swarm): + _, y_j, r_j = xyr_j + if (y_i - y_j) < (r_i + r_j): + neighbors.append(xyr_j) + else: + break + return np.array(neighbors)[::-1] + + def position_candidates(self, xyr_i, neighbors): + """Return a list of coordinates that might be valid by adjusting x.""" + candidates = [xyr_i] + x_i, y_i, r_i = xyr_i + left_first = True + for x_j, y_j, r_j in neighbors: + dy = y_i - y_j + dx = np.sqrt(max((r_i + r_j) ** 2 - dy ** 2, 0)) * 1.05 + cl, cr = (x_j - dx, y_i, r_i), (x_j + dx, y_i, r_i) + if left_first: + new_candidates = [cl, cr] + else: + new_candidates = [cr, cl] + candidates.extend(new_candidates) + left_first = not left_first + return np.array(candidates) + + def first_non_overlapping_candidate(self, candidates, neighbors): + """Find the first candidate that does not overlap with the swarm.""" + + # If we have no neighbors, all candidates are good. + if len(neighbors) == 0: + return candidates[0] + + neighbors_x = neighbors[:, 0] + neighbors_y = neighbors[:, 1] + neighbors_r = neighbors[:, 2] + + for xyr_i in candidates: + + x_i, y_i, r_i = xyr_i + + dx = neighbors_x - x_i + dy = neighbors_y - y_i + sq_distances = np.square(dx) + np.square(dy) + + sep_needed = np.square(neighbors_r + r_i) + + # Good candidate does not overlap any of neighbors which means that + # squared distance between candidate and any of the neighbors has + # to be at least square of the summed radii + good_candidate = np.all(sq_distances >= sep_needed) + + if good_candidate: + return xyr_i + + raise RuntimeError( + "No non-overlapping candidates found. This should not happen." + ) + + def add_gutters(self, points, center, log_scale=False): + """Stop points from extending beyond their territory.""" + half_width = self.width / 2 + if log_scale: + low_gutter = 10 ** (np.log10(center) - half_width) + else: + low_gutter = center - half_width + off_low = points < low_gutter + if off_low.any(): + points[off_low] = low_gutter + if log_scale: + high_gutter = 10 ** (np.log10(center) + half_width) + else: + high_gutter = center + half_width + off_high = points > high_gutter + if off_high.any(): + points[off_high] = high_gutter + + gutter_prop = (off_high + off_low).sum() / len(points) + if gutter_prop > self.warn_thresh: + msg = ( + "{:.1%} of the points cannot be placed; you may want " + "to decrease the size of the markers or use stripplot." + ).format(gutter_prop) + warnings.warn(msg, UserWarning) + + return points diff --git a/testbed/mwaskom__seaborn/seaborn/cm.py b/testbed/mwaskom__seaborn/seaborn/cm.py new file mode 100644 index 0000000000000000000000000000000000000000..df7ce61997882d7d7f734052292438e4234a5cc7 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/cm.py @@ -0,0 +1,1586 @@ +from matplotlib import colors +from seaborn._compat import register_colormap + + +_rocket_lut = [ + [ 0.01060815, 0.01808215, 0.10018654], + [ 0.01428972, 0.02048237, 0.10374486], + [ 0.01831941, 0.0229766 , 0.10738511], + [ 0.02275049, 0.02554464, 0.11108639], + [ 0.02759119, 0.02818316, 0.11483751], + [ 0.03285175, 0.03088792, 0.11863035], + [ 0.03853466, 0.03365771, 0.12245873], + [ 0.04447016, 0.03648425, 0.12631831], + [ 0.05032105, 0.03936808, 0.13020508], + [ 0.05611171, 0.04224835, 0.13411624], + [ 0.0618531 , 0.04504866, 0.13804929], + [ 0.06755457, 0.04778179, 0.14200206], + [ 0.0732236 , 0.05045047, 0.14597263], + [ 0.0788708 , 0.05305461, 0.14995981], + [ 0.08450105, 0.05559631, 0.15396203], + [ 0.09011319, 0.05808059, 0.15797687], + [ 0.09572396, 0.06050127, 0.16200507], + [ 0.10132312, 0.06286782, 0.16604287], + [ 0.10692823, 0.06517224, 0.17009175], + [ 0.1125315 , 0.06742194, 0.17414848], + [ 0.11813947, 0.06961499, 0.17821272], + [ 0.12375803, 0.07174938, 0.18228425], + [ 0.12938228, 0.07383015, 0.18636053], + [ 0.13501631, 0.07585609, 0.19044109], + [ 0.14066867, 0.0778224 , 0.19452676], + [ 0.14633406, 0.07973393, 0.1986151 ], + [ 0.15201338, 0.08159108, 0.20270523], + [ 0.15770877, 0.08339312, 0.20679668], + [ 0.16342174, 0.0851396 , 0.21088893], + [ 0.16915387, 0.08682996, 0.21498104], + [ 0.17489524, 0.08848235, 0.2190294 ], + [ 0.18065495, 0.09009031, 0.22303512], + [ 0.18643324, 0.09165431, 0.22699705], + [ 0.19223028, 0.09317479, 0.23091409], + [ 0.19804623, 0.09465217, 0.23478512], + [ 0.20388117, 0.09608689, 0.23860907], + [ 0.20973515, 0.09747934, 0.24238489], + [ 0.21560818, 0.09882993, 0.24611154], + [ 0.22150014, 0.10013944, 0.2497868 ], + [ 0.22741085, 0.10140876, 0.25340813], + [ 0.23334047, 0.10263737, 0.25697736], + [ 0.23928891, 0.10382562, 0.2604936 ], + [ 0.24525608, 0.10497384, 0.26395596], + [ 0.25124182, 0.10608236, 0.26736359], + [ 0.25724602, 0.10715148, 0.27071569], + [ 0.26326851, 0.1081815 , 0.27401148], + [ 0.26930915, 0.1091727 , 0.2772502 ], + [ 0.27536766, 0.11012568, 0.28043021], + [ 0.28144375, 0.11104133, 0.2835489 ], + [ 0.2875374 , 0.11191896, 0.28660853], + [ 0.29364846, 0.11275876, 0.2896085 ], + [ 0.29977678, 0.11356089, 0.29254823], + [ 0.30592213, 0.11432553, 0.29542718], + [ 0.31208435, 0.11505284, 0.29824485], + [ 0.31826327, 0.1157429 , 0.30100076], + [ 0.32445869, 0.11639585, 0.30369448], + [ 0.33067031, 0.11701189, 0.30632563], + [ 0.33689808, 0.11759095, 0.3088938 ], + [ 0.34314168, 0.11813362, 0.31139721], + [ 0.34940101, 0.11863987, 0.3138355 ], + [ 0.355676 , 0.11910909, 0.31620996], + [ 0.36196644, 0.1195413 , 0.31852037], + [ 0.36827206, 0.11993653, 0.32076656], + [ 0.37459292, 0.12029443, 0.32294825], + [ 0.38092887, 0.12061482, 0.32506528], + [ 0.38727975, 0.12089756, 0.3271175 ], + [ 0.39364518, 0.12114272, 0.32910494], + [ 0.40002537, 0.12134964, 0.33102734], + [ 0.40642019, 0.12151801, 0.33288464], + [ 0.41282936, 0.12164769, 0.33467689], + [ 0.41925278, 0.12173833, 0.33640407], + [ 0.42569057, 0.12178916, 0.33806605], + [ 0.43214263, 0.12179973, 0.33966284], + [ 0.43860848, 0.12177004, 0.34119475], + [ 0.44508855, 0.12169883, 0.34266151], + [ 0.45158266, 0.12158557, 0.34406324], + [ 0.45809049, 0.12142996, 0.34540024], + [ 0.46461238, 0.12123063, 0.34667231], + [ 0.47114798, 0.12098721, 0.34787978], + [ 0.47769736, 0.12069864, 0.34902273], + [ 0.48426077, 0.12036349, 0.35010104], + [ 0.49083761, 0.11998161, 0.35111537], + [ 0.49742847, 0.11955087, 0.35206533], + [ 0.50403286, 0.11907081, 0.35295152], + [ 0.51065109, 0.11853959, 0.35377385], + [ 0.51728314, 0.1179558 , 0.35453252], + [ 0.52392883, 0.11731817, 0.35522789], + [ 0.53058853, 0.11662445, 0.35585982], + [ 0.53726173, 0.11587369, 0.35642903], + [ 0.54394898, 0.11506307, 0.35693521], + [ 0.5506426 , 0.11420757, 0.35737863], + [ 0.55734473, 0.11330456, 0.35775059], + [ 0.56405586, 0.11235265, 0.35804813], + [ 0.57077365, 0.11135597, 0.35827146], + [ 0.5774991 , 0.11031233, 0.35841679], + [ 0.58422945, 0.10922707, 0.35848469], + [ 0.59096382, 0.10810205, 0.35847347], + [ 0.59770215, 0.10693774, 0.35838029], + [ 0.60444226, 0.10573912, 0.35820487], + [ 0.61118304, 0.10450943, 0.35794557], + [ 0.61792306, 0.10325288, 0.35760108], + [ 0.62466162, 0.10197244, 0.35716891], + [ 0.63139686, 0.10067417, 0.35664819], + [ 0.63812122, 0.09938212, 0.35603757], + [ 0.64483795, 0.0980891 , 0.35533555], + [ 0.65154562, 0.09680192, 0.35454107], + [ 0.65824241, 0.09552918, 0.3536529 ], + [ 0.66492652, 0.09428017, 0.3526697 ], + [ 0.67159578, 0.09306598, 0.35159077], + [ 0.67824099, 0.09192342, 0.3504148 ], + [ 0.684863 , 0.09085633, 0.34914061], + [ 0.69146268, 0.0898675 , 0.34776864], + [ 0.69803757, 0.08897226, 0.3462986 ], + [ 0.70457834, 0.0882129 , 0.34473046], + [ 0.71108138, 0.08761223, 0.3430635 ], + [ 0.7175507 , 0.08716212, 0.34129974], + [ 0.72398193, 0.08688725, 0.33943958], + [ 0.73035829, 0.0868623 , 0.33748452], + [ 0.73669146, 0.08704683, 0.33543669], + [ 0.74297501, 0.08747196, 0.33329799], + [ 0.74919318, 0.08820542, 0.33107204], + [ 0.75535825, 0.08919792, 0.32876184], + [ 0.76145589, 0.09050716, 0.32637117], + [ 0.76748424, 0.09213602, 0.32390525], + [ 0.77344838, 0.09405684, 0.32136808], + [ 0.77932641, 0.09634794, 0.31876642], + [ 0.78513609, 0.09892473, 0.31610488], + [ 0.79085854, 0.10184672, 0.313391 ], + [ 0.7965014 , 0.10506637, 0.31063031], + [ 0.80205987, 0.10858333, 0.30783 ], + [ 0.80752799, 0.11239964, 0.30499738], + [ 0.81291606, 0.11645784, 0.30213802], + [ 0.81820481, 0.12080606, 0.29926105], + [ 0.82341472, 0.12535343, 0.2963705 ], + [ 0.82852822, 0.13014118, 0.29347474], + [ 0.83355779, 0.13511035, 0.29057852], + [ 0.83850183, 0.14025098, 0.2876878 ], + [ 0.84335441, 0.14556683, 0.28480819], + [ 0.84813096, 0.15099892, 0.281943 ], + [ 0.85281737, 0.15657772, 0.27909826], + [ 0.85742602, 0.1622583 , 0.27627462], + [ 0.86196552, 0.16801239, 0.27346473], + [ 0.86641628, 0.17387796, 0.27070818], + [ 0.87079129, 0.17982114, 0.26797378], + [ 0.87507281, 0.18587368, 0.26529697], + [ 0.87925878, 0.19203259, 0.26268136], + [ 0.8833417 , 0.19830556, 0.26014181], + [ 0.88731387, 0.20469941, 0.25769539], + [ 0.89116859, 0.21121788, 0.2553592 ], + [ 0.89490337, 0.21785614, 0.25314362], + [ 0.8985026 , 0.22463251, 0.25108745], + [ 0.90197527, 0.23152063, 0.24918223], + [ 0.90530097, 0.23854541, 0.24748098], + [ 0.90848638, 0.24568473, 0.24598324], + [ 0.911533 , 0.25292623, 0.24470258], + [ 0.9144225 , 0.26028902, 0.24369359], + [ 0.91717106, 0.26773821, 0.24294137], + [ 0.91978131, 0.27526191, 0.24245973], + [ 0.92223947, 0.28287251, 0.24229568], + [ 0.92456587, 0.29053388, 0.24242622], + [ 0.92676657, 0.29823282, 0.24285536], + [ 0.92882964, 0.30598085, 0.24362274], + [ 0.93078135, 0.31373977, 0.24468803], + [ 0.93262051, 0.3215093 , 0.24606461], + [ 0.93435067, 0.32928362, 0.24775328], + [ 0.93599076, 0.33703942, 0.24972157], + [ 0.93752831, 0.34479177, 0.25199928], + [ 0.93899289, 0.35250734, 0.25452808], + [ 0.94036561, 0.36020899, 0.25734661], + [ 0.94167588, 0.36786594, 0.2603949 ], + [ 0.94291042, 0.37549479, 0.26369821], + [ 0.94408513, 0.3830811 , 0.26722004], + [ 0.94520419, 0.39062329, 0.27094924], + [ 0.94625977, 0.39813168, 0.27489742], + [ 0.94727016, 0.4055909 , 0.27902322], + [ 0.94823505, 0.41300424, 0.28332283], + [ 0.94914549, 0.42038251, 0.28780969], + [ 0.95001704, 0.42771398, 0.29244728], + [ 0.95085121, 0.43500005, 0.29722817], + [ 0.95165009, 0.44224144, 0.30214494], + [ 0.9524044 , 0.44944853, 0.3072105 ], + [ 0.95312556, 0.45661389, 0.31239776], + [ 0.95381595, 0.46373781, 0.31769923], + [ 0.95447591, 0.47082238, 0.32310953], + [ 0.95510255, 0.47787236, 0.32862553], + [ 0.95569679, 0.48489115, 0.33421404], + [ 0.95626788, 0.49187351, 0.33985601], + [ 0.95681685, 0.49882008, 0.34555431], + [ 0.9573439 , 0.50573243, 0.35130912], + [ 0.95784842, 0.51261283, 0.35711942], + [ 0.95833051, 0.51946267, 0.36298589], + [ 0.95879054, 0.52628305, 0.36890904], + [ 0.95922872, 0.53307513, 0.3748895 ], + [ 0.95964538, 0.53983991, 0.38092784], + [ 0.96004345, 0.54657593, 0.3870292 ], + [ 0.96042097, 0.55328624, 0.39319057], + [ 0.96077819, 0.55997184, 0.39941173], + [ 0.9611152 , 0.5666337 , 0.40569343], + [ 0.96143273, 0.57327231, 0.41203603], + [ 0.96173392, 0.57988594, 0.41844491], + [ 0.96201757, 0.58647675, 0.42491751], + [ 0.96228344, 0.59304598, 0.43145271], + [ 0.96253168, 0.5995944 , 0.43805131], + [ 0.96276513, 0.60612062, 0.44471698], + [ 0.96298491, 0.6126247 , 0.45145074], + [ 0.96318967, 0.61910879, 0.45824902], + [ 0.96337949, 0.6255736 , 0.46511271], + [ 0.96355923, 0.63201624, 0.47204746], + [ 0.96372785, 0.63843852, 0.47905028], + [ 0.96388426, 0.64484214, 0.4861196 ], + [ 0.96403203, 0.65122535, 0.4932578 ], + [ 0.96417332, 0.65758729, 0.50046894], + [ 0.9643063 , 0.66393045, 0.5077467 ], + [ 0.96443322, 0.67025402, 0.51509334], + [ 0.96455845, 0.67655564, 0.52251447], + [ 0.96467922, 0.68283846, 0.53000231], + [ 0.96479861, 0.68910113, 0.53756026], + [ 0.96492035, 0.69534192, 0.5451917 ], + [ 0.96504223, 0.7015636 , 0.5528892 ], + [ 0.96516917, 0.70776351, 0.5606593 ], + [ 0.96530224, 0.71394212, 0.56849894], + [ 0.96544032, 0.72010124, 0.57640375], + [ 0.96559206, 0.72623592, 0.58438387], + [ 0.96575293, 0.73235058, 0.59242739], + [ 0.96592829, 0.73844258, 0.60053991], + [ 0.96612013, 0.74451182, 0.60871954], + [ 0.96632832, 0.75055966, 0.61696136], + [ 0.96656022, 0.75658231, 0.62527295], + [ 0.96681185, 0.76258381, 0.63364277], + [ 0.96709183, 0.76855969, 0.64207921], + [ 0.96739773, 0.77451297, 0.65057302], + [ 0.96773482, 0.78044149, 0.65912731], + [ 0.96810471, 0.78634563, 0.66773889], + [ 0.96850919, 0.79222565, 0.6764046 ], + [ 0.96893132, 0.79809112, 0.68512266], + [ 0.96935926, 0.80395415, 0.69383201], + [ 0.9698028 , 0.80981139, 0.70252255], + [ 0.97025511, 0.81566605, 0.71120296], + [ 0.97071849, 0.82151775, 0.71987163], + [ 0.97120159, 0.82736371, 0.72851999], + [ 0.97169389, 0.83320847, 0.73716071], + [ 0.97220061, 0.83905052, 0.74578903], + [ 0.97272597, 0.84488881, 0.75440141], + [ 0.97327085, 0.85072354, 0.76299805], + [ 0.97383206, 0.85655639, 0.77158353], + [ 0.97441222, 0.86238689, 0.78015619], + [ 0.97501782, 0.86821321, 0.78871034], + [ 0.97564391, 0.87403763, 0.79725261], + [ 0.97628674, 0.87986189, 0.8057883 ], + [ 0.97696114, 0.88568129, 0.81430324], + [ 0.97765722, 0.89149971, 0.82280948], + [ 0.97837585, 0.89731727, 0.83130786], + [ 0.97912374, 0.90313207, 0.83979337], + [ 0.979891 , 0.90894778, 0.84827858], + [ 0.98067764, 0.91476465, 0.85676611], + [ 0.98137749, 0.92061729, 0.86536915] +] + + +_mako_lut = [ + [ 0.04503935, 0.01482344, 0.02092227], + [ 0.04933018, 0.01709292, 0.02535719], + [ 0.05356262, 0.01950702, 0.03018802], + [ 0.05774337, 0.02205989, 0.03545515], + [ 0.06188095, 0.02474764, 0.04115287], + [ 0.06598247, 0.0275665 , 0.04691409], + [ 0.07005374, 0.03051278, 0.05264306], + [ 0.07409947, 0.03358324, 0.05834631], + [ 0.07812339, 0.03677446, 0.06403249], + [ 0.08212852, 0.0400833 , 0.06970862], + [ 0.08611731, 0.04339148, 0.07538208], + [ 0.09009161, 0.04664706, 0.08105568], + [ 0.09405308, 0.04985685, 0.08673591], + [ 0.09800301, 0.05302279, 0.09242646], + [ 0.10194255, 0.05614641, 0.09813162], + [ 0.10587261, 0.05922941, 0.103854 ], + [ 0.1097942 , 0.06227277, 0.10959847], + [ 0.11370826, 0.06527747, 0.11536893], + [ 0.11761516, 0.06824548, 0.12116393], + [ 0.12151575, 0.07117741, 0.12698763], + [ 0.12541095, 0.07407363, 0.1328442 ], + [ 0.12930083, 0.07693611, 0.13873064], + [ 0.13317849, 0.07976988, 0.14465095], + [ 0.13701138, 0.08259683, 0.15060265], + [ 0.14079223, 0.08542126, 0.15659379], + [ 0.14452486, 0.08824175, 0.16262484], + [ 0.14820351, 0.09106304, 0.16869476], + [ 0.15183185, 0.09388372, 0.17480366], + [ 0.15540398, 0.09670855, 0.18094993], + [ 0.15892417, 0.09953561, 0.18713384], + [ 0.16238588, 0.10236998, 0.19335329], + [ 0.16579435, 0.10520905, 0.19960847], + [ 0.16914226, 0.10805832, 0.20589698], + [ 0.17243586, 0.11091443, 0.21221911], + [ 0.17566717, 0.11378321, 0.21857219], + [ 0.17884322, 0.11666074, 0.2249565 ], + [ 0.18195582, 0.11955283, 0.23136943], + [ 0.18501213, 0.12245547, 0.23781116], + [ 0.18800459, 0.12537395, 0.24427914], + [ 0.19093944, 0.1283047 , 0.25077369], + [ 0.19381092, 0.13125179, 0.25729255], + [ 0.19662307, 0.13421303, 0.26383543], + [ 0.19937337, 0.13719028, 0.27040111], + [ 0.20206187, 0.14018372, 0.27698891], + [ 0.20469116, 0.14319196, 0.28359861], + [ 0.20725547, 0.14621882, 0.29022775], + [ 0.20976258, 0.14925954, 0.29687795], + [ 0.21220409, 0.15231929, 0.30354703], + [ 0.21458611, 0.15539445, 0.31023563], + [ 0.21690827, 0.15848519, 0.31694355], + [ 0.21916481, 0.16159489, 0.32366939], + [ 0.2213631 , 0.16471913, 0.33041431], + [ 0.22349947, 0.1678599 , 0.33717781], + [ 0.2255714 , 0.1710185 , 0.34395925], + [ 0.22758415, 0.17419169, 0.35075983], + [ 0.22953569, 0.17738041, 0.35757941], + [ 0.23142077, 0.18058733, 0.3644173 ], + [ 0.2332454 , 0.18380872, 0.37127514], + [ 0.2350092 , 0.18704459, 0.3781528 ], + [ 0.23670785, 0.190297 , 0.38504973], + [ 0.23834119, 0.19356547, 0.39196711], + [ 0.23991189, 0.19684817, 0.39890581], + [ 0.24141903, 0.20014508, 0.4058667 ], + [ 0.24286214, 0.20345642, 0.4128484 ], + [ 0.24423453, 0.20678459, 0.41985299], + [ 0.24554109, 0.21012669, 0.42688124], + [ 0.2467815 , 0.21348266, 0.43393244], + [ 0.24795393, 0.21685249, 0.4410088 ], + [ 0.24905614, 0.22023618, 0.448113 ], + [ 0.25007383, 0.22365053, 0.45519562], + [ 0.25098926, 0.22710664, 0.46223892], + [ 0.25179696, 0.23060342, 0.46925447], + [ 0.25249346, 0.23414353, 0.47623196], + [ 0.25307401, 0.23772973, 0.48316271], + [ 0.25353152, 0.24136961, 0.49001976], + [ 0.25386167, 0.24506548, 0.49679407], + [ 0.25406082, 0.2488164 , 0.50348932], + [ 0.25412435, 0.25262843, 0.51007843], + [ 0.25404842, 0.25650743, 0.51653282], + [ 0.25383134, 0.26044852, 0.52286845], + [ 0.2534705 , 0.26446165, 0.52903422], + [ 0.25296722, 0.2685428 , 0.53503572], + [ 0.2523226 , 0.27269346, 0.54085315], + [ 0.25153974, 0.27691629, 0.54645752], + [ 0.25062402, 0.28120467, 0.55185939], + [ 0.24958205, 0.28556371, 0.55701246], + [ 0.24842386, 0.28998148, 0.56194601], + [ 0.24715928, 0.29446327, 0.56660884], + [ 0.24580099, 0.29899398, 0.57104399], + [ 0.24436202, 0.30357852, 0.57519929], + [ 0.24285591, 0.30819938, 0.57913247], + [ 0.24129828, 0.31286235, 0.58278615], + [ 0.23970131, 0.3175495 , 0.5862272 ], + [ 0.23807973, 0.32226344, 0.58941872], + [ 0.23644557, 0.32699241, 0.59240198], + [ 0.2348113 , 0.33173196, 0.59518282], + [ 0.23318874, 0.33648036, 0.59775543], + [ 0.2315855 , 0.34122763, 0.60016456], + [ 0.23001121, 0.34597357, 0.60240251], + [ 0.2284748 , 0.35071512, 0.6044784 ], + [ 0.22698081, 0.35544612, 0.60642528], + [ 0.22553305, 0.36016515, 0.60825252], + [ 0.22413977, 0.36487341, 0.60994938], + [ 0.22280246, 0.36956728, 0.61154118], + [ 0.22152555, 0.37424409, 0.61304472], + [ 0.22030752, 0.37890437, 0.61446646], + [ 0.2191538 , 0.38354668, 0.61581561], + [ 0.21806257, 0.38817169, 0.61709794], + [ 0.21703799, 0.39277882, 0.61831922], + [ 0.21607792, 0.39736958, 0.61948028], + [ 0.21518463, 0.40194196, 0.62059763], + [ 0.21435467, 0.40649717, 0.62167507], + [ 0.21358663, 0.41103579, 0.62271724], + [ 0.21288172, 0.41555771, 0.62373011], + [ 0.21223835, 0.42006355, 0.62471794], + [ 0.21165312, 0.42455441, 0.62568371], + [ 0.21112526, 0.42903064, 0.6266318 ], + [ 0.21065161, 0.43349321, 0.62756504], + [ 0.21023306, 0.43794288, 0.62848279], + [ 0.20985996, 0.44238227, 0.62938329], + [ 0.20951045, 0.44680966, 0.63030696], + [ 0.20916709, 0.45122981, 0.63124483], + [ 0.20882976, 0.45564335, 0.63219599], + [ 0.20849798, 0.46005094, 0.63315928], + [ 0.20817199, 0.46445309, 0.63413391], + [ 0.20785149, 0.46885041, 0.63511876], + [ 0.20753716, 0.47324327, 0.63611321], + [ 0.20722876, 0.47763224, 0.63711608], + [ 0.20692679, 0.48201774, 0.63812656], + [ 0.20663156, 0.48640018, 0.63914367], + [ 0.20634336, 0.49078002, 0.64016638], + [ 0.20606303, 0.49515755, 0.6411939 ], + [ 0.20578999, 0.49953341, 0.64222457], + [ 0.20552612, 0.50390766, 0.64325811], + [ 0.20527189, 0.50828072, 0.64429331], + [ 0.20502868, 0.51265277, 0.64532947], + [ 0.20479718, 0.51702417, 0.64636539], + [ 0.20457804, 0.52139527, 0.64739979], + [ 0.20437304, 0.52576622, 0.64843198], + [ 0.20418396, 0.53013715, 0.64946117], + [ 0.20401238, 0.53450825, 0.65048638], + [ 0.20385896, 0.53887991, 0.65150606], + [ 0.20372653, 0.54325208, 0.65251978], + [ 0.20361709, 0.5476249 , 0.6535266 ], + [ 0.20353258, 0.55199854, 0.65452542], + [ 0.20347472, 0.55637318, 0.655515 ], + [ 0.20344718, 0.56074869, 0.65649508], + [ 0.20345161, 0.56512531, 0.65746419], + [ 0.20349089, 0.56950304, 0.65842151], + [ 0.20356842, 0.57388184, 0.65936642], + [ 0.20368663, 0.57826181, 0.66029768], + [ 0.20384884, 0.58264293, 0.6612145 ], + [ 0.20405904, 0.58702506, 0.66211645], + [ 0.20431921, 0.59140842, 0.66300179], + [ 0.20463464, 0.59579264, 0.66387079], + [ 0.20500731, 0.60017798, 0.66472159], + [ 0.20544449, 0.60456387, 0.66555409], + [ 0.20596097, 0.60894927, 0.66636568], + [ 0.20654832, 0.61333521, 0.66715744], + [ 0.20721003, 0.61772167, 0.66792838], + [ 0.20795035, 0.62210845, 0.66867802], + [ 0.20877302, 0.62649546, 0.66940555], + [ 0.20968223, 0.63088252, 0.6701105 ], + [ 0.21068163, 0.63526951, 0.67079211], + [ 0.21177544, 0.63965621, 0.67145005], + [ 0.21298582, 0.64404072, 0.67208182], + [ 0.21430361, 0.64842404, 0.67268861], + [ 0.21572716, 0.65280655, 0.67326978], + [ 0.21726052, 0.65718791, 0.6738255 ], + [ 0.21890636, 0.66156803, 0.67435491], + [ 0.220668 , 0.66594665, 0.67485792], + [ 0.22255447, 0.67032297, 0.67533374], + [ 0.22458372, 0.67469531, 0.67578061], + [ 0.22673713, 0.67906542, 0.67620044], + [ 0.22901625, 0.6834332 , 0.67659251], + [ 0.23142316, 0.68779836, 0.67695703], + [ 0.23395924, 0.69216072, 0.67729378], + [ 0.23663857, 0.69651881, 0.67760151], + [ 0.23946645, 0.70087194, 0.67788018], + [ 0.24242624, 0.70522162, 0.67813088], + [ 0.24549008, 0.70957083, 0.67835215], + [ 0.24863372, 0.71392166, 0.67854868], + [ 0.25187832, 0.71827158, 0.67872193], + [ 0.25524083, 0.72261873, 0.67887024], + [ 0.25870947, 0.72696469, 0.67898912], + [ 0.26229238, 0.73130855, 0.67907645], + [ 0.26604085, 0.73564353, 0.67914062], + [ 0.26993099, 0.73997282, 0.67917264], + [ 0.27397488, 0.74429484, 0.67917096], + [ 0.27822463, 0.74860229, 0.67914468], + [ 0.28264201, 0.75290034, 0.67907959], + [ 0.2873016 , 0.75717817, 0.67899164], + [ 0.29215894, 0.76144162, 0.67886578], + [ 0.29729823, 0.76567816, 0.67871894], + [ 0.30268199, 0.76989232, 0.67853896], + [ 0.30835665, 0.77407636, 0.67833512], + [ 0.31435139, 0.77822478, 0.67811118], + [ 0.3206671 , 0.78233575, 0.67786729], + [ 0.32733158, 0.78640315, 0.67761027], + [ 0.33437168, 0.79042043, 0.67734882], + [ 0.34182112, 0.79437948, 0.67709394], + [ 0.34968889, 0.79827511, 0.67685638], + [ 0.35799244, 0.80210037, 0.67664969], + [ 0.36675371, 0.80584651, 0.67649539], + [ 0.3759816 , 0.80950627, 0.67641393], + [ 0.38566792, 0.81307432, 0.67642947], + [ 0.39579804, 0.81654592, 0.67656899], + [ 0.40634556, 0.81991799, 0.67686215], + [ 0.41730243, 0.82318339, 0.67735255], + [ 0.4285828 , 0.82635051, 0.6780564 ], + [ 0.44012728, 0.82942353, 0.67900049], + [ 0.45189421, 0.83240398, 0.68021733], + [ 0.46378379, 0.83530763, 0.6817062 ], + [ 0.47573199, 0.83814472, 0.68347352], + [ 0.48769865, 0.84092197, 0.68552698], + [ 0.49962354, 0.84365379, 0.68783929], + [ 0.5114027 , 0.8463718 , 0.69029789], + [ 0.52301693, 0.84908401, 0.69288545], + [ 0.53447549, 0.85179048, 0.69561066], + [ 0.54578602, 0.8544913 , 0.69848331], + [ 0.55695565, 0.85718723, 0.70150427], + [ 0.56798832, 0.85987893, 0.70468261], + [ 0.57888639, 0.86256715, 0.70802931], + [ 0.5896541 , 0.8652532 , 0.71154204], + [ 0.60028928, 0.86793835, 0.71523675], + [ 0.61079441, 0.87062438, 0.71910895], + [ 0.62116633, 0.87331311, 0.72317003], + [ 0.63140509, 0.87600675, 0.72741689], + [ 0.64150735, 0.87870746, 0.73185717], + [ 0.65147219, 0.8814179 , 0.73648495], + [ 0.66129632, 0.8841403 , 0.74130658], + [ 0.67097934, 0.88687758, 0.74631123], + [ 0.68051833, 0.88963189, 0.75150483], + [ 0.68991419, 0.89240612, 0.75687187], + [ 0.69916533, 0.89520211, 0.76241714], + [ 0.70827373, 0.89802257, 0.76812286], + [ 0.71723995, 0.90086891, 0.77399039], + [ 0.72606665, 0.90374337, 0.7800041 ], + [ 0.73475675, 0.90664718, 0.78615802], + [ 0.74331358, 0.90958151, 0.79244474], + [ 0.75174143, 0.91254787, 0.79884925], + [ 0.76004473, 0.91554656, 0.80536823], + [ 0.76827704, 0.91856549, 0.81196513], + [ 0.77647029, 0.921603 , 0.81855729], + [ 0.78462009, 0.92466151, 0.82514119], + [ 0.79273542, 0.92773848, 0.83172131], + [ 0.8008109 , 0.93083672, 0.83829355], + [ 0.80885107, 0.93395528, 0.84485982], + [ 0.81685878, 0.9370938 , 0.85142101], + [ 0.82483206, 0.94025378, 0.8579751 ], + [ 0.83277661, 0.94343371, 0.86452477], + [ 0.84069127, 0.94663473, 0.87106853], + [ 0.84857662, 0.9498573 , 0.8776059 ], + [ 0.8564431 , 0.95309792, 0.88414253], + [ 0.86429066, 0.95635719, 0.89067759], + [ 0.87218969, 0.95960708, 0.89725384] +] + + +_vlag_lut = [ + [ 0.13850039, 0.41331206, 0.74052025], + [ 0.15077609, 0.41762684, 0.73970427], + [ 0.16235219, 0.4219191 , 0.7389667 ], + [ 0.1733322 , 0.42619024, 0.73832537], + [ 0.18382538, 0.43044226, 0.73776764], + [ 0.19394034, 0.4346772 , 0.73725867], + [ 0.20367115, 0.43889576, 0.73685314], + [ 0.21313625, 0.44310003, 0.73648045], + [ 0.22231173, 0.44729079, 0.73619681], + [ 0.23125148, 0.45146945, 0.73597803], + [ 0.23998101, 0.45563715, 0.7358223 ], + [ 0.24853358, 0.45979489, 0.73571524], + [ 0.25691416, 0.4639437 , 0.73566943], + [ 0.26513894, 0.46808455, 0.73568319], + [ 0.27322194, 0.47221835, 0.73575497], + [ 0.28117543, 0.47634598, 0.73588332], + [ 0.28901021, 0.48046826, 0.73606686], + [ 0.2967358 , 0.48458597, 0.73630433], + [ 0.30436071, 0.48869986, 0.73659451], + [ 0.3118955 , 0.49281055, 0.73693255], + [ 0.31935389, 0.49691847, 0.73730851], + [ 0.32672701, 0.5010247 , 0.73774013], + [ 0.33402607, 0.50512971, 0.73821941], + [ 0.34125337, 0.50923419, 0.73874905], + [ 0.34840921, 0.51333892, 0.73933402], + [ 0.35551826, 0.51744353, 0.73994642], + [ 0.3625676 , 0.52154929, 0.74060763], + [ 0.36956356, 0.52565656, 0.74131327], + [ 0.37649902, 0.52976642, 0.74207698], + [ 0.38340273, 0.53387791, 0.74286286], + [ 0.39025859, 0.53799253, 0.7436962 ], + [ 0.39706821, 0.54211081, 0.744578 ], + [ 0.40384046, 0.54623277, 0.74549872], + [ 0.41058241, 0.55035849, 0.74645094], + [ 0.41728385, 0.55448919, 0.74745174], + [ 0.42395178, 0.55862494, 0.74849357], + [ 0.4305964 , 0.56276546, 0.74956387], + [ 0.4372044 , 0.56691228, 0.75068412], + [ 0.4437909 , 0.57106468, 0.75183427], + [ 0.45035117, 0.5752235 , 0.75302312], + [ 0.45687824, 0.57938983, 0.75426297], + [ 0.46339713, 0.58356191, 0.75551816], + [ 0.46988778, 0.58774195, 0.75682037], + [ 0.47635605, 0.59192986, 0.75816245], + [ 0.48281101, 0.5961252 , 0.75953212], + [ 0.4892374 , 0.60032986, 0.76095418], + [ 0.49566225, 0.60454154, 0.76238852], + [ 0.50206137, 0.60876307, 0.76387371], + [ 0.50845128, 0.61299312, 0.76538551], + [ 0.5148258 , 0.61723272, 0.76693475], + [ 0.52118385, 0.62148236, 0.76852436], + [ 0.52753571, 0.62574126, 0.77013939], + [ 0.53386831, 0.63001125, 0.77180152], + [ 0.54020159, 0.63429038, 0.7734803 ], + [ 0.54651272, 0.63858165, 0.77521306], + [ 0.55282975, 0.64288207, 0.77695608], + [ 0.55912585, 0.64719519, 0.77875327], + [ 0.56542599, 0.65151828, 0.78056551], + [ 0.57170924, 0.65585426, 0.78242747], + [ 0.57799572, 0.6602009 , 0.78430751], + [ 0.58426817, 0.66456073, 0.78623458], + [ 0.590544 , 0.66893178, 0.78818117], + [ 0.59680758, 0.67331643, 0.79017369], + [ 0.60307553, 0.67771273, 0.79218572], + [ 0.60934065, 0.68212194, 0.79422987], + [ 0.61559495, 0.68654548, 0.7963202 ], + [ 0.62185554, 0.69098125, 0.79842918], + [ 0.62810662, 0.69543176, 0.80058381], + [ 0.63436425, 0.69989499, 0.80275812], + [ 0.64061445, 0.70437326, 0.80497621], + [ 0.6468706 , 0.70886488, 0.80721641], + [ 0.65312213, 0.7133717 , 0.80949719], + [ 0.65937818, 0.71789261, 0.81180392], + [ 0.66563334, 0.72242871, 0.81414642], + [ 0.67189155, 0.72697967, 0.81651872], + [ 0.67815314, 0.73154569, 0.81892097], + [ 0.68441395, 0.73612771, 0.82136094], + [ 0.69068321, 0.74072452, 0.82382353], + [ 0.69694776, 0.7453385 , 0.82633199], + [ 0.70322431, 0.74996721, 0.8288583 ], + [ 0.70949595, 0.75461368, 0.83143221], + [ 0.7157774 , 0.75927574, 0.83402904], + [ 0.72206299, 0.76395461, 0.83665922], + [ 0.72835227, 0.76865061, 0.8393242 ], + [ 0.73465238, 0.7733628 , 0.84201224], + [ 0.74094862, 0.77809393, 0.84474951], + [ 0.74725683, 0.78284158, 0.84750915], + [ 0.75357103, 0.78760701, 0.85030217], + [ 0.75988961, 0.79239077, 0.85313207], + [ 0.76621987, 0.79719185, 0.85598668], + [ 0.77255045, 0.8020125 , 0.85888658], + [ 0.77889241, 0.80685102, 0.86181298], + [ 0.78524572, 0.81170768, 0.86476656], + [ 0.79159841, 0.81658489, 0.86776906], + [ 0.79796459, 0.82148036, 0.8707962 ], + [ 0.80434168, 0.82639479, 0.87385315], + [ 0.8107221 , 0.83132983, 0.87695392], + [ 0.81711301, 0.8362844 , 0.88008641], + [ 0.82351479, 0.84125863, 0.88325045], + [ 0.82992772, 0.84625263, 0.88644594], + [ 0.83634359, 0.85126806, 0.8896878 ], + [ 0.84277295, 0.85630293, 0.89295721], + [ 0.84921192, 0.86135782, 0.89626076], + [ 0.85566206, 0.866432 , 0.89959467], + [ 0.86211514, 0.87152627, 0.90297183], + [ 0.86857483, 0.87663856, 0.90638248], + [ 0.87504231, 0.88176648, 0.90981938], + [ 0.88151194, 0.88690782, 0.91328493], + [ 0.88797938, 0.89205857, 0.91677544], + [ 0.89443865, 0.89721298, 0.9202854 ], + [ 0.90088204, 0.90236294, 0.92380601], + [ 0.90729768, 0.90749778, 0.92732797], + [ 0.91367037, 0.91260329, 0.93083814], + [ 0.91998105, 0.91766106, 0.93431861], + [ 0.92620596, 0.92264789, 0.93774647], + [ 0.93231683, 0.9275351 , 0.94109192], + [ 0.93827772, 0.9322888 , 0.94432312], + [ 0.94404755, 0.93686925, 0.94740137], + [ 0.94958284, 0.94123072, 0.95027696], + [ 0.95482682, 0.9453245 , 0.95291103], + [ 0.9597248 , 0.94909728, 0.95525103], + [ 0.96422552, 0.95249273, 0.95723271], + [ 0.96826161, 0.95545812, 0.95882188], + [ 0.97178458, 0.95793984, 0.95995705], + [ 0.97474105, 0.95989142, 0.96059997], + [ 0.97708604, 0.96127366, 0.96071853], + [ 0.97877855, 0.96205832, 0.96030095], + [ 0.97978484, 0.96222949, 0.95935496], + [ 0.9805997 , 0.96155216, 0.95813083], + [ 0.98152619, 0.95993719, 0.95639322], + [ 0.9819726 , 0.95766608, 0.95399269], + [ 0.98191855, 0.9547873 , 0.95098107], + [ 0.98138514, 0.95134771, 0.94740644], + [ 0.98040845, 0.94739906, 0.94332125], + [ 0.97902107, 0.94300131, 0.93878672], + [ 0.97729348, 0.93820409, 0.93385135], + [ 0.9752533 , 0.933073 , 0.92858252], + [ 0.97297834, 0.92765261, 0.92302309], + [ 0.97049104, 0.92200317, 0.91723505], + [ 0.96784372, 0.91616744, 0.91126063], + [ 0.96507281, 0.91018664, 0.90514124], + [ 0.96222034, 0.90409203, 0.89890756], + [ 0.9593079 , 0.89791478, 0.89259122], + [ 0.95635626, 0.89167908, 0.88621654], + [ 0.95338303, 0.88540373, 0.87980238], + [ 0.95040174, 0.87910333, 0.87336339], + [ 0.94742246, 0.87278899, 0.86691076], + [ 0.94445249, 0.86646893, 0.86045277], + [ 0.94150476, 0.86014606, 0.85399191], + [ 0.93857394, 0.85382798, 0.84753642], + [ 0.93566206, 0.84751766, 0.84108935], + [ 0.93277194, 0.8412164 , 0.83465197], + [ 0.92990106, 0.83492672, 0.82822708], + [ 0.92704736, 0.82865028, 0.82181656], + [ 0.92422703, 0.82238092, 0.81541333], + [ 0.92142581, 0.81612448, 0.80902415], + [ 0.91864501, 0.80988032, 0.80264838], + [ 0.91587578, 0.80365187, 0.79629001], + [ 0.9131367 , 0.79743115, 0.78994 ], + [ 0.91041602, 0.79122265, 0.78360361], + [ 0.90771071, 0.78502727, 0.77728196], + [ 0.90501581, 0.77884674, 0.7709771 ], + [ 0.90235365, 0.77267117, 0.76467793], + [ 0.8997019 , 0.76650962, 0.75839484], + [ 0.89705346, 0.76036481, 0.752131 ], + [ 0.89444021, 0.75422253, 0.74587047], + [ 0.89183355, 0.74809474, 0.73962689], + [ 0.88923216, 0.74198168, 0.73340061], + [ 0.88665892, 0.73587283, 0.72717995], + [ 0.88408839, 0.72977904, 0.72097718], + [ 0.88153537, 0.72369332, 0.71478461], + [ 0.87899389, 0.7176179 , 0.70860487], + [ 0.87645157, 0.71155805, 0.7024439 ], + [ 0.8739399 , 0.70549893, 0.6962854 ], + [ 0.87142626, 0.6994551 , 0.69014561], + [ 0.8689268 , 0.69341868, 0.68401597], + [ 0.86643562, 0.687392 , 0.67789917], + [ 0.86394434, 0.68137863, 0.67179927], + [ 0.86147586, 0.67536728, 0.665704 ], + [ 0.85899928, 0.66937226, 0.6596292 ], + [ 0.85654668, 0.66337773, 0.6535577 ], + [ 0.85408818, 0.65739772, 0.64750494], + [ 0.85164413, 0.65142189, 0.64145983], + [ 0.84920091, 0.6454565 , 0.63542932], + [ 0.84676427, 0.63949827, 0.62941 ], + [ 0.84433231, 0.63354773, 0.62340261], + [ 0.84190106, 0.62760645, 0.61740899], + [ 0.83947935, 0.62166951, 0.61142404], + [ 0.8370538 , 0.61574332, 0.60545478], + [ 0.83463975, 0.60981951, 0.59949247], + [ 0.83221877, 0.60390724, 0.593547 ], + [ 0.82980985, 0.59799607, 0.58760751], + [ 0.82740268, 0.59209095, 0.58167944], + [ 0.82498638, 0.5861973 , 0.57576866], + [ 0.82258181, 0.5803034 , 0.56986307], + [ 0.82016611, 0.57442123, 0.56397539], + [ 0.81776305, 0.56853725, 0.55809173], + [ 0.81534551, 0.56266602, 0.55222741], + [ 0.81294293, 0.55679056, 0.5463651 ], + [ 0.81052113, 0.55092973, 0.54052443], + [ 0.80811509, 0.54506305, 0.53468464], + [ 0.80568952, 0.53921036, 0.52886622], + [ 0.80327506, 0.53335335, 0.52305077], + [ 0.80084727, 0.52750583, 0.51725256], + [ 0.79842217, 0.5216578 , 0.51146173], + [ 0.79599382, 0.51581223, 0.50568155], + [ 0.79355781, 0.50997127, 0.49991444], + [ 0.79112596, 0.50412707, 0.49415289], + [ 0.78867442, 0.49829386, 0.48841129], + [ 0.7862306 , 0.49245398, 0.48267247], + [ 0.7837687 , 0.48662309, 0.47695216], + [ 0.78130809, 0.4807883 , 0.47123805], + [ 0.77884467, 0.47495151, 0.46553236], + [ 0.77636283, 0.46912235, 0.45984473], + [ 0.77388383, 0.46328617, 0.45416141], + [ 0.77138912, 0.45745466, 0.44849398], + [ 0.76888874, 0.45162042, 0.44283573], + [ 0.76638802, 0.44577901, 0.43718292], + [ 0.76386116, 0.43994762, 0.43155211], + [ 0.76133542, 0.43410655, 0.42592523], + [ 0.75880631, 0.42825801, 0.42030488], + [ 0.75624913, 0.42241905, 0.41470727], + [ 0.7536919 , 0.41656866, 0.40911347], + [ 0.75112748, 0.41071104, 0.40352792], + [ 0.74854331, 0.40485474, 0.3979589 ], + [ 0.74594723, 0.39899309, 0.39240088], + [ 0.74334332, 0.39312199, 0.38685075], + [ 0.74073277, 0.38723941, 0.3813074 ], + [ 0.73809409, 0.38136133, 0.37578553], + [ 0.73544692, 0.37547129, 0.37027123], + [ 0.73278943, 0.36956954, 0.36476549], + [ 0.73011829, 0.36365761, 0.35927038], + [ 0.72743485, 0.35773314, 0.35378465], + [ 0.72472722, 0.35180504, 0.34831662], + [ 0.72200473, 0.34586421, 0.34285937], + [ 0.71927052, 0.33990649, 0.33741033], + [ 0.71652049, 0.33393396, 0.33197219], + [ 0.71375362, 0.32794602, 0.32654545], + [ 0.71096951, 0.32194148, 0.32113016], + [ 0.70816772, 0.31591904, 0.31572637], + [ 0.70534784, 0.30987734, 0.31033414], + [ 0.70250944, 0.30381489, 0.30495353], + [ 0.69965211, 0.2977301 , 0.2995846 ], + [ 0.6967754 , 0.29162126, 0.29422741], + [ 0.69388446, 0.28548074, 0.28887769], + [ 0.69097561, 0.2793096 , 0.28353795], + [ 0.68803513, 0.27311993, 0.27821876], + [ 0.6850794 , 0.26689144, 0.27290694], + [ 0.682108 , 0.26062114, 0.26760246], + [ 0.67911013, 0.2543177 , 0.26231367], + [ 0.67609393, 0.24796818, 0.25703372], + [ 0.67305921, 0.24156846, 0.25176238], + [ 0.67000176, 0.23511902, 0.24650278], + [ 0.66693423, 0.22859879, 0.24124404], + [ 0.6638441 , 0.22201742, 0.2359961 ], + [ 0.66080672, 0.21526712, 0.23069468] +] + + +_icefire_lut = [ + [ 0.73936227, 0.90443867, 0.85757238], + [ 0.72888063, 0.89639109, 0.85488394], + [ 0.71834255, 0.88842162, 0.8521605 ], + [ 0.70773866, 0.88052939, 0.849422 ], + [ 0.69706215, 0.87271313, 0.84668315], + [ 0.68629021, 0.86497329, 0.84398721], + [ 0.67543654, 0.85730617, 0.84130969], + [ 0.66448539, 0.84971123, 0.83868005], + [ 0.65342679, 0.84218728, 0.83611512], + [ 0.64231804, 0.83471867, 0.83358584], + [ 0.63117745, 0.827294 , 0.83113431], + [ 0.62000484, 0.81991069, 0.82876741], + [ 0.60879435, 0.81256797, 0.82648905], + [ 0.59754118, 0.80526458, 0.82430414], + [ 0.58624247, 0.79799884, 0.82221573], + [ 0.57489525, 0.7907688 , 0.82022901], + [ 0.56349779, 0.78357215, 0.81834861], + [ 0.55204294, 0.77640827, 0.81657563], + [ 0.54052516, 0.76927562, 0.81491462], + [ 0.52894085, 0.76217215, 0.81336913], + [ 0.51728854, 0.75509528, 0.81194156], + [ 0.50555676, 0.74804469, 0.81063503], + [ 0.49373871, 0.7410187 , 0.80945242], + [ 0.48183174, 0.73401449, 0.80839675], + [ 0.46982587, 0.72703075, 0.80747097], + [ 0.45770893, 0.72006648, 0.80667756], + [ 0.44547249, 0.71311941, 0.80601991], + [ 0.43318643, 0.70617126, 0.80549278], + [ 0.42110294, 0.69916972, 0.80506683], + [ 0.40925101, 0.69211059, 0.80473246], + [ 0.3976693 , 0.68498786, 0.80448272], + [ 0.38632002, 0.67781125, 0.80431024], + [ 0.37523981, 0.67057537, 0.80420832], + [ 0.36442578, 0.66328229, 0.80417474], + [ 0.35385939, 0.65593699, 0.80420591], + [ 0.34358916, 0.64853177, 0.8043 ], + [ 0.33355526, 0.64107876, 0.80445484], + [ 0.32383062, 0.63356578, 0.80467091], + [ 0.31434372, 0.62600624, 0.8049475 ], + [ 0.30516161, 0.618389 , 0.80528692], + [ 0.29623491, 0.61072284, 0.80569021], + [ 0.28759072, 0.60300319, 0.80616055], + [ 0.27923924, 0.59522877, 0.80669803], + [ 0.27114651, 0.5874047 , 0.80730545], + [ 0.26337153, 0.57952055, 0.80799113], + [ 0.25588696, 0.57157984, 0.80875922], + [ 0.248686 , 0.56358255, 0.80961366], + [ 0.24180668, 0.55552289, 0.81055123], + [ 0.23526251, 0.54739477, 0.8115939 ], + [ 0.22921445, 0.53918506, 0.81267292], + [ 0.22397687, 0.53086094, 0.8137141 ], + [ 0.21977058, 0.52241482, 0.81457651], + [ 0.21658989, 0.51384321, 0.81528511], + [ 0.21452772, 0.50514155, 0.81577278], + [ 0.21372783, 0.49630865, 0.81589566], + [ 0.21409503, 0.48734861, 0.81566163], + [ 0.2157176 , 0.47827123, 0.81487615], + [ 0.21842857, 0.46909168, 0.81351614], + [ 0.22211705, 0.45983212, 0.81146983], + [ 0.22665681, 0.45052233, 0.80860217], + [ 0.23176013, 0.44119137, 0.80494325], + [ 0.23727775, 0.43187704, 0.80038017], + [ 0.24298285, 0.42261123, 0.79493267], + [ 0.24865068, 0.41341842, 0.78869164], + [ 0.25423116, 0.40433127, 0.78155831], + [ 0.25950239, 0.39535521, 0.77376848], + [ 0.2644736 , 0.38651212, 0.76524809], + [ 0.26901584, 0.37779582, 0.75621942], + [ 0.27318141, 0.36922056, 0.746605 ], + [ 0.27690355, 0.3607736 , 0.73659374], + [ 0.28023585, 0.35244234, 0.72622103], + [ 0.28306009, 0.34438449, 0.71500731], + [ 0.28535896, 0.33660243, 0.70303975], + [ 0.28708711, 0.32912157, 0.69034504], + [ 0.28816354, 0.32200604, 0.67684067], + [ 0.28862749, 0.31519824, 0.66278813], + [ 0.28847904, 0.30869064, 0.6482815 ], + [ 0.28770912, 0.30250126, 0.63331265], + [ 0.28640325, 0.29655509, 0.61811374], + [ 0.28458943, 0.29082155, 0.60280913], + [ 0.28233561, 0.28527482, 0.58742866], + [ 0.27967038, 0.2798938 , 0.57204225], + [ 0.27665361, 0.27465357, 0.55667809], + [ 0.27332564, 0.2695165 , 0.54145387], + [ 0.26973851, 0.26447054, 0.52634916], + [ 0.2659204 , 0.25949691, 0.511417 ], + [ 0.26190145, 0.25458123, 0.49668768], + [ 0.2577151 , 0.24971691, 0.48214874], + [ 0.25337618, 0.24490494, 0.46778758], + [ 0.24890842, 0.24013332, 0.45363816], + [ 0.24433654, 0.23539226, 0.4397245 ], + [ 0.23967922, 0.23067729, 0.4260591 ], + [ 0.23495608, 0.22598894, 0.41262952], + [ 0.23018113, 0.22132414, 0.39945577], + [ 0.22534609, 0.21670847, 0.38645794], + [ 0.22048761, 0.21211723, 0.37372555], + [ 0.2156198 , 0.20755389, 0.36125301], + [ 0.21074637, 0.20302717, 0.34903192], + [ 0.20586893, 0.19855368, 0.33701661], + [ 0.20101757, 0.19411573, 0.32529173], + [ 0.19619947, 0.18972425, 0.31383846], + [ 0.19140726, 0.18540157, 0.30260777], + [ 0.1866769 , 0.1811332 , 0.29166583], + [ 0.18201285, 0.17694992, 0.28088776], + [ 0.17745228, 0.17282141, 0.27044211], + [ 0.17300684, 0.16876921, 0.26024893], + [ 0.16868273, 0.16479861, 0.25034479], + [ 0.16448691, 0.16091728, 0.24075373], + [ 0.16043195, 0.15714351, 0.23141745], + [ 0.15652427, 0.15348248, 0.22238175], + [ 0.15277065, 0.14994111, 0.21368395], + [ 0.14918274, 0.14653431, 0.20529486], + [ 0.14577095, 0.14327403, 0.19720829], + [ 0.14254381, 0.14016944, 0.18944326], + [ 0.13951035, 0.13723063, 0.18201072], + [ 0.13667798, 0.13446606, 0.17493774], + [ 0.13405762, 0.13188822, 0.16820842], + [ 0.13165767, 0.12950667, 0.16183275], + [ 0.12948748, 0.12733187, 0.15580631], + [ 0.12755435, 0.1253723 , 0.15014098], + [ 0.12586516, 0.12363617, 0.1448459 ], + [ 0.12442647, 0.12213143, 0.13992571], + [ 0.12324241, 0.12086419, 0.13539995], + [ 0.12232067, 0.11984278, 0.13124644], + [ 0.12166209, 0.11907077, 0.12749671], + [ 0.12126982, 0.11855309, 0.12415079], + [ 0.12114244, 0.11829179, 0.1212385 ], + [ 0.12127766, 0.11828837, 0.11878534], + [ 0.12284806, 0.1179729 , 0.11772022], + [ 0.12619498, 0.11721796, 0.11770203], + [ 0.129968 , 0.11663788, 0.11792377], + [ 0.13410011, 0.11625146, 0.11839138], + [ 0.13855459, 0.11606618, 0.11910584], + [ 0.14333775, 0.11607038, 0.1200606 ], + [ 0.148417 , 0.11626929, 0.12125453], + [ 0.15377389, 0.11666192, 0.12268364], + [ 0.15941427, 0.11723486, 0.12433911], + [ 0.16533376, 0.11797856, 0.12621303], + [ 0.17152547, 0.11888403, 0.12829735], + [ 0.17797765, 0.11994436, 0.13058435], + [ 0.18468769, 0.12114722, 0.13306426], + [ 0.19165663, 0.12247737, 0.13572616], + [ 0.19884415, 0.12394381, 0.1385669 ], + [ 0.20627181, 0.12551883, 0.14157124], + [ 0.21394877, 0.12718055, 0.14472604], + [ 0.22184572, 0.12893119, 0.14802579], + [ 0.22994394, 0.13076731, 0.15146314], + [ 0.23823937, 0.13267611, 0.15502793], + [ 0.24676041, 0.13462172, 0.15870321], + [ 0.25546457, 0.13661751, 0.16248722], + [ 0.26433628, 0.13865956, 0.16637301], + [ 0.27341345, 0.14070412, 0.17034221], + [ 0.28264773, 0.14277192, 0.1743957 ], + [ 0.29202272, 0.14486161, 0.17852793], + [ 0.30159648, 0.14691224, 0.1827169 ], + [ 0.31129002, 0.14897583, 0.18695213], + [ 0.32111555, 0.15103351, 0.19119629], + [ 0.33107961, 0.1530674 , 0.19543758], + [ 0.34119892, 0.15504762, 0.1996803 ], + [ 0.35142388, 0.15701131, 0.20389086], + [ 0.36178937, 0.1589124 , 0.20807639], + [ 0.37229381, 0.16073993, 0.21223189], + [ 0.38288348, 0.16254006, 0.2163249 ], + [ 0.39359592, 0.16426336, 0.22036577], + [ 0.40444332, 0.16588767, 0.22434027], + [ 0.41537995, 0.16745325, 0.2282297 ], + [ 0.42640867, 0.16894939, 0.23202755], + [ 0.43754706, 0.17034847, 0.23572899], + [ 0.44878564, 0.1716535 , 0.23932344], + [ 0.4601126 , 0.17287365, 0.24278607], + [ 0.47151732, 0.17401641, 0.24610337], + [ 0.48300689, 0.17506676, 0.2492737 ], + [ 0.49458302, 0.17601892, 0.25227688], + [ 0.50623876, 0.17687777, 0.255096 ], + [ 0.5179623 , 0.17765528, 0.2577162 ], + [ 0.52975234, 0.17835232, 0.2601134 ], + [ 0.54159776, 0.17898292, 0.26226847], + [ 0.55348804, 0.17956232, 0.26416003], + [ 0.56541729, 0.18010175, 0.26575971], + [ 0.57736669, 0.180631 , 0.26704888], + [ 0.58932081, 0.18117827, 0.26800409], + [ 0.60127582, 0.18175888, 0.26858488], + [ 0.61319563, 0.1824336 , 0.2687872 ], + [ 0.62506376, 0.18324015, 0.26858301], + [ 0.63681202, 0.18430173, 0.26795276], + [ 0.64842603, 0.18565472, 0.26689463], + [ 0.65988195, 0.18734638, 0.26543435], + [ 0.67111966, 0.18948885, 0.26357955], + [ 0.68209194, 0.19216636, 0.26137175], + [ 0.69281185, 0.19535326, 0.25887063], + [ 0.70335022, 0.19891271, 0.25617971], + [ 0.71375229, 0.20276438, 0.25331365], + [ 0.72401436, 0.20691287, 0.25027366], + [ 0.73407638, 0.21145051, 0.24710661], + [ 0.74396983, 0.21631913, 0.24380715], + [ 0.75361506, 0.22163653, 0.24043996], + [ 0.7630579 , 0.22731637, 0.23700095], + [ 0.77222228, 0.23346231, 0.23356628], + [ 0.78115441, 0.23998404, 0.23013825], + [ 0.78979746, 0.24694858, 0.22678822], + [ 0.79819286, 0.25427223, 0.22352658], + [ 0.80630444, 0.26198807, 0.22040877], + [ 0.81417437, 0.27001406, 0.21744645], + [ 0.82177364, 0.27837336, 0.21468316], + [ 0.82915955, 0.28696963, 0.21210766], + [ 0.83628628, 0.2958499 , 0.20977813], + [ 0.84322168, 0.30491136, 0.20766435], + [ 0.84995458, 0.31415945, 0.2057863 ], + [ 0.85648867, 0.32358058, 0.20415327], + [ 0.86286243, 0.33312058, 0.20274969], + [ 0.86908321, 0.34276705, 0.20157271], + [ 0.87512876, 0.3525416 , 0.20064949], + [ 0.88100349, 0.36243385, 0.19999078], + [ 0.8866469 , 0.37249496, 0.1997976 ], + [ 0.89203964, 0.38273475, 0.20013431], + [ 0.89713496, 0.39318156, 0.20121514], + [ 0.90195099, 0.40380687, 0.20301555], + [ 0.90648379, 0.41460191, 0.20558847], + [ 0.9106967 , 0.42557857, 0.20918529], + [ 0.91463791, 0.43668557, 0.21367954], + [ 0.91830723, 0.44790913, 0.21916352], + [ 0.92171507, 0.45922856, 0.22568002], + [ 0.92491786, 0.4705936 , 0.23308207], + [ 0.92790792, 0.48200153, 0.24145932], + [ 0.93073701, 0.49341219, 0.25065486], + [ 0.93343918, 0.5048017 , 0.26056148], + [ 0.93602064, 0.51616486, 0.27118485], + [ 0.93850535, 0.52748892, 0.28242464], + [ 0.94092933, 0.53875462, 0.29416042], + [ 0.94330011, 0.5499628 , 0.30634189], + [ 0.94563159, 0.56110987, 0.31891624], + [ 0.94792955, 0.57219822, 0.33184256], + [ 0.95020929, 0.5832232 , 0.34508419], + [ 0.95247324, 0.59419035, 0.35859866], + [ 0.95471709, 0.60510869, 0.37236035], + [ 0.95698411, 0.61595766, 0.38629631], + [ 0.95923863, 0.62676473, 0.40043317], + [ 0.9615041 , 0.6375203 , 0.41474106], + [ 0.96371553, 0.64826619, 0.42928335], + [ 0.96591497, 0.65899621, 0.44380444], + [ 0.96809871, 0.66971662, 0.45830232], + [ 0.9702495 , 0.6804394 , 0.47280492], + [ 0.9723881 , 0.69115622, 0.48729272], + [ 0.97450723, 0.70187358, 0.50178034], + [ 0.9766108 , 0.712592 , 0.51626837], + [ 0.97871716, 0.72330511, 0.53074053], + [ 0.98082222, 0.73401769, 0.54520694], + [ 0.9829001 , 0.74474445, 0.5597019 ], + [ 0.98497466, 0.75547635, 0.57420239], + [ 0.98705581, 0.76621129, 0.58870185], + [ 0.98913325, 0.77695637, 0.60321626], + [ 0.99119918, 0.78771716, 0.61775821], + [ 0.9932672 , 0.79848979, 0.63231691], + [ 0.99535958, 0.80926704, 0.64687278], + [ 0.99740544, 0.82008078, 0.66150571], + [ 0.9992197 , 0.83100723, 0.6764127 ] +] + + +_flare_lut = [ + [0.92907237, 0.68878959, 0.50411509], + [0.92891402, 0.68494686, 0.50173994], + [0.92864754, 0.68116207, 0.4993754], + [0.92836112, 0.67738527, 0.49701572], + [0.9280599, 0.67361354, 0.49466044], + [0.92775569, 0.66983999, 0.49230866], + [0.9274375, 0.66607098, 0.48996097], + [0.927111, 0.66230315, 0.48761688], + [0.92677996, 0.6585342, 0.485276], + [0.92644317, 0.65476476, 0.48293832], + [0.92609759, 0.65099658, 0.48060392], + [0.925747, 0.64722729, 0.47827244], + [0.92539502, 0.64345456, 0.47594352], + [0.92503106, 0.6396848, 0.47361782], + [0.92466877, 0.6359095, 0.47129427], + [0.92429828, 0.63213463, 0.46897349], + [0.92392172, 0.62835879, 0.46665526], + [0.92354597, 0.62457749, 0.46433898], + [0.9231622, 0.6207962, 0.46202524], + [0.92277222, 0.61701365, 0.45971384], + [0.92237978, 0.61322733, 0.45740444], + [0.92198615, 0.60943622, 0.45509686], + [0.92158735, 0.60564276, 0.45279137], + [0.92118373, 0.60184659, 0.45048789], + [0.92077582, 0.59804722, 0.44818634], + [0.92036413, 0.59424414, 0.44588663], + [0.91994924, 0.5904368, 0.44358868], + [0.91952943, 0.58662619, 0.4412926], + [0.91910675, 0.58281075, 0.43899817], + [0.91868096, 0.57899046, 0.4367054], + [0.91825103, 0.57516584, 0.43441436], + [0.91781857, 0.57133556, 0.43212486], + [0.9173814, 0.56750099, 0.4298371], + [0.91694139, 0.56366058, 0.42755089], + [0.91649756, 0.55981483, 0.42526631], + [0.91604942, 0.55596387, 0.42298339], + [0.9155979, 0.55210684, 0.42070204], + [0.9151409, 0.54824485, 0.4184247], + [0.91466138, 0.54438817, 0.41617858], + [0.91416896, 0.54052962, 0.41396347], + [0.91366559, 0.53666778, 0.41177769], + [0.91315173, 0.53280208, 0.40962196], + [0.91262605, 0.52893336, 0.40749715], + [0.91208866, 0.52506133, 0.40540404], + [0.91153952, 0.52118582, 0.40334346], + [0.91097732, 0.51730767, 0.4013163], + [0.910403, 0.51342591, 0.39932342], + [0.90981494, 0.50954168, 0.39736571], + [0.90921368, 0.5056543, 0.39544411], + [0.90859797, 0.50176463, 0.39355952], + [0.90796841, 0.49787195, 0.39171297], + [0.90732341, 0.4939774, 0.38990532], + [0.90666382, 0.49008006, 0.38813773], + [0.90598815, 0.486181, 0.38641107], + [0.90529624, 0.48228017, 0.38472641], + [0.90458808, 0.47837738, 0.38308489], + [0.90386248, 0.47447348, 0.38148746], + [0.90311921, 0.4705685, 0.37993524], + [0.90235809, 0.46666239, 0.37842943], + [0.90157824, 0.46275577, 0.37697105], + [0.90077904, 0.45884905, 0.37556121], + [0.89995995, 0.45494253, 0.37420106], + [0.89912041, 0.4510366, 0.37289175], + [0.8982602, 0.44713126, 0.37163458], + [0.89737819, 0.44322747, 0.37043052], + [0.89647387, 0.43932557, 0.36928078], + [0.89554477, 0.43542759, 0.36818855], + [0.89458871, 0.4315354, 0.36715654], + [0.89360794, 0.42764714, 0.36618273], + [0.89260152, 0.42376366, 0.36526813], + [0.8915687, 0.41988565, 0.36441384], + [0.89050882, 0.41601371, 0.36362102], + [0.8894159, 0.41215334, 0.36289639], + [0.888292, 0.40830288, 0.36223756], + [0.88713784, 0.40446193, 0.36164328], + [0.88595253, 0.40063149, 0.36111438], + [0.88473115, 0.39681635, 0.3606566], + [0.88347246, 0.39301805, 0.36027074], + [0.88217931, 0.38923439, 0.35995244], + [0.880851, 0.38546632, 0.35970244], + [0.87947728, 0.38172422, 0.35953127], + [0.87806542, 0.37800172, 0.35942941], + [0.87661509, 0.37429964, 0.35939659], + [0.87511668, 0.37062819, 0.35944178], + [0.87357554, 0.36698279, 0.35955811], + [0.87199254, 0.3633634, 0.35974223], + [0.87035691, 0.35978174, 0.36000516], + [0.86867647, 0.35623087, 0.36033559], + [0.86694949, 0.35271349, 0.36073358], + [0.86516775, 0.34923921, 0.36120624], + [0.86333996, 0.34580008, 0.36174113], + [0.86145909, 0.3424046, 0.36234402], + [0.85952586, 0.33905327, 0.36301129], + [0.85754536, 0.33574168, 0.36373567], + [0.855514, 0.33247568, 0.36451271], + [0.85344392, 0.32924217, 0.36533344], + [0.8513284, 0.32604977, 0.36620106], + [0.84916723, 0.32289973, 0.36711424], + [0.84696243, 0.31979068, 0.36806976], + [0.84470627, 0.31673295, 0.36907066], + [0.84240761, 0.31371695, 0.37010969], + [0.84005337, 0.31075974, 0.37119284], + [0.83765537, 0.30784814, 0.3723105], + [0.83520234, 0.30499724, 0.37346726], + [0.83270291, 0.30219766, 0.37465552], + [0.83014895, 0.29946081, 0.37587769], + [0.82754694, 0.29677989, 0.37712733], + [0.82489111, 0.29416352, 0.37840532], + [0.82218644, 0.29160665, 0.37970606], + [0.81942908, 0.28911553, 0.38102921], + [0.81662276, 0.28668665, 0.38236999], + [0.81376555, 0.28432371, 0.383727], + [0.81085964, 0.28202508, 0.38509649], + [0.8079055, 0.27979128, 0.38647583], + [0.80490309, 0.27762348, 0.3878626], + [0.80185613, 0.2755178, 0.38925253], + [0.79876118, 0.27347974, 0.39064559], + [0.79562644, 0.27149928, 0.39203532], + [0.79244362, 0.2695883, 0.39342447], + [0.78922456, 0.26773176, 0.3948046], + [0.78596161, 0.26594053, 0.39617873], + [0.7826624, 0.26420493, 0.39754146], + [0.77932717, 0.26252522, 0.39889102], + [0.77595363, 0.2609049, 0.4002279], + [0.77254999, 0.25933319, 0.40154704], + [0.76911107, 0.25781758, 0.40284959], + [0.76564158, 0.25635173, 0.40413341], + [0.76214598, 0.25492998, 0.40539471], + [0.75861834, 0.25356035, 0.40663694], + [0.75506533, 0.25223402, 0.40785559], + [0.75148963, 0.2509473, 0.40904966], + [0.74788835, 0.24970413, 0.41022028], + [0.74426345, 0.24850191, 0.41136599], + [0.74061927, 0.24733457, 0.41248516], + [0.73695678, 0.24620072, 0.41357737], + [0.73327278, 0.24510469, 0.41464364], + [0.72957096, 0.24404127, 0.4156828], + [0.72585394, 0.24300672, 0.41669383], + [0.7221226, 0.24199971, 0.41767651], + [0.71837612, 0.24102046, 0.41863486], + [0.71463236, 0.24004289, 0.41956983], + [0.7108932, 0.23906316, 0.42048681], + [0.70715842, 0.23808142, 0.42138647], + [0.70342811, 0.2370976, 0.42226844], + [0.69970218, 0.23611179, 0.42313282], + [0.69598055, 0.2351247, 0.42397678], + [0.69226314, 0.23413578, 0.42480327], + [0.68854988, 0.23314511, 0.42561234], + [0.68484064, 0.23215279, 0.42640419], + [0.68113541, 0.23115942, 0.42717615], + [0.67743412, 0.23016472, 0.42792989], + [0.67373662, 0.22916861, 0.42866642], + [0.67004287, 0.22817117, 0.42938576], + [0.66635279, 0.22717328, 0.43008427], + [0.66266621, 0.22617435, 0.43076552], + [0.65898313, 0.22517434, 0.43142956], + [0.65530349, 0.22417381, 0.43207427], + [0.65162696, 0.22317307, 0.4327001], + [0.64795375, 0.22217149, 0.43330852], + [0.64428351, 0.22116972, 0.43389854], + [0.64061624, 0.22016818, 0.43446845], + [0.63695183, 0.21916625, 0.43502123], + [0.63329016, 0.21816454, 0.43555493], + [0.62963102, 0.2171635, 0.43606881], + [0.62597451, 0.21616235, 0.43656529], + [0.62232019, 0.21516239, 0.43704153], + [0.61866821, 0.21416307, 0.43749868], + [0.61501835, 0.21316435, 0.43793808], + [0.61137029, 0.21216761, 0.4383556], + [0.60772426, 0.2111715, 0.43875552], + [0.60407977, 0.21017746, 0.43913439], + [0.60043678, 0.20918503, 0.43949412], + [0.59679524, 0.20819447, 0.43983393], + [0.59315487, 0.20720639, 0.44015254], + [0.58951566, 0.20622027, 0.44045213], + [0.58587715, 0.20523751, 0.44072926], + [0.5822395, 0.20425693, 0.44098758], + [0.57860222, 0.20328034, 0.44122241], + [0.57496549, 0.20230637, 0.44143805], + [0.57132875, 0.20133689, 0.4416298], + [0.56769215, 0.20037071, 0.44180142], + [0.5640552, 0.19940936, 0.44194923], + [0.56041794, 0.19845221, 0.44207535], + [0.55678004, 0.1975, 0.44217824], + [0.55314129, 0.19655316, 0.44225723], + [0.54950166, 0.19561118, 0.44231412], + [0.54585987, 0.19467771, 0.44234111], + [0.54221157, 0.19375869, 0.44233698], + [0.5385549, 0.19285696, 0.44229959], + [0.5348913, 0.19197036, 0.44222958], + [0.53122177, 0.1910974, 0.44212735], + [0.52754464, 0.19024042, 0.44199159], + [0.52386353, 0.18939409, 0.44182449], + [0.52017476, 0.18856368, 0.44162345], + [0.51648277, 0.18774266, 0.44139128], + [0.51278481, 0.18693492, 0.44112605], + [0.50908361, 0.18613639, 0.4408295], + [0.50537784, 0.18534893, 0.44050064], + [0.50166912, 0.18457008, 0.44014054], + [0.49795686, 0.18380056, 0.43974881], + [0.49424218, 0.18303865, 0.43932623], + [0.49052472, 0.18228477, 0.43887255], + [0.48680565, 0.1815371, 0.43838867], + [0.48308419, 0.18079663, 0.43787408], + [0.47936222, 0.18006056, 0.43733022], + [0.47563799, 0.17933127, 0.43675585], + [0.47191466, 0.17860416, 0.43615337], + [0.46818879, 0.17788392, 0.43552047], + [0.46446454, 0.17716458, 0.43486036], + [0.46073893, 0.17645017, 0.43417097], + [0.45701462, 0.17573691, 0.43345429], + [0.45329097, 0.17502549, 0.43271025], + [0.44956744, 0.17431649, 0.4319386], + [0.44584668, 0.17360625, 0.43114133], + [0.44212538, 0.17289906, 0.43031642], + [0.43840678, 0.17219041, 0.42946642], + [0.43469046, 0.17148074, 0.42859124], + [0.4309749, 0.17077192, 0.42769008], + [0.42726297, 0.17006003, 0.42676519], + [0.42355299, 0.16934709, 0.42581586], + [0.41984535, 0.16863258, 0.42484219], + [0.41614149, 0.16791429, 0.42384614], + [0.41244029, 0.16719372, 0.42282661], + [0.40874177, 0.16647061, 0.42178429], + [0.40504765, 0.16574261, 0.42072062], + [0.401357, 0.16501079, 0.41963528], + [0.397669, 0.16427607, 0.418528], + [0.39398585, 0.16353554, 0.41740053], + [0.39030735, 0.16278924, 0.41625344], + [0.3866314, 0.16203977, 0.41508517], + [0.38295904, 0.16128519, 0.41389849], + [0.37928736, 0.16052483, 0.41270599], + [0.37562649, 0.15974704, 0.41151182], + [0.37197803, 0.15895049, 0.41031532], + [0.36833779, 0.15813871, 0.40911916], + [0.36470944, 0.15730861, 0.40792149], + [0.36109117, 0.15646169, 0.40672362], + [0.35748213, 0.15559861, 0.40552633], + [0.353885, 0.15471714, 0.40432831], + [0.35029682, 0.15381967, 0.4031316], + [0.34671861, 0.1529053, 0.40193587], + [0.34315191, 0.15197275, 0.40074049], + [0.33959331, 0.15102466, 0.3995478], + [0.33604378, 0.15006017, 0.39835754], + [0.33250529, 0.14907766, 0.39716879], + [0.32897621, 0.14807831, 0.39598285], + [0.3254559, 0.14706248, 0.39480044], + [0.32194567, 0.14602909, 0.39362106], + [0.31844477, 0.14497857, 0.39244549], + [0.31494974, 0.14391333, 0.39127626], + [0.31146605, 0.14282918, 0.39011024], + [0.30798857, 0.1417297, 0.38895105], + [0.30451661, 0.14061515, 0.38779953], + [0.30105136, 0.13948445, 0.38665531], + [0.2975886, 0.1383403, 0.38552159], + [0.29408557, 0.13721193, 0.38442775] +] + + +_crest_lut = [ + [0.6468274, 0.80289262, 0.56592265], + [0.64233318, 0.80081141, 0.56639461], + [0.63791969, 0.7987162, 0.56674976], + [0.6335316, 0.79661833, 0.56706128], + [0.62915226, 0.7945212, 0.56735066], + [0.62477862, 0.79242543, 0.56762143], + [0.62042003, 0.79032918, 0.56786129], + [0.61606327, 0.78823508, 0.56808666], + [0.61171322, 0.78614216, 0.56829092], + [0.60736933, 0.78405055, 0.56847436], + [0.60302658, 0.78196121, 0.56864272], + [0.59868708, 0.77987374, 0.56879289], + [0.59435366, 0.77778758, 0.56892099], + [0.59001953, 0.77570403, 0.56903477], + [0.58568753, 0.77362254, 0.56913028], + [0.58135593, 0.77154342, 0.56920908], + [0.57702623, 0.76946638, 0.56926895], + [0.57269165, 0.76739266, 0.5693172], + [0.56835934, 0.76532092, 0.56934507], + [0.56402533, 0.76325185, 0.56935664], + [0.55968429, 0.76118643, 0.56935732], + [0.55534159, 0.75912361, 0.56934052], + [0.55099572, 0.75706366, 0.56930743], + [0.54664626, 0.75500662, 0.56925799], + [0.54228969, 0.75295306, 0.56919546], + [0.53792417, 0.75090328, 0.56912118], + [0.53355172, 0.74885687, 0.5690324], + [0.52917169, 0.74681387, 0.56892926], + [0.52478243, 0.74477453, 0.56881287], + [0.52038338, 0.74273888, 0.56868323], + [0.5159739, 0.74070697, 0.56854039], + [0.51155269, 0.73867895, 0.56838507], + [0.50711872, 0.73665492, 0.56821764], + [0.50267118, 0.73463494, 0.56803826], + [0.49822926, 0.73261388, 0.56785146], + [0.49381422, 0.73058524, 0.56767484], + [0.48942421, 0.72854938, 0.56751036], + [0.48505993, 0.72650623, 0.56735752], + [0.48072207, 0.72445575, 0.56721583], + [0.4764113, 0.72239788, 0.56708475], + [0.47212827, 0.72033258, 0.56696376], + [0.46787361, 0.71825983, 0.56685231], + [0.46364792, 0.71617961, 0.56674986], + [0.45945271, 0.71409167, 0.56665625], + [0.45528878, 0.71199595, 0.56657103], + [0.45115557, 0.70989276, 0.5664931], + [0.44705356, 0.70778212, 0.56642189], + [0.44298321, 0.70566406, 0.56635683], + [0.43894492, 0.70353863, 0.56629734], + [0.43493911, 0.70140588, 0.56624286], + [0.43096612, 0.69926587, 0.5661928], + [0.42702625, 0.69711868, 0.56614659], + [0.42311977, 0.69496438, 0.56610368], + [0.41924689, 0.69280308, 0.56606355], + [0.41540778, 0.69063486, 0.56602564], + [0.41160259, 0.68845984, 0.56598944], + [0.40783143, 0.68627814, 0.56595436], + [0.40409434, 0.68408988, 0.56591994], + [0.40039134, 0.68189518, 0.56588564], + [0.39672238, 0.6796942, 0.56585103], + [0.39308781, 0.67748696, 0.56581581], + [0.38949137, 0.67527276, 0.56578084], + [0.38592889, 0.67305266, 0.56574422], + [0.38240013, 0.67082685, 0.56570561], + [0.37890483, 0.66859548, 0.56566462], + [0.37544276, 0.66635871, 0.56562081], + [0.37201365, 0.66411673, 0.56557372], + [0.36861709, 0.6618697, 0.5655231], + [0.36525264, 0.65961782, 0.56546873], + [0.36191986, 0.65736125, 0.56541032], + [0.35861935, 0.65509998, 0.56534768], + [0.35535621, 0.65283302, 0.56528211], + [0.35212361, 0.65056188, 0.56521171], + [0.34892097, 0.64828676, 0.56513633], + [0.34574785, 0.64600783, 0.56505539], + [0.34260357, 0.64372528, 0.5649689], + [0.33948744, 0.64143931, 0.56487679], + [0.33639887, 0.6391501, 0.56477869], + [0.33334501, 0.63685626, 0.56467661], + [0.33031952, 0.63455911, 0.564569], + [0.3273199, 0.63225924, 0.56445488], + [0.32434526, 0.62995682, 0.56433457], + [0.32139487, 0.62765201, 0.56420795], + [0.31846807, 0.62534504, 0.56407446], + [0.3155731, 0.62303426, 0.56393695], + [0.31270304, 0.62072111, 0.56379321], + [0.30985436, 0.61840624, 0.56364307], + [0.30702635, 0.61608984, 0.56348606], + [0.30421803, 0.61377205, 0.56332267], + [0.30143611, 0.61145167, 0.56315419], + [0.29867863, 0.60912907, 0.56298054], + [0.29593872, 0.60680554, 0.56280022], + [0.29321538, 0.60448121, 0.56261376], + [0.2905079, 0.60215628, 0.56242036], + [0.28782827, 0.5998285, 0.56222366], + [0.28516521, 0.59749996, 0.56202093], + [0.28251558, 0.59517119, 0.56181204], + [0.27987847, 0.59284232, 0.56159709], + [0.27726216, 0.59051189, 0.56137785], + [0.27466434, 0.58818027, 0.56115433], + [0.2720767, 0.58584893, 0.56092486], + [0.26949829, 0.58351797, 0.56068983], + [0.26693801, 0.58118582, 0.56045121], + [0.26439366, 0.57885288, 0.56020858], + [0.26185616, 0.57652063, 0.55996077], + [0.25932459, 0.57418919, 0.55970795], + [0.25681303, 0.57185614, 0.55945297], + [0.25431024, 0.56952337, 0.55919385], + [0.25180492, 0.56719255, 0.5589305], + [0.24929311, 0.56486397, 0.5586654], + [0.24678356, 0.56253666, 0.55839491], + [0.24426587, 0.56021153, 0.55812473], + [0.24174022, 0.55788852, 0.55785448], + [0.23921167, 0.55556705, 0.55758211], + [0.23668315, 0.55324675, 0.55730676], + [0.23414742, 0.55092825, 0.55703167], + [0.23160473, 0.54861143, 0.5567573], + [0.22905996, 0.54629572, 0.55648168], + [0.22651648, 0.54398082, 0.5562029], + [0.22396709, 0.54166721, 0.55592542], + [0.22141221, 0.53935481, 0.55564885], + [0.21885269, 0.53704347, 0.55537294], + [0.21629986, 0.53473208, 0.55509319], + [0.21374297, 0.53242154, 0.5548144], + [0.21118255, 0.53011166, 0.55453708], + [0.2086192, 0.52780237, 0.55426067], + [0.20605624, 0.52549322, 0.55398479], + [0.20350004, 0.5231837, 0.55370601], + [0.20094292, 0.52087429, 0.55342884], + [0.19838567, 0.51856489, 0.55315283], + [0.19582911, 0.51625531, 0.55287818], + [0.19327413, 0.51394542, 0.55260469], + [0.19072933, 0.51163448, 0.5523289], + [0.18819045, 0.50932268, 0.55205372], + [0.18565609, 0.50701014, 0.55177937], + [0.18312739, 0.50469666, 0.55150597], + [0.18060561, 0.50238204, 0.55123374], + [0.178092, 0.50006616, 0.55096224], + [0.17558808, 0.49774882, 0.55069118], + [0.17310341, 0.49542924, 0.5504176], + [0.17063111, 0.49310789, 0.55014445], + [0.1681728, 0.49078458, 0.54987159], + [0.1657302, 0.48845913, 0.54959882], + [0.16330517, 0.48613135, 0.54932605], + [0.16089963, 0.48380104, 0.54905306], + [0.15851561, 0.48146803, 0.54877953], + [0.15615526, 0.47913212, 0.54850526], + [0.15382083, 0.47679313, 0.54822991], + [0.15151471, 0.47445087, 0.54795318], + [0.14924112, 0.47210502, 0.54767411], + [0.1470032, 0.46975537, 0.54739226], + [0.14480101, 0.46740187, 0.54710832], + [0.14263736, 0.46504434, 0.54682188], + [0.14051521, 0.46268258, 0.54653253], + [0.13843761, 0.46031639, 0.54623985], + [0.13640774, 0.45794558, 0.5459434], + [0.13442887, 0.45556994, 0.54564272], + [0.1325044, 0.45318928, 0.54533736], + [0.13063777, 0.4508034, 0.54502674], + [0.12883252, 0.44841211, 0.5447104], + [0.12709242, 0.44601517, 0.54438795], + [0.1254209, 0.44361244, 0.54405855], + [0.12382162, 0.44120373, 0.54372156], + [0.12229818, 0.43878887, 0.54337634], + [0.12085453, 0.4363676, 0.54302253], + [0.11949938, 0.43393955, 0.54265715], + [0.11823166, 0.43150478, 0.54228104], + [0.11705496, 0.42906306, 0.54189388], + [0.115972, 0.42661431, 0.54149449], + [0.11498598, 0.42415835, 0.54108222], + [0.11409965, 0.42169502, 0.54065622], + [0.11331533, 0.41922424, 0.5402155], + [0.11263542, 0.41674582, 0.53975931], + [0.1120615, 0.4142597, 0.53928656], + [0.11159738, 0.41176567, 0.53879549], + [0.11125248, 0.40926325, 0.53828203], + [0.11101698, 0.40675289, 0.53774864], + [0.11089152, 0.40423445, 0.53719455], + [0.11085121, 0.4017095, 0.53662425], + [0.11087217, 0.39917938, 0.53604354], + [0.11095515, 0.39664394, 0.53545166], + [0.11110676, 0.39410282, 0.53484509], + [0.11131735, 0.39155635, 0.53422678], + [0.11158595, 0.38900446, 0.53359634], + [0.11191139, 0.38644711, 0.5329534], + [0.11229224, 0.38388426, 0.53229748], + [0.11273683, 0.38131546, 0.53162393], + [0.11323438, 0.37874109, 0.53093619], + [0.11378271, 0.37616112, 0.53023413], + [0.11437992, 0.37357557, 0.52951727], + [0.11502681, 0.37098429, 0.52878396], + [0.11572661, 0.36838709, 0.52803124], + [0.11646936, 0.36578429, 0.52726234], + [0.11725299, 0.3631759, 0.52647685], + [0.1180755, 0.36056193, 0.52567436], + [0.1189438, 0.35794203, 0.5248497], + [0.11984752, 0.35531657, 0.52400649], + [0.1207833, 0.35268564, 0.52314492], + [0.12174895, 0.35004927, 0.52226461], + [0.12274959, 0.34740723, 0.52136104], + [0.12377809, 0.34475975, 0.52043639], + [0.12482961, 0.34210702, 0.51949179], + [0.125902, 0.33944908, 0.51852688], + [0.12699998, 0.33678574, 0.51753708], + [0.12811691, 0.33411727, 0.51652464], + [0.12924811, 0.33144384, 0.51549084], + [0.13039157, 0.32876552, 0.51443538], + [0.13155228, 0.32608217, 0.51335321], + [0.13272282, 0.32339407, 0.51224759], + [0.13389954, 0.32070138, 0.51111946], + [0.13508064, 0.31800419, 0.50996862], + [0.13627149, 0.31530238, 0.50878942], + [0.13746376, 0.31259627, 0.50758645], + [0.13865499, 0.30988598, 0.50636017], + [0.13984364, 0.30717161, 0.50511042], + [0.14103515, 0.30445309, 0.50383119], + [0.14222093, 0.30173071, 0.50252813], + [0.14339946, 0.2990046, 0.50120127], + [0.14456941, 0.29627483, 0.49985054], + [0.14573579, 0.29354139, 0.49847009], + [0.14689091, 0.29080452, 0.49706566], + [0.1480336, 0.28806432, 0.49563732], + [0.1491628, 0.28532086, 0.49418508], + [0.15028228, 0.28257418, 0.49270402], + [0.15138673, 0.27982444, 0.49119848], + [0.15247457, 0.27707172, 0.48966925], + [0.15354487, 0.2743161, 0.48811641], + [0.15459955, 0.27155765, 0.4865371], + [0.15563716, 0.26879642, 0.4849321], + [0.1566572, 0.26603191, 0.48330429], + [0.15765823, 0.26326032, 0.48167456], + [0.15862147, 0.26048295, 0.48005785], + [0.15954301, 0.25770084, 0.47845341], + [0.16043267, 0.25491144, 0.4768626], + [0.16129262, 0.25211406, 0.4752857], + [0.1621119, 0.24931169, 0.47372076], + [0.16290577, 0.24649998, 0.47217025], + [0.16366819, 0.24368054, 0.47063302], + [0.1644021, 0.24085237, 0.46910949], + [0.16510882, 0.2380149, 0.46759982], + [0.16579015, 0.23516739, 0.46610429], + [0.1664433, 0.2323105, 0.46462219], + [0.16707586, 0.22944155, 0.46315508], + [0.16768475, 0.22656122, 0.46170223], + [0.16826815, 0.22366984, 0.46026308], + [0.16883174, 0.22076514, 0.45883891], + [0.16937589, 0.21784655, 0.45742976], + [0.16990129, 0.21491339, 0.45603578], + [0.1704074, 0.21196535, 0.45465677], + [0.17089473, 0.20900176, 0.4532928], + [0.17136819, 0.20602012, 0.45194524], + [0.17182683, 0.20302012, 0.45061386], + [0.17227059, 0.20000106, 0.44929865], + [0.17270583, 0.19695949, 0.44800165], + [0.17313804, 0.19389201, 0.44672488], + [0.17363177, 0.19076859, 0.44549087] +] + + +_lut_dict = dict( + rocket=_rocket_lut, + mako=_mako_lut, + icefire=_icefire_lut, + vlag=_vlag_lut, + flare=_flare_lut, + crest=_crest_lut, + +) + +for _name, _lut in _lut_dict.items(): + + _cmap = colors.ListedColormap(_lut, _name) + locals()[_name] = _cmap + + _cmap_r = colors.ListedColormap(_lut[::-1], _name + "_r") + locals()[_name + "_r"] = _cmap_r + + register_colormap(_name, _cmap) + register_colormap(_name + "_r", _cmap_r) + +del colors, register_colormap diff --git a/testbed/mwaskom__seaborn/seaborn/colors/__init__.py b/testbed/mwaskom__seaborn/seaborn/colors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0bf1d56bdc5c0e724c8eeb95200297884337cc --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/colors/__init__.py @@ -0,0 +1,2 @@ +from .xkcd_rgb import xkcd_rgb # noqa: F401 +from .crayons import crayons # noqa: F401 diff --git a/testbed/mwaskom__seaborn/seaborn/colors/crayons.py b/testbed/mwaskom__seaborn/seaborn/colors/crayons.py new file mode 100644 index 0000000000000000000000000000000000000000..548af1f199355e00e2b1956aa992a48ed61d090a --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/colors/crayons.py @@ -0,0 +1,120 @@ +crayons = {'Almond': '#EFDECD', + 'Antique Brass': '#CD9575', + 'Apricot': '#FDD9B5', + 'Aquamarine': '#78DBE2', + 'Asparagus': '#87A96B', + 'Atomic Tangerine': '#FFA474', + 'Banana Mania': '#FAE7B5', + 'Beaver': '#9F8170', + 'Bittersweet': '#FD7C6E', + 'Black': '#000000', + 'Blue': '#1F75FE', + 'Blue Bell': '#A2A2D0', + 'Blue Green': '#0D98BA', + 'Blue Violet': '#7366BD', + 'Blush': '#DE5D83', + 'Brick Red': '#CB4154', + 'Brown': '#B4674D', + 'Burnt Orange': '#FF7F49', + 'Burnt Sienna': '#EA7E5D', + 'Cadet Blue': '#B0B7C6', + 'Canary': '#FFFF99', + 'Caribbean Green': '#00CC99', + 'Carnation Pink': '#FFAACC', + 'Cerise': '#DD4492', + 'Cerulean': '#1DACD6', + 'Chestnut': '#BC5D58', + 'Copper': '#DD9475', + 'Cornflower': '#9ACEEB', + 'Cotton Candy': '#FFBCD9', + 'Dandelion': '#FDDB6D', + 'Denim': '#2B6CC4', + 'Desert Sand': '#EFCDB8', + 'Eggplant': '#6E5160', + 'Electric Lime': '#CEFF1D', + 'Fern': '#71BC78', + 'Forest Green': '#6DAE81', + 'Fuchsia': '#C364C5', + 'Fuzzy Wuzzy': '#CC6666', + 'Gold': '#E7C697', + 'Goldenrod': '#FCD975', + 'Granny Smith Apple': '#A8E4A0', + 'Gray': '#95918C', + 'Green': '#1CAC78', + 'Green Yellow': '#F0E891', + 'Hot Magenta': '#FF1DCE', + 'Inchworm': '#B2EC5D', + 'Indigo': '#5D76CB', + 'Jazzberry Jam': '#CA3767', + 'Jungle Green': '#3BB08F', + 'Laser Lemon': '#FEFE22', + 'Lavender': '#FCB4D5', + 'Macaroni and Cheese': '#FFBD88', + 'Magenta': '#F664AF', + 'Mahogany': '#CD4A4C', + 'Manatee': '#979AAA', + 'Mango Tango': '#FF8243', + 'Maroon': '#C8385A', + 'Mauvelous': '#EF98AA', + 'Melon': '#FDBCB4', + 'Midnight Blue': '#1A4876', + 'Mountain Meadow': '#30BA8F', + 'Navy Blue': '#1974D2', + 'Neon Carrot': '#FFA343', + 'Olive Green': '#BAB86C', + 'Orange': '#FF7538', + 'Orchid': '#E6A8D7', + 'Outer Space': '#414A4C', + 'Outrageous Orange': '#FF6E4A', + 'Pacific Blue': '#1CA9C9', + 'Peach': '#FFCFAB', + 'Periwinkle': '#C5D0E6', + 'Piggy Pink': '#FDDDE6', + 'Pine Green': '#158078', + 'Pink Flamingo': '#FC74FD', + 'Pink Sherbert': '#F78FA7', + 'Plum': '#8E4585', + 'Purple Heart': '#7442C8', + "Purple Mountains' Majesty": '#9D81BA', + 'Purple Pizzazz': '#FE4EDA', + 'Radical Red': '#FF496C', + 'Raw Sienna': '#D68A59', + 'Razzle Dazzle Rose': '#FF48D0', + 'Razzmatazz': '#E3256B', + 'Red': '#EE204D', + 'Red Orange': '#FF5349', + 'Red Violet': '#C0448F', + "Robin's Egg Blue": '#1FCECB', + 'Royal Purple': '#7851A9', + 'Salmon': '#FF9BAA', + 'Scarlet': '#FC2847', + "Screamin' Green": '#76FF7A', + 'Sea Green': '#93DFB8', + 'Sepia': '#A5694F', + 'Shadow': '#8A795D', + 'Shamrock': '#45CEA2', + 'Shocking Pink': '#FB7EFD', + 'Silver': '#CDC5C2', + 'Sky Blue': '#80DAEB', + 'Spring Green': '#ECEABE', + 'Sunglow': '#FFCF48', + 'Sunset Orange': '#FD5E53', + 'Tan': '#FAA76C', + 'Tickle Me Pink': '#FC89AC', + 'Timberwolf': '#DBD7D2', + 'Tropical Rain Forest': '#17806D', + 'Tumbleweed': '#DEAA88', + 'Turquoise Blue': '#77DDE7', + 'Unmellow Yellow': '#FFFF66', + 'Violet (Purple)': '#926EAE', + 'Violet Red': '#F75394', + 'Vivid Tangerine': '#FFA089', + 'Vivid Violet': '#8F509D', + 'White': '#FFFFFF', + 'Wild Blue Yonder': '#A2ADD0', + 'Wild Strawberry': '#FF43A4', + 'Wild Watermelon': '#FC6C85', + 'Wisteria': '#CDA4DE', + 'Yellow': '#FCE883', + 'Yellow Green': '#C5E384', + 'Yellow Orange': '#FFAE42'} diff --git a/testbed/mwaskom__seaborn/seaborn/colors/xkcd_rgb.py b/testbed/mwaskom__seaborn/seaborn/colors/xkcd_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..0f775cf6512c789ee4201cc41ed5c5fcc389a500 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/colors/xkcd_rgb.py @@ -0,0 +1,949 @@ +xkcd_rgb = {'acid green': '#8ffe09', + 'adobe': '#bd6c48', + 'algae': '#54ac68', + 'algae green': '#21c36f', + 'almost black': '#070d0d', + 'amber': '#feb308', + 'amethyst': '#9b5fc0', + 'apple': '#6ecb3c', + 'apple green': '#76cd26', + 'apricot': '#ffb16d', + 'aqua': '#13eac9', + 'aqua blue': '#02d8e9', + 'aqua green': '#12e193', + 'aqua marine': '#2ee8bb', + 'aquamarine': '#04d8b2', + 'army green': '#4b5d16', + 'asparagus': '#77ab56', + 'aubergine': '#3d0734', + 'auburn': '#9a3001', + 'avocado': '#90b134', + 'avocado green': '#87a922', + 'azul': '#1d5dec', + 'azure': '#069af3', + 'baby blue': '#a2cffe', + 'baby green': '#8cff9e', + 'baby pink': '#ffb7ce', + 'baby poo': '#ab9004', + 'baby poop': '#937c00', + 'baby poop green': '#8f9805', + 'baby puke green': '#b6c406', + 'baby purple': '#ca9bf7', + 'baby shit brown': '#ad900d', + 'baby shit green': '#889717', + 'banana': '#ffff7e', + 'banana yellow': '#fafe4b', + 'barbie pink': '#fe46a5', + 'barf green': '#94ac02', + 'barney': '#ac1db8', + 'barney purple': '#a00498', + 'battleship grey': '#6b7c85', + 'beige': '#e6daa6', + 'berry': '#990f4b', + 'bile': '#b5c306', + 'black': '#000000', + 'bland': '#afa88b', + 'blood': '#770001', + 'blood orange': '#fe4b03', + 'blood red': '#980002', + 'blue': '#0343df', + 'blue blue': '#2242c7', + 'blue green': '#137e6d', + 'blue grey': '#607c8e', + 'blue purple': '#5729ce', + 'blue violet': '#5d06e9', + 'blue with a hint of purple': '#533cc6', + 'blue/green': '#0f9b8e', + 'blue/grey': '#758da3', + 'blue/purple': '#5a06ef', + 'blueberry': '#464196', + 'bluegreen': '#017a79', + 'bluegrey': '#85a3b2', + 'bluey green': '#2bb179', + 'bluey grey': '#89a0b0', + 'bluey purple': '#6241c7', + 'bluish': '#2976bb', + 'bluish green': '#10a674', + 'bluish grey': '#748b97', + 'bluish purple': '#703be7', + 'blurple': '#5539cc', + 'blush': '#f29e8e', + 'blush pink': '#fe828c', + 'booger': '#9bb53c', + 'booger green': '#96b403', + 'bordeaux': '#7b002c', + 'boring green': '#63b365', + 'bottle green': '#044a05', + 'brick': '#a03623', + 'brick orange': '#c14a09', + 'brick red': '#8f1402', + 'bright aqua': '#0bf9ea', + 'bright blue': '#0165fc', + 'bright cyan': '#41fdfe', + 'bright green': '#01ff07', + 'bright lavender': '#c760ff', + 'bright light blue': '#26f7fd', + 'bright light green': '#2dfe54', + 'bright lilac': '#c95efb', + 'bright lime': '#87fd05', + 'bright lime green': '#65fe08', + 'bright magenta': '#ff08e8', + 'bright olive': '#9cbb04', + 'bright orange': '#ff5b00', + 'bright pink': '#fe01b1', + 'bright purple': '#be03fd', + 'bright red': '#ff000d', + 'bright sea green': '#05ffa6', + 'bright sky blue': '#02ccfe', + 'bright teal': '#01f9c6', + 'bright turquoise': '#0ffef9', + 'bright violet': '#ad0afd', + 'bright yellow': '#fffd01', + 'bright yellow green': '#9dff00', + 'british racing green': '#05480d', + 'bronze': '#a87900', + 'brown': '#653700', + 'brown green': '#706c11', + 'brown grey': '#8d8468', + 'brown orange': '#b96902', + 'brown red': '#922b05', + 'brown yellow': '#b29705', + 'brownish': '#9c6d57', + 'brownish green': '#6a6e09', + 'brownish grey': '#86775f', + 'brownish orange': '#cb7723', + 'brownish pink': '#c27e79', + 'brownish purple': '#76424e', + 'brownish red': '#9e3623', + 'brownish yellow': '#c9b003', + 'browny green': '#6f6c0a', + 'browny orange': '#ca6b02', + 'bruise': '#7e4071', + 'bubble gum pink': '#ff69af', + 'bubblegum': '#ff6cb5', + 'bubblegum pink': '#fe83cc', + 'buff': '#fef69e', + 'burgundy': '#610023', + 'burnt orange': '#c04e01', + 'burnt red': '#9f2305', + 'burnt siena': '#b75203', + 'burnt sienna': '#b04e0f', + 'burnt umber': '#a0450e', + 'burnt yellow': '#d5ab09', + 'burple': '#6832e3', + 'butter': '#ffff81', + 'butter yellow': '#fffd74', + 'butterscotch': '#fdb147', + 'cadet blue': '#4e7496', + 'camel': '#c69f59', + 'camo': '#7f8f4e', + 'camo green': '#526525', + 'camouflage green': '#4b6113', + 'canary': '#fdff63', + 'canary yellow': '#fffe40', + 'candy pink': '#ff63e9', + 'caramel': '#af6f09', + 'carmine': '#9d0216', + 'carnation': '#fd798f', + 'carnation pink': '#ff7fa7', + 'carolina blue': '#8ab8fe', + 'celadon': '#befdb7', + 'celery': '#c1fd95', + 'cement': '#a5a391', + 'cerise': '#de0c62', + 'cerulean': '#0485d1', + 'cerulean blue': '#056eee', + 'charcoal': '#343837', + 'charcoal grey': '#3c4142', + 'chartreuse': '#c1f80a', + 'cherry': '#cf0234', + 'cherry red': '#f7022a', + 'chestnut': '#742802', + 'chocolate': '#3d1c02', + 'chocolate brown': '#411900', + 'cinnamon': '#ac4f06', + 'claret': '#680018', + 'clay': '#b66a50', + 'clay brown': '#b2713d', + 'clear blue': '#247afd', + 'cloudy blue': '#acc2d9', + 'cobalt': '#1e488f', + 'cobalt blue': '#030aa7', + 'cocoa': '#875f42', + 'coffee': '#a6814c', + 'cool blue': '#4984b8', + 'cool green': '#33b864', + 'cool grey': '#95a3a6', + 'copper': '#b66325', + 'coral': '#fc5a50', + 'coral pink': '#ff6163', + 'cornflower': '#6a79f7', + 'cornflower blue': '#5170d7', + 'cranberry': '#9e003a', + 'cream': '#ffffc2', + 'creme': '#ffffb6', + 'crimson': '#8c000f', + 'custard': '#fffd78', + 'cyan': '#00ffff', + 'dandelion': '#fedf08', + 'dark': '#1b2431', + 'dark aqua': '#05696b', + 'dark aquamarine': '#017371', + 'dark beige': '#ac9362', + 'dark blue': '#00035b', + 'dark blue green': '#005249', + 'dark blue grey': '#1f3b4d', + 'dark brown': '#341c02', + 'dark coral': '#cf524e', + 'dark cream': '#fff39a', + 'dark cyan': '#0a888a', + 'dark forest green': '#002d04', + 'dark fuchsia': '#9d0759', + 'dark gold': '#b59410', + 'dark grass green': '#388004', + 'dark green': '#033500', + 'dark green blue': '#1f6357', + 'dark grey': '#363737', + 'dark grey blue': '#29465b', + 'dark hot pink': '#d90166', + 'dark indigo': '#1f0954', + 'dark khaki': '#9b8f55', + 'dark lavender': '#856798', + 'dark lilac': '#9c6da5', + 'dark lime': '#84b701', + 'dark lime green': '#7ebd01', + 'dark magenta': '#960056', + 'dark maroon': '#3c0008', + 'dark mauve': '#874c62', + 'dark mint': '#48c072', + 'dark mint green': '#20c073', + 'dark mustard': '#a88905', + 'dark navy': '#000435', + 'dark navy blue': '#00022e', + 'dark olive': '#373e02', + 'dark olive green': '#3c4d03', + 'dark orange': '#c65102', + 'dark pastel green': '#56ae57', + 'dark peach': '#de7e5d', + 'dark periwinkle': '#665fd1', + 'dark pink': '#cb416b', + 'dark plum': '#3f012c', + 'dark purple': '#35063e', + 'dark red': '#840000', + 'dark rose': '#b5485d', + 'dark royal blue': '#02066f', + 'dark sage': '#598556', + 'dark salmon': '#c85a53', + 'dark sand': '#a88f59', + 'dark sea green': '#11875d', + 'dark seafoam': '#1fb57a', + 'dark seafoam green': '#3eaf76', + 'dark sky blue': '#448ee4', + 'dark slate blue': '#214761', + 'dark tan': '#af884a', + 'dark taupe': '#7f684e', + 'dark teal': '#014d4e', + 'dark turquoise': '#045c5a', + 'dark violet': '#34013f', + 'dark yellow': '#d5b60a', + 'dark yellow green': '#728f02', + 'darkblue': '#030764', + 'darkgreen': '#054907', + 'darkish blue': '#014182', + 'darkish green': '#287c37', + 'darkish pink': '#da467d', + 'darkish purple': '#751973', + 'darkish red': '#a90308', + 'deep aqua': '#08787f', + 'deep blue': '#040273', + 'deep brown': '#410200', + 'deep green': '#02590f', + 'deep lavender': '#8d5eb7', + 'deep lilac': '#966ebd', + 'deep magenta': '#a0025c', + 'deep orange': '#dc4d01', + 'deep pink': '#cb0162', + 'deep purple': '#36013f', + 'deep red': '#9a0200', + 'deep rose': '#c74767', + 'deep sea blue': '#015482', + 'deep sky blue': '#0d75f8', + 'deep teal': '#00555a', + 'deep turquoise': '#017374', + 'deep violet': '#490648', + 'denim': '#3b638c', + 'denim blue': '#3b5b92', + 'desert': '#ccad60', + 'diarrhea': '#9f8303', + 'dirt': '#8a6e45', + 'dirt brown': '#836539', + 'dirty blue': '#3f829d', + 'dirty green': '#667e2c', + 'dirty orange': '#c87606', + 'dirty pink': '#ca7b80', + 'dirty purple': '#734a65', + 'dirty yellow': '#cdc50a', + 'dodger blue': '#3e82fc', + 'drab': '#828344', + 'drab green': '#749551', + 'dried blood': '#4b0101', + 'duck egg blue': '#c3fbf4', + 'dull blue': '#49759c', + 'dull brown': '#876e4b', + 'dull green': '#74a662', + 'dull orange': '#d8863b', + 'dull pink': '#d5869d', + 'dull purple': '#84597e', + 'dull red': '#bb3f3f', + 'dull teal': '#5f9e8f', + 'dull yellow': '#eedc5b', + 'dusk': '#4e5481', + 'dusk blue': '#26538d', + 'dusky blue': '#475f94', + 'dusky pink': '#cc7a8b', + 'dusky purple': '#895b7b', + 'dusky rose': '#ba6873', + 'dust': '#b2996e', + 'dusty blue': '#5a86ad', + 'dusty green': '#76a973', + 'dusty lavender': '#ac86a8', + 'dusty orange': '#f0833a', + 'dusty pink': '#d58a94', + 'dusty purple': '#825f87', + 'dusty red': '#b9484e', + 'dusty rose': '#c0737a', + 'dusty teal': '#4c9085', + 'earth': '#a2653e', + 'easter green': '#8cfd7e', + 'easter purple': '#c071fe', + 'ecru': '#feffca', + 'egg shell': '#fffcc4', + 'eggplant': '#380835', + 'eggplant purple': '#430541', + 'eggshell': '#ffffd4', + 'eggshell blue': '#c4fff7', + 'electric blue': '#0652ff', + 'electric green': '#21fc0d', + 'electric lime': '#a8ff04', + 'electric pink': '#ff0490', + 'electric purple': '#aa23ff', + 'emerald': '#01a049', + 'emerald green': '#028f1e', + 'evergreen': '#05472a', + 'faded blue': '#658cbb', + 'faded green': '#7bb274', + 'faded orange': '#f0944d', + 'faded pink': '#de9dac', + 'faded purple': '#916e99', + 'faded red': '#d3494e', + 'faded yellow': '#feff7f', + 'fawn': '#cfaf7b', + 'fern': '#63a950', + 'fern green': '#548d44', + 'fire engine red': '#fe0002', + 'flat blue': '#3c73a8', + 'flat green': '#699d4c', + 'fluorescent green': '#08ff08', + 'fluro green': '#0aff02', + 'foam green': '#90fda9', + 'forest': '#0b5509', + 'forest green': '#06470c', + 'forrest green': '#154406', + 'french blue': '#436bad', + 'fresh green': '#69d84f', + 'frog green': '#58bc08', + 'fuchsia': '#ed0dd9', + 'gold': '#dbb40c', + 'golden': '#f5bf03', + 'golden brown': '#b27a01', + 'golden rod': '#f9bc08', + 'golden yellow': '#fec615', + 'goldenrod': '#fac205', + 'grape': '#6c3461', + 'grape purple': '#5d1451', + 'grapefruit': '#fd5956', + 'grass': '#5cac2d', + 'grass green': '#3f9b0b', + 'grassy green': '#419c03', + 'green': '#15b01a', + 'green apple': '#5edc1f', + 'green blue': '#06b48b', + 'green brown': '#544e03', + 'green grey': '#77926f', + 'green teal': '#0cb577', + 'green yellow': '#c9ff27', + 'green/blue': '#01c08d', + 'green/yellow': '#b5ce08', + 'greenblue': '#23c48b', + 'greenish': '#40a368', + 'greenish beige': '#c9d179', + 'greenish blue': '#0b8b87', + 'greenish brown': '#696112', + 'greenish cyan': '#2afeb7', + 'greenish grey': '#96ae8d', + 'greenish tan': '#bccb7a', + 'greenish teal': '#32bf84', + 'greenish turquoise': '#00fbb0', + 'greenish yellow': '#cdfd02', + 'greeny blue': '#42b395', + 'greeny brown': '#696006', + 'greeny grey': '#7ea07a', + 'greeny yellow': '#c6f808', + 'grey': '#929591', + 'grey blue': '#6b8ba4', + 'grey brown': '#7f7053', + 'grey green': '#789b73', + 'grey pink': '#c3909b', + 'grey purple': '#826d8c', + 'grey teal': '#5e9b8a', + 'grey/blue': '#647d8e', + 'grey/green': '#86a17d', + 'greyblue': '#77a1b5', + 'greyish': '#a8a495', + 'greyish blue': '#5e819d', + 'greyish brown': '#7a6a4f', + 'greyish green': '#82a67d', + 'greyish pink': '#c88d94', + 'greyish purple': '#887191', + 'greyish teal': '#719f91', + 'gross green': '#a0bf16', + 'gunmetal': '#536267', + 'hazel': '#8e7618', + 'heather': '#a484ac', + 'heliotrope': '#d94ff5', + 'highlighter green': '#1bfc06', + 'hospital green': '#9be5aa', + 'hot green': '#25ff29', + 'hot magenta': '#f504c9', + 'hot pink': '#ff028d', + 'hot purple': '#cb00f5', + 'hunter green': '#0b4008', + 'ice': '#d6fffa', + 'ice blue': '#d7fffe', + 'icky green': '#8fae22', + 'indian red': '#850e04', + 'indigo': '#380282', + 'indigo blue': '#3a18b1', + 'iris': '#6258c4', + 'irish green': '#019529', + 'ivory': '#ffffcb', + 'jade': '#1fa774', + 'jade green': '#2baf6a', + 'jungle green': '#048243', + 'kelley green': '#009337', + 'kelly green': '#02ab2e', + 'kermit green': '#5cb200', + 'key lime': '#aeff6e', + 'khaki': '#aaa662', + 'khaki green': '#728639', + 'kiwi': '#9cef43', + 'kiwi green': '#8ee53f', + 'lavender': '#c79fef', + 'lavender blue': '#8b88f8', + 'lavender pink': '#dd85d7', + 'lawn green': '#4da409', + 'leaf': '#71aa34', + 'leaf green': '#5ca904', + 'leafy green': '#51b73b', + 'leather': '#ac7434', + 'lemon': '#fdff52', + 'lemon green': '#adf802', + 'lemon lime': '#bffe28', + 'lemon yellow': '#fdff38', + 'lichen': '#8fb67b', + 'light aqua': '#8cffdb', + 'light aquamarine': '#7bfdc7', + 'light beige': '#fffeb6', + 'light blue': '#95d0fc', + 'light blue green': '#7efbb3', + 'light blue grey': '#b7c9e2', + 'light bluish green': '#76fda8', + 'light bright green': '#53fe5c', + 'light brown': '#ad8150', + 'light burgundy': '#a8415b', + 'light cyan': '#acfffc', + 'light eggplant': '#894585', + 'light forest green': '#4f9153', + 'light gold': '#fddc5c', + 'light grass green': '#9af764', + 'light green': '#96f97b', + 'light green blue': '#56fca2', + 'light greenish blue': '#63f7b4', + 'light grey': '#d8dcd6', + 'light grey blue': '#9dbcd4', + 'light grey green': '#b7e1a1', + 'light indigo': '#6d5acf', + 'light khaki': '#e6f2a2', + 'light lavendar': '#efc0fe', + 'light lavender': '#dfc5fe', + 'light light blue': '#cafffb', + 'light light green': '#c8ffb0', + 'light lilac': '#edc8ff', + 'light lime': '#aefd6c', + 'light lime green': '#b9ff66', + 'light magenta': '#fa5ff7', + 'light maroon': '#a24857', + 'light mauve': '#c292a1', + 'light mint': '#b6ffbb', + 'light mint green': '#a6fbb2', + 'light moss green': '#a6c875', + 'light mustard': '#f7d560', + 'light navy': '#155084', + 'light navy blue': '#2e5a88', + 'light neon green': '#4efd54', + 'light olive': '#acbf69', + 'light olive green': '#a4be5c', + 'light orange': '#fdaa48', + 'light pastel green': '#b2fba5', + 'light pea green': '#c4fe82', + 'light peach': '#ffd8b1', + 'light periwinkle': '#c1c6fc', + 'light pink': '#ffd1df', + 'light plum': '#9d5783', + 'light purple': '#bf77f6', + 'light red': '#ff474c', + 'light rose': '#ffc5cb', + 'light royal blue': '#3a2efe', + 'light sage': '#bcecac', + 'light salmon': '#fea993', + 'light sea green': '#98f6b0', + 'light seafoam': '#a0febf', + 'light seafoam green': '#a7ffb5', + 'light sky blue': '#c6fcff', + 'light tan': '#fbeeac', + 'light teal': '#90e4c1', + 'light turquoise': '#7ef4cc', + 'light urple': '#b36ff6', + 'light violet': '#d6b4fc', + 'light yellow': '#fffe7a', + 'light yellow green': '#ccfd7f', + 'light yellowish green': '#c2ff89', + 'lightblue': '#7bc8f6', + 'lighter green': '#75fd63', + 'lighter purple': '#a55af4', + 'lightgreen': '#76ff7b', + 'lightish blue': '#3d7afd', + 'lightish green': '#61e160', + 'lightish purple': '#a552e6', + 'lightish red': '#fe2f4a', + 'lilac': '#cea2fd', + 'liliac': '#c48efd', + 'lime': '#aaff32', + 'lime green': '#89fe05', + 'lime yellow': '#d0fe1d', + 'lipstick': '#d5174e', + 'lipstick red': '#c0022f', + 'macaroni and cheese': '#efb435', + 'magenta': '#c20078', + 'mahogany': '#4a0100', + 'maize': '#f4d054', + 'mango': '#ffa62b', + 'manilla': '#fffa86', + 'marigold': '#fcc006', + 'marine': '#042e60', + 'marine blue': '#01386a', + 'maroon': '#650021', + 'mauve': '#ae7181', + 'medium blue': '#2c6fbb', + 'medium brown': '#7f5112', + 'medium green': '#39ad48', + 'medium grey': '#7d7f7c', + 'medium pink': '#f36196', + 'medium purple': '#9e43a2', + 'melon': '#ff7855', + 'merlot': '#730039', + 'metallic blue': '#4f738e', + 'mid blue': '#276ab3', + 'mid green': '#50a747', + 'midnight': '#03012d', + 'midnight blue': '#020035', + 'midnight purple': '#280137', + 'military green': '#667c3e', + 'milk chocolate': '#7f4e1e', + 'mint': '#9ffeb0', + 'mint green': '#8fff9f', + 'minty green': '#0bf77d', + 'mocha': '#9d7651', + 'moss': '#769958', + 'moss green': '#658b38', + 'mossy green': '#638b27', + 'mud': '#735c12', + 'mud brown': '#60460f', + 'mud green': '#606602', + 'muddy brown': '#886806', + 'muddy green': '#657432', + 'muddy yellow': '#bfac05', + 'mulberry': '#920a4e', + 'murky green': '#6c7a0e', + 'mushroom': '#ba9e88', + 'mustard': '#ceb301', + 'mustard brown': '#ac7e04', + 'mustard green': '#a8b504', + 'mustard yellow': '#d2bd0a', + 'muted blue': '#3b719f', + 'muted green': '#5fa052', + 'muted pink': '#d1768f', + 'muted purple': '#805b87', + 'nasty green': '#70b23f', + 'navy': '#01153e', + 'navy blue': '#001146', + 'navy green': '#35530a', + 'neon blue': '#04d9ff', + 'neon green': '#0cff0c', + 'neon pink': '#fe019a', + 'neon purple': '#bc13fe', + 'neon red': '#ff073a', + 'neon yellow': '#cfff04', + 'nice blue': '#107ab0', + 'night blue': '#040348', + 'ocean': '#017b92', + 'ocean blue': '#03719c', + 'ocean green': '#3d9973', + 'ocher': '#bf9b0c', + 'ochre': '#bf9005', + 'ocre': '#c69c04', + 'off blue': '#5684ae', + 'off green': '#6ba353', + 'off white': '#ffffe4', + 'off yellow': '#f1f33f', + 'old pink': '#c77986', + 'old rose': '#c87f89', + 'olive': '#6e750e', + 'olive brown': '#645403', + 'olive drab': '#6f7632', + 'olive green': '#677a04', + 'olive yellow': '#c2b709', + 'orange': '#f97306', + 'orange brown': '#be6400', + 'orange pink': '#ff6f52', + 'orange red': '#fd411e', + 'orange yellow': '#ffad01', + 'orangeish': '#fd8d49', + 'orangered': '#fe420f', + 'orangey brown': '#b16002', + 'orangey red': '#fa4224', + 'orangey yellow': '#fdb915', + 'orangish': '#fc824a', + 'orangish brown': '#b25f03', + 'orangish red': '#f43605', + 'orchid': '#c875c4', + 'pale': '#fff9d0', + 'pale aqua': '#b8ffeb', + 'pale blue': '#d0fefe', + 'pale brown': '#b1916e', + 'pale cyan': '#b7fffa', + 'pale gold': '#fdde6c', + 'pale green': '#c7fdb5', + 'pale grey': '#fdfdfe', + 'pale lavender': '#eecffe', + 'pale light green': '#b1fc99', + 'pale lilac': '#e4cbff', + 'pale lime': '#befd73', + 'pale lime green': '#b1ff65', + 'pale magenta': '#d767ad', + 'pale mauve': '#fed0fc', + 'pale olive': '#b9cc81', + 'pale olive green': '#b1d27b', + 'pale orange': '#ffa756', + 'pale peach': '#ffe5ad', + 'pale pink': '#ffcfdc', + 'pale purple': '#b790d4', + 'pale red': '#d9544d', + 'pale rose': '#fdc1c5', + 'pale salmon': '#ffb19a', + 'pale sky blue': '#bdf6fe', + 'pale teal': '#82cbb2', + 'pale turquoise': '#a5fbd5', + 'pale violet': '#ceaefa', + 'pale yellow': '#ffff84', + 'parchment': '#fefcaf', + 'pastel blue': '#a2bffe', + 'pastel green': '#b0ff9d', + 'pastel orange': '#ff964f', + 'pastel pink': '#ffbacd', + 'pastel purple': '#caa0ff', + 'pastel red': '#db5856', + 'pastel yellow': '#fffe71', + 'pea': '#a4bf20', + 'pea green': '#8eab12', + 'pea soup': '#929901', + 'pea soup green': '#94a617', + 'peach': '#ffb07c', + 'peachy pink': '#ff9a8a', + 'peacock blue': '#016795', + 'pear': '#cbf85f', + 'periwinkle': '#8e82fe', + 'periwinkle blue': '#8f99fb', + 'perrywinkle': '#8f8ce7', + 'petrol': '#005f6a', + 'pig pink': '#e78ea5', + 'pine': '#2b5d34', + 'pine green': '#0a481e', + 'pink': '#ff81c0', + 'pink purple': '#db4bda', + 'pink red': '#f5054f', + 'pink/purple': '#ef1de7', + 'pinkish': '#d46a7e', + 'pinkish brown': '#b17261', + 'pinkish grey': '#c8aca9', + 'pinkish orange': '#ff724c', + 'pinkish purple': '#d648d7', + 'pinkish red': '#f10c45', + 'pinkish tan': '#d99b82', + 'pinky': '#fc86aa', + 'pinky purple': '#c94cbe', + 'pinky red': '#fc2647', + 'piss yellow': '#ddd618', + 'pistachio': '#c0fa8b', + 'plum': '#580f41', + 'plum purple': '#4e0550', + 'poison green': '#40fd14', + 'poo': '#8f7303', + 'poo brown': '#885f01', + 'poop': '#7f5e00', + 'poop brown': '#7a5901', + 'poop green': '#6f7c00', + 'powder blue': '#b1d1fc', + 'powder pink': '#ffb2d0', + 'primary blue': '#0804f9', + 'prussian blue': '#004577', + 'puce': '#a57e52', + 'puke': '#a5a502', + 'puke brown': '#947706', + 'puke green': '#9aae07', + 'puke yellow': '#c2be0e', + 'pumpkin': '#e17701', + 'pumpkin orange': '#fb7d07', + 'pure blue': '#0203e2', + 'purple': '#7e1e9c', + 'purple blue': '#632de9', + 'purple brown': '#673a3f', + 'purple grey': '#866f85', + 'purple pink': '#e03fd8', + 'purple red': '#990147', + 'purple/blue': '#5d21d0', + 'purple/pink': '#d725de', + 'purpleish': '#98568d', + 'purpleish blue': '#6140ef', + 'purpleish pink': '#df4ec8', + 'purpley': '#8756e4', + 'purpley blue': '#5f34e7', + 'purpley grey': '#947e94', + 'purpley pink': '#c83cb9', + 'purplish': '#94568c', + 'purplish blue': '#601ef9', + 'purplish brown': '#6b4247', + 'purplish grey': '#7a687f', + 'purplish pink': '#ce5dae', + 'purplish red': '#b0054b', + 'purply': '#983fb2', + 'purply blue': '#661aee', + 'purply pink': '#f075e6', + 'putty': '#beae8a', + 'racing green': '#014600', + 'radioactive green': '#2cfa1f', + 'raspberry': '#b00149', + 'raw sienna': '#9a6200', + 'raw umber': '#a75e09', + 'really light blue': '#d4ffff', + 'red': '#e50000', + 'red brown': '#8b2e16', + 'red orange': '#fd3c06', + 'red pink': '#fa2a55', + 'red purple': '#820747', + 'red violet': '#9e0168', + 'red wine': '#8c0034', + 'reddish': '#c44240', + 'reddish brown': '#7f2b0a', + 'reddish grey': '#997570', + 'reddish orange': '#f8481c', + 'reddish pink': '#fe2c54', + 'reddish purple': '#910951', + 'reddy brown': '#6e1005', + 'rich blue': '#021bf9', + 'rich purple': '#720058', + 'robin egg blue': '#8af1fe', + "robin's egg": '#6dedfd', + "robin's egg blue": '#98eff9', + 'rosa': '#fe86a4', + 'rose': '#cf6275', + 'rose pink': '#f7879a', + 'rose red': '#be013c', + 'rosy pink': '#f6688e', + 'rouge': '#ab1239', + 'royal': '#0c1793', + 'royal blue': '#0504aa', + 'royal purple': '#4b006e', + 'ruby': '#ca0147', + 'russet': '#a13905', + 'rust': '#a83c09', + 'rust brown': '#8b3103', + 'rust orange': '#c45508', + 'rust red': '#aa2704', + 'rusty orange': '#cd5909', + 'rusty red': '#af2f0d', + 'saffron': '#feb209', + 'sage': '#87ae73', + 'sage green': '#88b378', + 'salmon': '#ff796c', + 'salmon pink': '#fe7b7c', + 'sand': '#e2ca76', + 'sand brown': '#cba560', + 'sand yellow': '#fce166', + 'sandstone': '#c9ae74', + 'sandy': '#f1da7a', + 'sandy brown': '#c4a661', + 'sandy yellow': '#fdee73', + 'sap green': '#5c8b15', + 'sapphire': '#2138ab', + 'scarlet': '#be0119', + 'sea': '#3c9992', + 'sea blue': '#047495', + 'sea green': '#53fca1', + 'seafoam': '#80f9ad', + 'seafoam blue': '#78d1b6', + 'seafoam green': '#7af9ab', + 'seaweed': '#18d17b', + 'seaweed green': '#35ad6b', + 'sepia': '#985e2b', + 'shamrock': '#01b44c', + 'shamrock green': '#02c14d', + 'shit': '#7f5f00', + 'shit brown': '#7b5804', + 'shit green': '#758000', + 'shocking pink': '#fe02a2', + 'sick green': '#9db92c', + 'sickly green': '#94b21c', + 'sickly yellow': '#d0e429', + 'sienna': '#a9561e', + 'silver': '#c5c9c7', + 'sky': '#82cafc', + 'sky blue': '#75bbfd', + 'slate': '#516572', + 'slate blue': '#5b7c99', + 'slate green': '#658d6d', + 'slate grey': '#59656d', + 'slime green': '#99cc04', + 'snot': '#acbb0d', + 'snot green': '#9dc100', + 'soft blue': '#6488ea', + 'soft green': '#6fc276', + 'soft pink': '#fdb0c0', + 'soft purple': '#a66fb5', + 'spearmint': '#1ef876', + 'spring green': '#a9f971', + 'spruce': '#0a5f38', + 'squash': '#f2ab15', + 'steel': '#738595', + 'steel blue': '#5a7d9a', + 'steel grey': '#6f828a', + 'stone': '#ada587', + 'stormy blue': '#507b9c', + 'straw': '#fcf679', + 'strawberry': '#fb2943', + 'strong blue': '#0c06f7', + 'strong pink': '#ff0789', + 'sun yellow': '#ffdf22', + 'sunflower': '#ffc512', + 'sunflower yellow': '#ffda03', + 'sunny yellow': '#fff917', + 'sunshine yellow': '#fffd37', + 'swamp': '#698339', + 'swamp green': '#748500', + 'tan': '#d1b26f', + 'tan brown': '#ab7e4c', + 'tan green': '#a9be70', + 'tangerine': '#ff9408', + 'taupe': '#b9a281', + 'tea': '#65ab7c', + 'tea green': '#bdf8a3', + 'teal': '#029386', + 'teal blue': '#01889f', + 'teal green': '#25a36f', + 'tealish': '#24bca8', + 'tealish green': '#0cdc73', + 'terra cotta': '#c9643b', + 'terracota': '#cb6843', + 'terracotta': '#ca6641', + 'tiffany blue': '#7bf2da', + 'tomato': '#ef4026', + 'tomato red': '#ec2d01', + 'topaz': '#13bbaf', + 'toupe': '#c7ac7d', + 'toxic green': '#61de2a', + 'tree green': '#2a7e19', + 'true blue': '#010fcc', + 'true green': '#089404', + 'turquoise': '#06c2ac', + 'turquoise blue': '#06b1c4', + 'turquoise green': '#04f489', + 'turtle green': '#75b84f', + 'twilight': '#4e518b', + 'twilight blue': '#0a437a', + 'ugly blue': '#31668a', + 'ugly brown': '#7d7103', + 'ugly green': '#7a9703', + 'ugly pink': '#cd7584', + 'ugly purple': '#a442a0', + 'ugly yellow': '#d0c101', + 'ultramarine': '#2000b1', + 'ultramarine blue': '#1805db', + 'umber': '#b26400', + 'velvet': '#750851', + 'vermillion': '#f4320c', + 'very dark blue': '#000133', + 'very dark brown': '#1d0200', + 'very dark green': '#062e03', + 'very dark purple': '#2a0134', + 'very light blue': '#d5ffff', + 'very light brown': '#d3b683', + 'very light green': '#d1ffbd', + 'very light pink': '#fff4f2', + 'very light purple': '#f6cefc', + 'very pale blue': '#d6fffe', + 'very pale green': '#cffdbc', + 'vibrant blue': '#0339f8', + 'vibrant green': '#0add08', + 'vibrant purple': '#ad03de', + 'violet': '#9a0eea', + 'violet blue': '#510ac9', + 'violet pink': '#fb5ffc', + 'violet red': '#a50055', + 'viridian': '#1e9167', + 'vivid blue': '#152eff', + 'vivid green': '#2fef10', + 'vivid purple': '#9900fa', + 'vomit': '#a2a415', + 'vomit green': '#89a203', + 'vomit yellow': '#c7c10c', + 'warm blue': '#4b57db', + 'warm brown': '#964e02', + 'warm grey': '#978a84', + 'warm pink': '#fb5581', + 'warm purple': '#952e8f', + 'washed out green': '#bcf5a6', + 'water blue': '#0e87cc', + 'watermelon': '#fd4659', + 'weird green': '#3ae57f', + 'wheat': '#fbdd7e', + 'white': '#ffffff', + 'windows blue': '#3778bf', + 'wine': '#80013f', + 'wine red': '#7b0323', + 'wintergreen': '#20f986', + 'wisteria': '#a87dc2', + 'yellow': '#ffff14', + 'yellow brown': '#b79400', + 'yellow green': '#c0fb2d', + 'yellow ochre': '#cb9d06', + 'yellow orange': '#fcb001', + 'yellow tan': '#ffe36e', + 'yellow/green': '#c8fd3d', + 'yellowgreen': '#bbf90f', + 'yellowish': '#faee66', + 'yellowish brown': '#9b7a01', + 'yellowish green': '#b0dd16', + 'yellowish orange': '#ffab0f', + 'yellowish tan': '#fcfc81', + 'yellowy brown': '#ae8b0c', + 'yellowy green': '#bff128'} diff --git a/testbed/mwaskom__seaborn/seaborn/distributions.py b/testbed/mwaskom__seaborn/seaborn/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0cfacbdf8c5c117307bc906aa90fad390816ca --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/distributions.py @@ -0,0 +1,2546 @@ +"""Plotting functions for visualizing distributions.""" +from numbers import Number +from functools import partial +import math +import textwrap +import warnings + +import numpy as np +import pandas as pd +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.transforms as tx +from matplotlib.colors import to_rgba +from matplotlib.collections import LineCollection + +from ._oldcore import ( + VectorPlotter, +) + +# We have moved univariate histogram computation over to the new Hist class, +# but still use the older Histogram for bivariate computation. +from ._statistics import ECDF, Histogram, KDE +from ._stats.counting import Hist + +from .axisgrid import ( + FacetGrid, + _facet_docs, +) +from .utils import ( + remove_na, + _kde_support, + _normalize_kwargs, + _check_argument, + _assign_default_kwargs, + _default_color, +) +from .palettes import color_palette +from .external import husl +from .external.kde import gaussian_kde +from ._docstrings import ( + DocstringComponents, + _core_docs, +) + + +__all__ = ["displot", "histplot", "kdeplot", "ecdfplot", "rugplot", "distplot"] + +# ==================================================================================== # +# Module documentation +# ==================================================================================== # + +_dist_params = dict( + + multiple=""" +multiple : {{"layer", "stack", "fill"}} + Method for drawing multiple elements when semantic mapping creates subsets. + Only relevant with univariate data. + """, + log_scale=""" +log_scale : bool or number, or pair of bools or numbers + Set axis scale(s) to log. A single value sets the data axis for univariate + distributions and both axes for bivariate distributions. A pair of values + sets each axis independently. Numeric values are interpreted as the desired + base (default 10). If `False`, defer to the existing Axes scale. + """, + legend=""" +legend : bool + If False, suppress the legend for semantic variables. + """, + cbar=""" +cbar : bool + If True, add a colorbar to annotate the color mapping in a bivariate plot. + Note: Does not currently support plots with a ``hue`` variable well. + """, + cbar_ax=""" +cbar_ax : :class:`matplotlib.axes.Axes` + Pre-existing axes for the colorbar. + """, + cbar_kws=""" +cbar_kws : dict + Additional parameters passed to :meth:`matplotlib.figure.Figure.colorbar`. + """, +) + +_param_docs = DocstringComponents.from_nested_components( + core=_core_docs["params"], + facets=DocstringComponents(_facet_docs), + dist=DocstringComponents(_dist_params), + kde=DocstringComponents.from_function_params(KDE.__init__), + hist=DocstringComponents.from_function_params(Histogram.__init__), + ecdf=DocstringComponents.from_function_params(ECDF.__init__), +) + + +# ==================================================================================== # +# Internal API +# ==================================================================================== # + + +class _DistributionPlotter(VectorPlotter): + + semantics = "x", "y", "hue", "weights" + + wide_structure = {"x": "@values", "hue": "@columns"} + flat_structure = {"x": "@values"} + + def __init__( + self, + data=None, + variables={}, + ): + + super().__init__(data=data, variables=variables) + + @property + def univariate(self): + """Return True if only x or y are used.""" + # TODO this could go down to core, but putting it here now. + # We'd want to be conceptually clear that univariate only applies + # to x/y and not to other semantics, which can exist. + # We haven't settled on a good conceptual name for x/y. + return bool({"x", "y"} - set(self.variables)) + + @property + def data_variable(self): + """Return the variable with data for univariate plots.""" + # TODO This could also be in core, but it should have a better name. + if not self.univariate: + raise AttributeError("This is not a univariate plot") + return {"x", "y"}.intersection(self.variables).pop() + + @property + def has_xy_data(self): + """Return True at least one of x or y is defined.""" + # TODO see above points about where this should go + return bool({"x", "y"} & set(self.variables)) + + def _add_legend( + self, + ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws, + ): + """Add artists that reflect semantic mappings and put then in a legend.""" + # TODO note that this doesn't handle numeric mappings like the relational plots + handles = [] + labels = [] + for level in self._hue_map.levels: + color = self._hue_map(level) + + kws = self._artist_kws( + artist_kws, fill, element, multiple, color, alpha + ) + + # color gets added to the kws to workaround an issue with barplot's color + # cycle integration but it causes problems in this context where we are + # setting artist properties directly, so pop it off here + if "facecolor" in kws: + kws.pop("color", None) + + handles.append(artist(**kws)) + labels.append(level) + + if isinstance(ax_obj, mpl.axes.Axes): + ax_obj.legend(handles, labels, title=self.variables["hue"], **legend_kws) + else: # i.e. a FacetGrid. TODO make this better + legend_data = dict(zip(labels, handles)) + ax_obj.add_legend( + legend_data, + title=self.variables["hue"], + label_order=self.var_levels["hue"], + **legend_kws + ) + + def _artist_kws(self, kws, fill, element, multiple, color, alpha): + """Handle differences between artists in filled/unfilled plots.""" + kws = kws.copy() + if fill: + kws = _normalize_kwargs(kws, mpl.collections.PolyCollection) + kws.setdefault("facecolor", to_rgba(color, alpha)) + + if element == "bars": + # Make bar() interface with property cycle correctly + # https://github.com/matplotlib/matplotlib/issues/19385 + kws["color"] = "none" + + if multiple in ["stack", "fill"] or element == "bars": + kws.setdefault("edgecolor", mpl.rcParams["patch.edgecolor"]) + else: + kws.setdefault("edgecolor", to_rgba(color, 1)) + elif element == "bars": + kws["facecolor"] = "none" + kws["edgecolor"] = to_rgba(color, alpha) + else: + kws["color"] = to_rgba(color, alpha) + return kws + + def _quantile_to_level(self, data, quantile): + """Return data levels corresponding to quantile cuts of mass.""" + isoprop = np.asarray(quantile) + values = np.ravel(data) + sorted_values = np.sort(values)[::-1] + normalized_values = np.cumsum(sorted_values) / values.sum() + idx = np.searchsorted(normalized_values, 1 - isoprop) + levels = np.take(sorted_values, idx, mode="clip") + return levels + + def _cmap_from_color(self, color): + """Return a sequential colormap given a color seed.""" + # Like so much else here, this is broadly useful, but keeping it + # in this class to signify that I haven't thought overly hard about it... + r, g, b, _ = to_rgba(color) + h, s, _ = husl.rgb_to_husl(r, g, b) + xx = np.linspace(-1, 1, int(1.15 * 256))[:256] + ramp = np.zeros((256, 3)) + ramp[:, 0] = h + ramp[:, 1] = s * np.cos(xx) + ramp[:, 2] = np.linspace(35, 80, 256) + colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1) + return mpl.colors.ListedColormap(colors[::-1]) + + def _default_discrete(self): + """Find default values for discrete hist estimation based on variable type.""" + if self.univariate: + discrete = self.var_types[self.data_variable] == "categorical" + else: + discrete_x = self.var_types["x"] == "categorical" + discrete_y = self.var_types["y"] == "categorical" + discrete = discrete_x, discrete_y + return discrete + + def _resolve_multiple(self, curves, multiple): + """Modify the density data structure to handle multiple densities.""" + + # Default baselines have all densities starting at 0 + baselines = {k: np.zeros_like(v) for k, v in curves.items()} + + # TODO we should have some central clearinghouse for checking if any + # "grouping" (terminnology?) semantics have been assigned + if "hue" not in self.variables: + return curves, baselines + + if multiple in ("stack", "fill"): + + # Setting stack or fill means that the curves share a + # support grid / set of bin edges, so we can make a dataframe + # Reverse the column order to plot from top to bottom + curves = pd.DataFrame(curves).iloc[:, ::-1] + + # Find column groups that are nested within col/row variables + column_groups = {} + for i, keyd in enumerate(map(dict, curves.columns)): + facet_key = keyd.get("col", None), keyd.get("row", None) + column_groups.setdefault(facet_key, []) + column_groups[facet_key].append(i) + + baselines = curves.copy() + for col_idxs in column_groups.values(): + cols = curves.columns[col_idxs] + + norm_constant = curves[cols].sum(axis="columns") + + # Take the cumulative sum to stack + curves[cols] = curves[cols].cumsum(axis="columns") + + # Normalize by row sum to fill + if multiple == "fill": + curves[cols] = curves[cols].div(norm_constant, axis="index") + + # Define where each segment starts + baselines[cols] = curves[cols].shift(1, axis=1).fillna(0) + + if multiple == "dodge": + + # Account for the unique semantic (non-faceting) levels + # This will require rethiniking if we add other semantics! + hue_levels = self.var_levels["hue"] + n = len(hue_levels) + for key in curves: + level = dict(key)["hue"] + hist = curves[key].reset_index(name="heights") + level_idx = hue_levels.index(level) + if self._log_scaled(self.data_variable): + log_min = np.log10(hist["edges"]) + log_max = np.log10(hist["edges"] + hist["widths"]) + log_width = (log_max - log_min) / n + new_min = np.power(10, log_min + level_idx * log_width) + new_max = np.power(10, log_min + (level_idx + 1) * log_width) + hist["widths"] = new_max - new_min + hist["edges"] = new_min + else: + hist["widths"] /= n + hist["edges"] += level_idx * hist["widths"] + + curves[key] = hist.set_index(["edges", "widths"])["heights"] + + return curves, baselines + + # -------------------------------------------------------------------------------- # + # Computation + # -------------------------------------------------------------------------------- # + + def _compute_univariate_density( + self, + data_variable, + common_norm, + common_grid, + estimate_kws, + log_scale, + warn_singular=True, + ): + + # Initialize the estimator object + estimator = KDE(**estimate_kws) + + if set(self.variables) - {"x", "y"}: + if common_grid: + all_observations = self.comp_data.dropna() + estimator.define_support(all_observations[data_variable]) + else: + common_norm = False + + all_data = self.plot_data.dropna() + if common_norm and "weights" in all_data: + whole_weight = all_data["weights"].sum() + else: + whole_weight = len(all_data) + + densities = {} + + for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): + + # Extract the data points from this sub set and remove nulls + observations = sub_data[data_variable] + + # Extract the weights for this subset of observations + if "weights" in self.variables: + weights = sub_data["weights"] + part_weight = weights.sum() + else: + weights = None + part_weight = len(sub_data) + + # Estimate the density of observations at this level + variance = np.nan_to_num(observations.var()) + singular = len(observations) < 2 or math.isclose(variance, 0) + try: + if not singular: + # Convoluted approach needed because numerical failures + # can manifest in a few different ways. + density, support = estimator(observations, weights=weights) + except np.linalg.LinAlgError: + singular = True + + if singular: + msg = ( + "Dataset has 0 variance; skipping density estimate. " + "Pass `warn_singular=False` to disable this warning." + ) + if warn_singular: + warnings.warn(msg, UserWarning, stacklevel=4) + continue + + if log_scale: + support = np.power(10, support) + + # Apply a scaling factor so that the integral over all subsets is 1 + if common_norm: + density *= part_weight / whole_weight + + # Store the density for this level + key = tuple(sub_vars.items()) + densities[key] = pd.Series(density, index=support) + + return densities + + # -------------------------------------------------------------------------------- # + # Plotting + # -------------------------------------------------------------------------------- # + + def plot_univariate_histogram( + self, + multiple, + element, + fill, + common_norm, + common_bins, + shrink, + kde, + kde_kws, + color, + legend, + line_kws, + estimate_kws, + **plot_kws, + ): + + # -- Default keyword dicts + kde_kws = {} if kde_kws is None else kde_kws.copy() + line_kws = {} if line_kws is None else line_kws.copy() + estimate_kws = {} if estimate_kws is None else estimate_kws.copy() + + # -- Input checking + _check_argument("multiple", ["layer", "stack", "fill", "dodge"], multiple) + _check_argument("element", ["bars", "step", "poly"], element) + + auto_bins_with_weights = ( + "weights" in self.variables + and estimate_kws["bins"] == "auto" + and estimate_kws["binwidth"] is None + and not estimate_kws["discrete"] + ) + if auto_bins_with_weights: + msg = ( + "`bins` cannot be 'auto' when using weights. " + "Setting `bins=10`, but you will likely want to adjust." + ) + warnings.warn(msg, UserWarning) + estimate_kws["bins"] = 10 + + # Simplify downstream code if we are not normalizing + if estimate_kws["stat"] == "count": + common_norm = False + + orient = self.data_variable + + # Now initialize the Histogram estimator + estimator = Hist(**estimate_kws) + histograms = {} + + # Do pre-compute housekeeping related to multiple groups + all_data = self.comp_data.dropna() + all_weights = all_data.get("weights", None) + + multiple_histograms = set(self.variables) - {"x", "y"} + if multiple_histograms: + if common_bins: + bin_kws = estimator._define_bin_params(all_data, orient, None) + else: + common_norm = False + + if common_norm and all_weights is not None: + whole_weight = all_weights.sum() + else: + whole_weight = len(all_data) + + # Estimate the smoothed kernel densities, for use later + if kde: + # TODO alternatively, clip at min/max bins? + kde_kws.setdefault("cut", 0) + kde_kws["cumulative"] = estimate_kws["cumulative"] + log_scale = self._log_scaled(self.data_variable) + densities = self._compute_univariate_density( + self.data_variable, + common_norm, + common_bins, + kde_kws, + log_scale, + warn_singular=False, + ) + + # First pass through the data to compute the histograms + for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): + + # Prepare the relevant data + key = tuple(sub_vars.items()) + orient = self.data_variable + + if "weights" in self.variables: + sub_data["weight"] = sub_data.pop("weights") + part_weight = sub_data["weight"].sum() + else: + part_weight = len(sub_data) + + # Do the histogram computation + if not (multiple_histograms and common_bins): + bin_kws = estimator._define_bin_params(sub_data, orient, None) + res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws)) + heights = res[estimator.stat].to_numpy() + widths = res["space"].to_numpy() + edges = res[orient].to_numpy() - widths / 2 + + # Rescale the smoothed curve to match the histogram + if kde and key in densities: + density = densities[key] + if estimator.cumulative: + hist_norm = heights.max() + else: + hist_norm = (heights * widths).sum() + densities[key] *= hist_norm + + # Convert edges back to original units for plotting + if self._log_scaled(self.data_variable): + widths = np.power(10, edges + widths) - np.power(10, edges) + edges = np.power(10, edges) + + # Pack the histogram data and metadata together + edges = edges + (1 - shrink) / 2 * widths + widths *= shrink + index = pd.MultiIndex.from_arrays([ + pd.Index(edges, name="edges"), + pd.Index(widths, name="widths"), + ]) + hist = pd.Series(heights, index=index, name="heights") + + # Apply scaling to normalize across groups + if common_norm: + hist *= part_weight / whole_weight + + # Store the finalized histogram data for future plotting + histograms[key] = hist + + # Modify the histogram and density data to resolve multiple groups + histograms, baselines = self._resolve_multiple(histograms, multiple) + if kde: + densities, _ = self._resolve_multiple( + densities, None if multiple == "dodge" else multiple + ) + + # Set autoscaling-related meta + sticky_stat = (0, 1) if multiple == "fill" else (0, np.inf) + if multiple == "fill": + # Filled plots should not have any margins + bin_vals = histograms.index.to_frame() + edges = bin_vals["edges"] + widths = bin_vals["widths"] + sticky_data = ( + edges.min(), + edges.max() + widths.loc[edges.idxmax()] + ) + else: + sticky_data = [] + + # --- Handle default visual attributes + + # Note: default linewidth is determined after plotting + + # Default alpha should depend on other parameters + if fill: + # Note: will need to account for other grouping semantics if added + if "hue" in self.variables and multiple == "layer": + default_alpha = .5 if element == "bars" else .25 + elif kde: + default_alpha = .5 + else: + default_alpha = .75 + else: + default_alpha = 1 + alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? + + hist_artists = [] + + # Go back through the dataset and draw the plots + for sub_vars, _ in self.iter_data("hue", reverse=True): + + key = tuple(sub_vars.items()) + hist = histograms[key].rename("heights").reset_index() + bottom = np.asarray(baselines[key]) + + ax = self._get_axes(sub_vars) + + # Define the matplotlib attributes that depend on semantic mapping + if "hue" in self.variables: + sub_color = self._hue_map(sub_vars["hue"]) + else: + sub_color = color + + artist_kws = self._artist_kws( + plot_kws, fill, element, multiple, sub_color, alpha + ) + + if element == "bars": + + # Use matplotlib bar plotting + + plot_func = ax.bar if self.data_variable == "x" else ax.barh + artists = plot_func( + hist["edges"], + hist["heights"] - bottom, + hist["widths"], + bottom, + align="edge", + **artist_kws, + ) + + for bar in artists: + if self.data_variable == "x": + bar.sticky_edges.x[:] = sticky_data + bar.sticky_edges.y[:] = sticky_stat + else: + bar.sticky_edges.x[:] = sticky_stat + bar.sticky_edges.y[:] = sticky_data + + hist_artists.extend(artists) + + else: + + # Use either fill_between or plot to draw hull of histogram + if element == "step": + + final = hist.iloc[-1] + x = np.append(hist["edges"], final["edges"] + final["widths"]) + y = np.append(hist["heights"], final["heights"]) + b = np.append(bottom, bottom[-1]) + + if self.data_variable == "x": + step = "post" + drawstyle = "steps-post" + else: + step = "post" # fillbetweenx handles mapping internally + drawstyle = "steps-pre" + + elif element == "poly": + + x = hist["edges"] + hist["widths"] / 2 + y = hist["heights"] + b = bottom + + step = None + drawstyle = None + + if self.data_variable == "x": + if fill: + artist = ax.fill_between(x, b, y, step=step, **artist_kws) + else: + artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws) + artist.sticky_edges.x[:] = sticky_data + artist.sticky_edges.y[:] = sticky_stat + else: + if fill: + artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws) + else: + artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws) + artist.sticky_edges.x[:] = sticky_stat + artist.sticky_edges.y[:] = sticky_data + + hist_artists.append(artist) + + if kde: + + # Add in the density curves + + try: + density = densities[key] + except KeyError: + continue + support = density.index + + if "x" in self.variables: + line_args = support, density + sticky_x, sticky_y = None, (0, np.inf) + else: + line_args = density, support + sticky_x, sticky_y = (0, np.inf), None + + line_kws["color"] = to_rgba(sub_color, 1) + line, = ax.plot( + *line_args, **line_kws, + ) + + if sticky_x is not None: + line.sticky_edges.x[:] = sticky_x + if sticky_y is not None: + line.sticky_edges.y[:] = sticky_y + + if element == "bars" and "linewidth" not in plot_kws: + + # Now we handle linewidth, which depends on the scaling of the plot + + # We will base everything on the minimum bin width + hist_metadata = pd.concat([ + # Use .items for generality over dict or df + h.index.to_frame() for _, h in histograms.items() + ]).reset_index(drop=True) + thin_bar_idx = hist_metadata["widths"].idxmin() + binwidth = hist_metadata.loc[thin_bar_idx, "widths"] + left_edge = hist_metadata.loc[thin_bar_idx, "edges"] + + # Set initial value + default_linewidth = math.inf + + # Loop through subsets based only on facet variables + for sub_vars, _ in self.iter_data(): + + ax = self._get_axes(sub_vars) + + # Needed in some cases to get valid transforms. + # Innocuous in other cases? + ax.autoscale_view() + + # Convert binwidth from data coordinates to pixels + pts_x, pts_y = 72 / ax.figure.dpi * abs( + ax.transData.transform([left_edge + binwidth] * 2) + - ax.transData.transform([left_edge] * 2) + ) + if self.data_variable == "x": + binwidth_points = pts_x + else: + binwidth_points = pts_y + + # The relative size of the lines depends on the appearance + # This is a provisional value and may need more tweaking + default_linewidth = min(.1 * binwidth_points, default_linewidth) + + # Set the attributes + for bar in hist_artists: + + # Don't let the lines get too thick + max_linewidth = bar.get_linewidth() + if not fill: + max_linewidth *= 1.5 + + linewidth = min(default_linewidth, max_linewidth) + + # If not filling, don't let lines disappear + if not fill: + min_linewidth = .5 + linewidth = max(linewidth, min_linewidth) + + bar.set_linewidth(linewidth) + + # --- Finalize the plot ---- + + # Axis labels + ax = self.ax if self.ax is not None else self.facets.axes.flat[0] + default_x = default_y = "" + if self.data_variable == "x": + default_y = estimator.stat.capitalize() + if self.data_variable == "y": + default_x = estimator.stat.capitalize() + self._add_axis_labels(ax, default_x, default_y) + + # Legend for semantic variables + if "hue" in self.variables and legend: + + if fill or element == "bars": + artist = partial(mpl.patches.Patch) + else: + artist = partial(mpl.lines.Line2D, [], []) + + ax_obj = self.ax if self.ax is not None else self.facets + self._add_legend( + ax_obj, artist, fill, element, multiple, alpha, plot_kws, {}, + ) + + def plot_bivariate_histogram( + self, + common_bins, common_norm, + thresh, pthresh, pmax, + color, legend, + cbar, cbar_ax, cbar_kws, + estimate_kws, + **plot_kws, + ): + + # Default keyword dicts + cbar_kws = {} if cbar_kws is None else cbar_kws.copy() + + # Now initialize the Histogram estimator + estimator = Histogram(**estimate_kws) + + # Do pre-compute housekeeping related to multiple groups + if set(self.variables) - {"x", "y"}: + all_data = self.comp_data.dropna() + if common_bins: + estimator.define_bin_params( + all_data["x"], + all_data["y"], + all_data.get("weights", None), + ) + else: + common_norm = False + + # -- Determine colormap threshold and norm based on the full data + + full_heights = [] + for _, sub_data in self.iter_data(from_comp_data=True): + sub_heights, _ = estimator( + sub_data["x"], sub_data["y"], sub_data.get("weights", None) + ) + full_heights.append(sub_heights) + + common_color_norm = not set(self.variables) - {"x", "y"} or common_norm + + if pthresh is not None and common_color_norm: + thresh = self._quantile_to_level(full_heights, pthresh) + + plot_kws.setdefault("vmin", 0) + if common_color_norm: + if pmax is not None: + vmax = self._quantile_to_level(full_heights, pmax) + else: + vmax = plot_kws.pop("vmax", max(map(np.max, full_heights))) + else: + vmax = None + + # Get a default color + # (We won't follow the color cycle here, as multiple plots are unlikely) + if color is None: + color = "C0" + + # --- Loop over data (subsets) and draw the histograms + for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): + + if sub_data.empty: + continue + + # Do the histogram computation + heights, (x_edges, y_edges) = estimator( + sub_data["x"], + sub_data["y"], + weights=sub_data.get("weights", None), + ) + + # Check for log scaling on the data axis + if self._log_scaled("x"): + x_edges = np.power(10, x_edges) + if self._log_scaled("y"): + y_edges = np.power(10, y_edges) + + # Apply scaling to normalize across groups + if estimator.stat != "count" and common_norm: + heights *= len(sub_data) / len(all_data) + + # Define the specific kwargs for this artist + artist_kws = plot_kws.copy() + if "hue" in self.variables: + color = self._hue_map(sub_vars["hue"]) + cmap = self._cmap_from_color(color) + artist_kws["cmap"] = cmap + else: + cmap = artist_kws.pop("cmap", None) + if isinstance(cmap, str): + cmap = color_palette(cmap, as_cmap=True) + elif cmap is None: + cmap = self._cmap_from_color(color) + artist_kws["cmap"] = cmap + + # Set the upper norm on the colormap + if not common_color_norm and pmax is not None: + vmax = self._quantile_to_level(heights, pmax) + if vmax is not None: + artist_kws["vmax"] = vmax + + # Make cells at or below the threshold transparent + if not common_color_norm and pthresh: + thresh = self._quantile_to_level(heights, pthresh) + if thresh is not None: + heights = np.ma.masked_less_equal(heights, thresh) + + # Get the axes for this plot + ax = self._get_axes(sub_vars) + + # pcolormesh is going to turn the grid off, but we want to keep it + # I'm not sure if there's a better way to get the grid state + x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()]) + y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()]) + + mesh = ax.pcolormesh( + x_edges, + y_edges, + heights.T, + **artist_kws, + ) + + # pcolormesh sets sticky edges, but we only want them if not thresholding + if thresh is not None: + mesh.sticky_edges.x[:] = [] + mesh.sticky_edges.y[:] = [] + + # Add an optional colorbar + # Note, we want to improve this. When hue is used, it will stack + # multiple colorbars with redundant ticks in an ugly way. + # But it's going to take some work to have multiple colorbars that + # share ticks nicely. + if cbar: + ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws) + + # Reset the grid state + if x_grid: + ax.grid(True, axis="x") + if y_grid: + ax.grid(True, axis="y") + + # --- Finalize the plot + + ax = self.ax if self.ax is not None else self.facets.axes.flat[0] + self._add_axis_labels(ax) + + if "hue" in self.variables and legend: + + # TODO if possible, I would like to move the contour + # intensity information into the legend too and label the + # iso proportions rather than the raw density values + + artist_kws = {} + artist = partial(mpl.patches.Patch) + ax_obj = self.ax if self.ax is not None else self.facets + self._add_legend( + ax_obj, artist, True, False, "layer", 1, artist_kws, {}, + ) + + def plot_univariate_density( + self, + multiple, + common_norm, + common_grid, + warn_singular, + fill, + color, + legend, + estimate_kws, + **plot_kws, + ): + + # Handle conditional defaults + if fill is None: + fill = multiple in ("stack", "fill") + + # Preprocess the matplotlib keyword dictionaries + if fill: + artist = mpl.collections.PolyCollection + else: + artist = mpl.lines.Line2D + plot_kws = _normalize_kwargs(plot_kws, artist) + + # Input checking + _check_argument("multiple", ["layer", "stack", "fill"], multiple) + + # Always share the evaluation grid when stacking + subsets = bool(set(self.variables) - {"x", "y"}) + if subsets and multiple in ("stack", "fill"): + common_grid = True + + # Check if the data axis is log scaled + log_scale = self._log_scaled(self.data_variable) + + # Do the computation + densities = self._compute_univariate_density( + self.data_variable, + common_norm, + common_grid, + estimate_kws, + log_scale, + warn_singular, + ) + + # Adjust densities based on the `multiple` rule + densities, baselines = self._resolve_multiple(densities, multiple) + + # Control the interaction with autoscaling by defining sticky_edges + # i.e. we don't want autoscale margins below the density curve + sticky_density = (0, 1) if multiple == "fill" else (0, np.inf) + + if multiple == "fill": + # Filled plots should not have any margins + sticky_support = densities.index.min(), densities.index.max() + else: + sticky_support = [] + + if fill: + if multiple == "layer": + default_alpha = .25 + else: + default_alpha = .75 + else: + default_alpha = 1 + alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? + + # Now iterate through the subsets and draw the densities + # We go backwards so stacked densities read from top-to-bottom + for sub_vars, _ in self.iter_data("hue", reverse=True): + + # Extract the support grid and density curve for this level + key = tuple(sub_vars.items()) + try: + density = densities[key] + except KeyError: + continue + support = density.index + fill_from = baselines[key] + + ax = self._get_axes(sub_vars) + + if "hue" in self.variables: + sub_color = self._hue_map(sub_vars["hue"]) + else: + sub_color = color + + artist_kws = self._artist_kws( + plot_kws, fill, False, multiple, sub_color, alpha + ) + + # Either plot a curve with observation values on the x axis + if "x" in self.variables: + + if fill: + artist = ax.fill_between(support, fill_from, density, **artist_kws) + + else: + artist, = ax.plot(support, density, **artist_kws) + + artist.sticky_edges.x[:] = sticky_support + artist.sticky_edges.y[:] = sticky_density + + # Or plot a curve with observation values on the y axis + else: + if fill: + artist = ax.fill_betweenx(support, fill_from, density, **artist_kws) + else: + artist, = ax.plot(density, support, **artist_kws) + + artist.sticky_edges.x[:] = sticky_density + artist.sticky_edges.y[:] = sticky_support + + # --- Finalize the plot ---- + + ax = self.ax if self.ax is not None else self.facets.axes.flat[0] + default_x = default_y = "" + if self.data_variable == "x": + default_y = "Density" + if self.data_variable == "y": + default_x = "Density" + self._add_axis_labels(ax, default_x, default_y) + + if "hue" in self.variables and legend: + + if fill: + artist = partial(mpl.patches.Patch) + else: + artist = partial(mpl.lines.Line2D, [], []) + + ax_obj = self.ax if self.ax is not None else self.facets + self._add_legend( + ax_obj, artist, fill, False, multiple, alpha, plot_kws, {}, + ) + + def plot_bivariate_density( + self, + common_norm, + fill, + levels, + thresh, + color, + legend, + cbar, + warn_singular, + cbar_ax, + cbar_kws, + estimate_kws, + **contour_kws, + ): + + contour_kws = contour_kws.copy() + + estimator = KDE(**estimate_kws) + + if not set(self.variables) - {"x", "y"}: + common_norm = False + + all_data = self.plot_data.dropna() + + # Loop through the subsets and estimate the KDEs + densities, supports = {}, {} + + for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): + + # Extract the data points from this sub set + observations = sub_data[["x", "y"]] + min_variance = observations.var().fillna(0).min() + observations = observations["x"], observations["y"] + + # Extract the weights for this subset of observations + if "weights" in self.variables: + weights = sub_data["weights"] + else: + weights = None + + # Estimate the density of observations at this level + singular = math.isclose(min_variance, 0) + try: + if not singular: + density, support = estimator(*observations, weights=weights) + except np.linalg.LinAlgError: + # Testing for 0 variance doesn't catch all cases where scipy raises, + # but we can also get a ValueError, so we need this convoluted approach + singular = True + + if singular: + msg = ( + "KDE cannot be estimated (0 variance or perfect covariance). " + "Pass `warn_singular=False` to disable this warning." + ) + if warn_singular: + warnings.warn(msg, UserWarning, stacklevel=3) + continue + + # Transform the support grid back to the original scale + xx, yy = support + if self._log_scaled("x"): + xx = np.power(10, xx) + if self._log_scaled("y"): + yy = np.power(10, yy) + support = xx, yy + + # Apply a scaling factor so that the integral over all subsets is 1 + if common_norm: + density *= len(sub_data) / len(all_data) + + key = tuple(sub_vars.items()) + densities[key] = density + supports[key] = support + + # Define a grid of iso-proportion levels + if thresh is None: + thresh = 0 + if isinstance(levels, Number): + levels = np.linspace(thresh, 1, levels) + else: + if min(levels) < 0 or max(levels) > 1: + raise ValueError("levels must be in [0, 1]") + + # Transform from iso-proportions to iso-densities + if common_norm: + common_levels = self._quantile_to_level( + list(densities.values()), levels, + ) + draw_levels = {k: common_levels for k in densities} + else: + draw_levels = { + k: self._quantile_to_level(d, levels) + for k, d in densities.items() + } + + # Define the coloring of the contours + if "hue" in self.variables: + for param in ["cmap", "colors"]: + if param in contour_kws: + msg = f"{param} parameter ignored when using hue mapping." + warnings.warn(msg, UserWarning) + contour_kws.pop(param) + else: + + # Work out a default coloring of the contours + coloring_given = set(contour_kws) & {"cmap", "colors"} + if fill and not coloring_given: + cmap = self._cmap_from_color(color) + contour_kws["cmap"] = cmap + if not fill and not coloring_given: + contour_kws["colors"] = [color] + + # Use our internal colormap lookup + cmap = contour_kws.pop("cmap", None) + if isinstance(cmap, str): + cmap = color_palette(cmap, as_cmap=True) + if cmap is not None: + contour_kws["cmap"] = cmap + + # Loop through the subsets again and plot the data + for sub_vars, _ in self.iter_data("hue"): + + if "hue" in sub_vars: + color = self._hue_map(sub_vars["hue"]) + if fill: + contour_kws["cmap"] = self._cmap_from_color(color) + else: + contour_kws["colors"] = [color] + + ax = self._get_axes(sub_vars) + + # Choose the function to plot with + # TODO could add a pcolormesh based option as well + # Which would look something like element="raster" + if fill: + contour_func = ax.contourf + else: + contour_func = ax.contour + + key = tuple(sub_vars.items()) + if key not in densities: + continue + density = densities[key] + xx, yy = supports[key] + + label = contour_kws.pop("label", None) + + cset = contour_func( + xx, yy, density, + levels=draw_levels[key], + **contour_kws, + ) + + if "hue" not in self.variables: + cset.collections[0].set_label(label) + + # Add a color bar representing the contour heights + # Note: this shows iso densities, not iso proportions + # See more notes in histplot about how this could be improved + if cbar: + cbar_kws = {} if cbar_kws is None else cbar_kws + ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws) + + # --- Finalize the plot + ax = self.ax if self.ax is not None else self.facets.axes.flat[0] + self._add_axis_labels(ax) + + if "hue" in self.variables and legend: + + # TODO if possible, I would like to move the contour + # intensity information into the legend too and label the + # iso proportions rather than the raw density values + + artist_kws = {} + if fill: + artist = partial(mpl.patches.Patch) + else: + artist = partial(mpl.lines.Line2D, [], []) + + ax_obj = self.ax if self.ax is not None else self.facets + self._add_legend( + ax_obj, artist, fill, False, "layer", 1, artist_kws, {}, + ) + + def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws): + + estimator = ECDF(**estimate_kws) + + # Set the draw style to step the right way for the data variable + drawstyles = dict(x="steps-post", y="steps-pre") + plot_kws["drawstyle"] = drawstyles[self.data_variable] + + # Loop through the subsets, transform and plot the data + for sub_vars, sub_data in self.iter_data( + "hue", reverse=True, from_comp_data=True, + ): + + # Compute the ECDF + if sub_data.empty: + continue + + observations = sub_data[self.data_variable] + weights = sub_data.get("weights", None) + stat, vals = estimator(observations, weights=weights) + + # Assign attributes based on semantic mapping + artist_kws = plot_kws.copy() + if "hue" in self.variables: + artist_kws["color"] = self._hue_map(sub_vars["hue"]) + + # Return the data variable to the linear domain + # This needs an automatic solution; see GH2409 + if self._log_scaled(self.data_variable): + vals = np.power(10, vals) + vals[0] = -np.inf + + # Work out the orientation of the plot + if self.data_variable == "x": + plot_args = vals, stat + stat_variable = "y" + else: + plot_args = stat, vals + stat_variable = "x" + + if estimator.stat == "count": + top_edge = len(observations) + else: + top_edge = 1 + + # Draw the line for this subset + ax = self._get_axes(sub_vars) + artist, = ax.plot(*plot_args, **artist_kws) + sticky_edges = getattr(artist.sticky_edges, stat_variable) + sticky_edges[:] = 0, top_edge + + # --- Finalize the plot ---- + ax = self.ax if self.ax is not None else self.facets.axes.flat[0] + stat = estimator.stat.capitalize() + default_x = default_y = "" + if self.data_variable == "x": + default_y = stat + if self.data_variable == "y": + default_x = stat + self._add_axis_labels(ax, default_x, default_y) + + if "hue" in self.variables and legend: + artist = partial(mpl.lines.Line2D, [], []) + alpha = plot_kws.get("alpha", 1) + ax_obj = self.ax if self.ax is not None else self.facets + self._add_legend( + ax_obj, artist, False, False, None, alpha, plot_kws, {}, + ) + + def plot_rug(self, height, expand_margins, legend, **kws): + + for sub_vars, sub_data, in self.iter_data(from_comp_data=True): + + ax = self._get_axes(sub_vars) + + kws.setdefault("linewidth", 1) + + if expand_margins: + xmarg, ymarg = ax.margins() + if "x" in self.variables: + ymarg += height * 2 + if "y" in self.variables: + xmarg += height * 2 + ax.margins(x=xmarg, y=ymarg) + + if "hue" in self.variables: + kws.pop("c", None) + kws.pop("color", None) + + if "x" in self.variables: + self._plot_single_rug(sub_data, "x", height, ax, kws) + if "y" in self.variables: + self._plot_single_rug(sub_data, "y", height, ax, kws) + + # --- Finalize the plot + self._add_axis_labels(ax) + if "hue" in self.variables and legend: + # TODO ideally i'd like the legend artist to look like a rug + legend_artist = partial(mpl.lines.Line2D, [], []) + self._add_legend( + ax, legend_artist, False, False, None, 1, {}, {}, + ) + + def _plot_single_rug(self, sub_data, var, height, ax, kws): + """Draw a rugplot along one axis of the plot.""" + vector = sub_data[var] + n = len(vector) + + # Return data to linear domain + # This needs an automatic solution; see GH2409 + if self._log_scaled(var): + vector = np.power(10, vector) + + # We'll always add a single collection with varying colors + if "hue" in self.variables: + colors = self._hue_map(sub_data["hue"]) + else: + colors = None + + # Build the array of values for the LineCollection + if var == "x": + + trans = tx.blended_transform_factory(ax.transData, ax.transAxes) + xy_pairs = np.column_stack([ + np.repeat(vector, 2), np.tile([0, height], n) + ]) + + if var == "y": + + trans = tx.blended_transform_factory(ax.transAxes, ax.transData) + xy_pairs = np.column_stack([ + np.tile([0, height], n), np.repeat(vector, 2) + ]) + + # Draw the lines on the plot + line_segs = xy_pairs.reshape([n, 2, 2]) + ax.add_collection(LineCollection( + line_segs, transform=trans, colors=colors, **kws + )) + + ax.autoscale_view(scalex=var == "x", scaley=var == "y") + + +class _DistributionFacetPlotter(_DistributionPlotter): + + semantics = _DistributionPlotter.semantics + ("col", "row") + + +# ==================================================================================== # +# External API +# ==================================================================================== # + +def histplot( + data=None, *, + # Vector variables + x=None, y=None, hue=None, weights=None, + # Histogram computation parameters + stat="count", bins="auto", binwidth=None, binrange=None, + discrete=None, cumulative=False, common_bins=True, common_norm=True, + # Histogram appearance parameters + multiple="layer", element="bars", fill=True, shrink=1, + # Histogram smoothing with a kernel density estimate + kde=False, kde_kws=None, line_kws=None, + # Bivariate histogram parameters + thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None, + # Hue mapping parameters + palette=None, hue_order=None, hue_norm=None, color=None, + # Axes information + log_scale=None, legend=True, ax=None, + # Other appearance keywords + **kwargs, +): + + p = _DistributionPlotter( + data=data, + variables=_DistributionPlotter.get_semantics(locals()) + ) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + if ax is None: + ax = plt.gca() + + p._attach(ax, log_scale=log_scale) + + if p.univariate: # Note, bivariate plots won't cycle + if fill: + method = ax.bar if element == "bars" else ax.fill_between + else: + method = ax.plot + color = _default_color(method, hue, color, kwargs) + + if not p.has_xy_data: + return ax + + # Default to discrete bins for categorical variables + if discrete is None: + discrete = p._default_discrete() + + estimate_kws = dict( + stat=stat, + bins=bins, + binwidth=binwidth, + binrange=binrange, + discrete=discrete, + cumulative=cumulative, + ) + + if p.univariate: + + p.plot_univariate_histogram( + multiple=multiple, + element=element, + fill=fill, + shrink=shrink, + common_norm=common_norm, + common_bins=common_bins, + kde=kde, + kde_kws=kde_kws, + color=color, + legend=legend, + estimate_kws=estimate_kws, + line_kws=line_kws, + **kwargs, + ) + + else: + + p.plot_bivariate_histogram( + common_bins=common_bins, + common_norm=common_norm, + thresh=thresh, + pthresh=pthresh, + pmax=pmax, + color=color, + legend=legend, + cbar=cbar, + cbar_ax=cbar_ax, + cbar_kws=cbar_kws, + estimate_kws=estimate_kws, + **kwargs, + ) + + return ax + + +histplot.__doc__ = """\ +Plot univariate or bivariate histograms to show distributions of datasets. + +A histogram is a classic visualization tool that represents the distribution +of one or more variables by counting the number of observations that fall within +discrete bins. + +This function can normalize the statistic computed within each bin to estimate +frequency, density or probability mass, and it can add a smooth curve obtained +using a kernel density estimate, similar to :func:`kdeplot`. + +More information is provided in the :ref:`user guide `. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} +weights : vector or key in ``data`` + If provided, weight the contribution of the corresponding data points + towards the count in each bin by these factors. +{params.hist.stat} +{params.hist.bins} +{params.hist.binwidth} +{params.hist.binrange} +discrete : bool + If True, default to ``binwidth=1`` and draw the bars so that they are + centered on their corresponding data points. This avoids "gaps" that may + otherwise appear when using discrete (integer) data. +cumulative : bool + If True, plot the cumulative counts as bins increase. +common_bins : bool + If True, use the same bins when semantic variables produce multiple + plots. If using a reference rule to determine the bins, it will be computed + with the full dataset. +common_norm : bool + If True and using a normalized statistic, the normalization will apply over + the full dataset. Otherwise, normalize each histogram independently. +multiple : {{"layer", "dodge", "stack", "fill"}} + Approach to resolving multiple elements when semantic mapping creates subsets. + Only relevant with univariate data. +element : {{"bars", "step", "poly"}} + Visual representation of the histogram statistic. + Only relevant with univariate data. +fill : bool + If True, fill in the space under the histogram. + Only relevant with univariate data. +shrink : number + Scale the width of each bar relative to the binwidth by this factor. + Only relevant with univariate data. +kde : bool + If True, compute a kernel density estimate to smooth the distribution + and show on the plot as (one or more) line(s). + Only relevant with univariate data. +kde_kws : dict + Parameters that control the KDE computation, as in :func:`kdeplot`. +line_kws : dict + Parameters that control the KDE visualization, passed to + :meth:`matplotlib.axes.Axes.plot`. +thresh : number or None + Cells with a statistic less than or equal to this value will be transparent. + Only relevant with bivariate data. +pthresh : number or None + Like ``thresh``, but a value in [0, 1] such that cells with aggregate counts + (or other statistics, when used) up to this proportion of the total will be + transparent. +pmax : number or None + A value in [0, 1] that sets that saturation point for the colormap at a value + such that cells below constitute this proportion of the total count (or + other statistic, when used). +{params.dist.cbar} +{params.dist.cbar_ax} +{params.dist.cbar_kws} +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +{params.core.color} +{params.dist.log_scale} +{params.dist.legend} +{params.core.ax} +kwargs + Other keyword arguments are passed to one of the following matplotlib + functions: + + - :meth:`matplotlib.axes.Axes.bar` (univariate, element="bars") + - :meth:`matplotlib.axes.Axes.fill_between` (univariate, other element, fill=True) + - :meth:`matplotlib.axes.Axes.plot` (univariate, other element, fill=False) + - :meth:`matplotlib.axes.Axes.pcolormesh` (bivariate) + +Returns +------- +{returns.ax} + +See Also +-------- +{seealso.displot} +{seealso.kdeplot} +{seealso.rugplot} +{seealso.ecdfplot} +{seealso.jointplot} + +Notes +----- + +The choice of bins for computing and plotting a histogram can exert +substantial influence on the insights that one is able to draw from the +visualization. If the bins are too large, they may erase important features. +On the other hand, bins that are too small may be dominated by random +variability, obscuring the shape of the true underlying distribution. The +default bin size is determined using a reference rule that depends on the +sample size and variance. This works well in many cases, (i.e., with +"well-behaved" data) but it fails in others. It is always a good to try +different bin sizes to be sure that you are not missing something important. +This function allows you to specify bins in several different ways, such as +by setting the total number of bins to use, the width of each bin, or the +specific locations where the bins should break. + +Examples +-------- + +.. include:: ../docstrings/histplot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +def kdeplot( + data=None, *, x=None, y=None, hue=None, weights=None, + palette=None, hue_order=None, hue_norm=None, color=None, fill=None, + multiple="layer", common_norm=True, common_grid=False, cumulative=False, + bw_method="scott", bw_adjust=1, warn_singular=True, log_scale=None, + levels=10, thresh=.05, gridsize=200, cut=3, clip=None, + legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None, + **kwargs, +): + + # --- Start with backwards compatability for versions < 0.11.0 ---------------- + + # Handle (past) deprecation of `data2` + if "data2" in kwargs: + msg = "`data2` has been removed (replaced by `y`); please update your code." + TypeError(msg) + + # Handle deprecation of `vertical` + vertical = kwargs.pop("vertical", None) + if vertical is not None: + if vertical: + action_taken = "assigning data to `y`." + if x is None: + data, y = y, data + else: + x, y = y, x + else: + action_taken = "assigning data to `x`." + msg = textwrap.dedent(f"""\n + The `vertical` parameter is deprecated; {action_taken} + This will become an error in seaborn v0.13.0; please update your code. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + # Handle deprecation of `bw` + bw = kwargs.pop("bw", None) + if bw is not None: + msg = textwrap.dedent(f"""\n + The `bw` parameter is deprecated in favor of `bw_method` and `bw_adjust`. + Setting `bw_method={bw}`, but please see the docs for the new parameters + and update your code. This will become an error in seaborn v0.13.0. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + bw_method = bw + + # Handle deprecation of `kernel` + if kwargs.pop("kernel", None) is not None: + msg = textwrap.dedent("""\n + Support for alternate kernels has been removed; using Gaussian kernel. + This will become an error in seaborn v0.13.0; please update your code. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + # Handle deprecation of shade_lowest + shade_lowest = kwargs.pop("shade_lowest", None) + if shade_lowest is not None: + if shade_lowest: + thresh = 0 + msg = textwrap.dedent(f"""\n + `shade_lowest` has been replaced by `thresh`; setting `thresh={thresh}. + This will become an error in seaborn v0.13.0; please update your code. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + # Handle "soft" deprecation of shade `shade` is not really the right + # terminology here, but unlike some of the other deprecated parameters it + # is probably very commonly used and much hard to remove. This is therefore + # going to be a longer process where, first, `fill` will be introduced and + # be used throughout the documentation. In 0.12, when kwarg-only + # enforcement hits, we can remove the shade/shade_lowest out of the + # function signature all together and pull them out of the kwargs. Then we + # can actually fire a FutureWarning, and eventually remove. + shade = kwargs.pop("shade", None) + if shade is not None: + fill = shade + msg = textwrap.dedent(f"""\n + `shade` is now deprecated in favor of `fill`; setting `fill={shade}`. + This will become an error in seaborn v0.14.0; please update your code. + """) + warnings.warn(msg, FutureWarning, stacklevel=2) + + # Handle `n_levels` + # This was never in the formal API but it was processed, and appeared in an + # example. We can treat as an alias for `levels` now and deprecate later. + levels = kwargs.pop("n_levels", levels) + + # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # + + p = _DistributionPlotter( + data=data, + variables=_DistributionPlotter.get_semantics(locals()), + ) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + if ax is None: + ax = plt.gca() + + p._attach(ax, allowed_types=["numeric", "datetime"], log_scale=log_scale) + + method = ax.fill_between if fill else ax.plot + color = _default_color(method, hue, color, kwargs) + + if not p.has_xy_data: + return ax + + # Pack the kwargs for statistics.KDE + estimate_kws = dict( + bw_method=bw_method, + bw_adjust=bw_adjust, + gridsize=gridsize, + cut=cut, + clip=clip, + cumulative=cumulative, + ) + + if p.univariate: + + plot_kws = kwargs.copy() + + p.plot_univariate_density( + multiple=multiple, + common_norm=common_norm, + common_grid=common_grid, + fill=fill, + color=color, + legend=legend, + warn_singular=warn_singular, + estimate_kws=estimate_kws, + **plot_kws, + ) + + else: + + p.plot_bivariate_density( + common_norm=common_norm, + fill=fill, + levels=levels, + thresh=thresh, + legend=legend, + color=color, + warn_singular=warn_singular, + cbar=cbar, + cbar_ax=cbar_ax, + cbar_kws=cbar_kws, + estimate_kws=estimate_kws, + **kwargs, + ) + + return ax + + +kdeplot.__doc__ = """\ +Plot univariate or bivariate distributions using kernel density estimation. + +A kernel density estimate (KDE) plot is a method for visualizing the +distribution of observations in a dataset, analogous to a histogram. KDE +represents the data using a continuous probability density curve in one or +more dimensions. + +The approach is explained further in the :ref:`user guide `. + +Relative to a histogram, KDE can produce a plot that is less cluttered and +more interpretable, especially when drawing multiple distributions. But it +has the potential to introduce distortions if the underlying distribution is +bounded or not smooth. Like a histogram, the quality of the representation +also depends on the selection of good smoothing parameters. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} +weights : vector or key in ``data`` + If provided, weight the kernel density estimation using these values. +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +{params.core.color} +fill : bool or None + If True, fill in the area under univariate density curves or between + bivariate contours. If None, the default depends on ``multiple``. +{params.dist.multiple} +common_norm : bool + If True, scale each conditional density by the number of observations + such that the total area under all densities sums to 1. Otherwise, + normalize each density independently. +common_grid : bool + If True, use the same evaluation grid for each kernel density estimate. + Only relevant with univariate data. +{params.kde.cumulative} +{params.kde.bw_method} +{params.kde.bw_adjust} +warn_singular : bool + If True, issue a warning when trying to estimate the density of data + with zero variance. +{params.dist.log_scale} +levels : int or vector + Number of contour levels or values to draw contours at. A vector argument + must have increasing values in [0, 1]. Levels correspond to iso-proportions + of the density: e.g., 20% of the probability mass will lie below the + contour drawn for 0.2. Only relevant with bivariate data. +thresh : number in [0, 1] + Lowest iso-proportion level at which to draw a contour line. Ignored when + ``levels`` is a vector. Only relevant with bivariate data. +gridsize : int + Number of points on each dimension of the evaluation grid. +{params.kde.cut} +{params.kde.clip} +{params.dist.legend} +{params.dist.cbar} +{params.dist.cbar_ax} +{params.dist.cbar_kws} +{params.core.ax} +kwargs + Other keyword arguments are passed to one of the following matplotlib + functions: + + - :meth:`matplotlib.axes.Axes.plot` (univariate, ``fill=False``), + - :meth:`matplotlib.axes.Axes.fill_between` (univariate, ``fill=True``), + - :meth:`matplotlib.axes.Axes.contour` (bivariate, ``fill=False``), + - :meth:`matplotlib.axes.contourf` (bivariate, ``fill=True``). + +Returns +------- +{returns.ax} + +See Also +-------- +{seealso.displot} +{seealso.histplot} +{seealso.ecdfplot} +{seealso.jointplot} +{seealso.violinplot} + +Notes +----- + +The *bandwidth*, or standard deviation of the smoothing kernel, is an +important parameter. Misspecification of the bandwidth can produce a +distorted representation of the data. Much like the choice of bin width in a +histogram, an over-smoothed curve can erase true features of a +distribution, while an under-smoothed curve can create false features out of +random variability. The rule-of-thumb that sets the default bandwidth works +best when the true distribution is smooth, unimodal, and roughly bell-shaped. +It is always a good idea to check the default behavior by using ``bw_adjust`` +to increase or decrease the amount of smoothing. + +Because the smoothing algorithm uses a Gaussian kernel, the estimated density +curve can extend to values that do not make sense for a particular dataset. +For example, the curve may be drawn over negative values when smoothing data +that are naturally positive. The ``cut`` and ``clip`` parameters can be used +to control the extent of the curve, but datasets that have many observations +close to a natural boundary may be better served by a different visualization +method. + +Similar considerations apply when a dataset is naturally discrete or "spiky" +(containing many repeated observations of the same value). Kernel density +estimation will always produce a smooth curve, which would be misleading +in these situations. + +The units on the density axis are a common source of confusion. While kernel +density estimation produces a probability distribution, the height of the curve +at each point gives a density, not a probability. A probability can be obtained +only by integrating the density across a range. The curve is normalized so +that the integral over all possible values is 1, meaning that the scale of +the density axis depends on the data values. + +Examples +-------- + +.. include:: ../docstrings/kdeplot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +def ecdfplot( + data=None, *, + # Vector variables + x=None, y=None, hue=None, weights=None, + # Computation parameters + stat="proportion", complementary=False, + # Hue mapping parameters + palette=None, hue_order=None, hue_norm=None, + # Axes information + log_scale=None, legend=True, ax=None, + # Other appearance keywords + **kwargs, +): + + p = _DistributionPlotter( + data=data, + variables=_DistributionPlotter.get_semantics(locals()) + ) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + # We could support other semantics (size, style) here fairly easily + # But it would make distplot a bit more complicated. + # It's always possible to add features like that later, so I am going to defer. + # It will be even easier to wait until after there is a more general/abstract + # way to go from semantic specs to artist attributes. + + if ax is None: + ax = plt.gca() + + p._attach(ax, log_scale=log_scale) + + color = kwargs.pop("color", kwargs.pop("c", None)) + kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) + + if not p.has_xy_data: + return ax + + # We could add this one day, but it's of dubious value + if not p.univariate: + raise NotImplementedError("Bivariate ECDF plots are not implemented") + + estimate_kws = dict( + stat=stat, + complementary=complementary, + ) + + p.plot_univariate_ecdf( + estimate_kws=estimate_kws, + legend=legend, + **kwargs, + ) + + return ax + + +ecdfplot.__doc__ = """\ +Plot empirical cumulative distribution functions. + +An ECDF represents the proportion or count of observations falling below each +unique value in a dataset. Compared to a histogram or density plot, it has the +advantage that each observation is visualized directly, meaning that there are +no binning or smoothing parameters that need to be adjusted. It also aids direct +comparisons between multiple distributions. A downside is that the relationship +between the appearance of the plot and the basic properties of the distribution +(such as its central tendency, variance, and the presence of any bimodality) +may not be as intuitive. + +More information is provided in the :ref:`user guide `. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} +weights : vector or key in ``data`` + If provided, weight the contribution of the corresponding data points + towards the cumulative distribution using these values. +{params.ecdf.stat} +{params.ecdf.complementary} +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +{params.dist.log_scale} +{params.dist.legend} +{params.core.ax} +kwargs + Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.plot`. + +Returns +------- +{returns.ax} + +See Also +-------- +{seealso.displot} +{seealso.histplot} +{seealso.kdeplot} +{seealso.rugplot} + +Examples +-------- + +.. include:: ../docstrings/ecdfplot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +def rugplot( + data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True, + palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs +): + + # A note: I think it would make sense to add multiple= to rugplot and allow + # rugs for different hue variables to be shifted orthogonal to the data axis + # But is this stacking, or dodging? + + # A note: if we want to add a style semantic to rugplot, + # we could make an option that draws the rug using scatterplot + + # A note, it would also be nice to offer some kind of histogram/density + # rugplot, since alpha blending doesn't work great in the large n regime + + # --- Start with backwards compatability for versions < 0.11.0 ---------------- + + a = kwargs.pop("a", None) + axis = kwargs.pop("axis", None) + + if a is not None: + data = a + msg = textwrap.dedent("""\n + The `a` parameter has been replaced; use `x`, `y`, and/or `data` instead. + Please update your code; This will become an error in seaborn v0.13.0. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + if axis is not None: + if axis == "x": + x = data + elif axis == "y": + y = data + msg = textwrap.dedent(f"""\n + The `axis` parameter has been deprecated; use the `{axis}` parameter instead. + Please update your code; this will become an error in seaborn v0.13.0. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + vertical = kwargs.pop("vertical", None) + if vertical is not None: + if vertical: + action_taken = "assigning data to `y`." + if x is None: + data, y = y, data + else: + x, y = y, x + else: + action_taken = "assigning data to `x`." + msg = textwrap.dedent(f"""\n + The `vertical` parameter is deprecated; {action_taken} + This will become an error in seaborn v0.13.0; please update your code. + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # + + weights = None + p = _DistributionPlotter( + data=data, + variables=_DistributionPlotter.get_semantics(locals()), + ) + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + if ax is None: + ax = plt.gca() + + p._attach(ax) + + color = kwargs.pop("color", kwargs.pop("c", None)) + kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) + + if not p.has_xy_data: + return ax + + p.plot_rug(height, expand_margins, legend, **kwargs) + + return ax + + +rugplot.__doc__ = """\ +Plot marginal distributions by drawing ticks along the x and y axes. + +This function is intended to complement other plots by showing the location +of individual observations in an unobtrusive way. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} +height : float + Proportion of axes extent covered by each rug element. Can be negative. +expand_margins : bool + If True, increase the axes margins by the height of the rug to avoid + overlap with other elements. +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +legend : bool + If False, do not add a legend for semantic variables. +{params.core.ax} +kwargs + Other keyword arguments are passed to + :meth:`matplotlib.collections.LineCollection` + +Returns +------- +{returns.ax} + +Examples +-------- + +.. include:: ../docstrings/rugplot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +def displot( + data=None, *, + # Vector variables + x=None, y=None, hue=None, row=None, col=None, weights=None, + # Other plot parameters + kind="hist", rug=False, rug_kws=None, log_scale=None, legend=True, + # Hue-mapping parameters + palette=None, hue_order=None, hue_norm=None, color=None, + # Faceting parameters + col_wrap=None, row_order=None, col_order=None, + height=5, aspect=1, facet_kws=None, + **kwargs, +): + + p = _DistributionFacetPlotter( + data=data, + variables=_DistributionFacetPlotter.get_semantics(locals()) + ) + + p.map_hue(palette=palette, order=hue_order, norm=hue_norm) + + _check_argument("kind", ["hist", "kde", "ecdf"], kind) + + # --- Initialize the FacetGrid object + + # Check for attempt to plot onto specific axes and warn + if "ax" in kwargs: + msg = ( + "`displot` is a figure-level function and does not accept " + "the ax= parameter. You may wish to try {}plot.".format(kind) + ) + warnings.warn(msg, UserWarning) + kwargs.pop("ax") + + for var in ["row", "col"]: + # Handle faceting variables that lack name information + if var in p.variables and p.variables[var] is None: + p.variables[var] = f"_{var}_" + + # Adapt the plot_data dataframe for use with FacetGrid + grid_data = p.plot_data.rename(columns=p.variables) + grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()] + + col_name = p.variables.get("col") + row_name = p.variables.get("row") + + if facet_kws is None: + facet_kws = {} + + g = FacetGrid( + data=grid_data, row=row_name, col=col_name, + col_wrap=col_wrap, row_order=row_order, + col_order=col_order, height=height, + aspect=aspect, + **facet_kws, + ) + + # Now attach the axes object to the plotter object + if kind == "kde": + allowed_types = ["numeric", "datetime"] + else: + allowed_types = None + p._attach(g, allowed_types=allowed_types, log_scale=log_scale) + + # Check for a specification that lacks x/y data and return early + if not p.has_xy_data: + return g + + if color is None and hue is None: + color = "C0" + # XXX else warn if hue is not None? + + kwargs["legend"] = legend + + # --- Draw the plots + + if kind == "hist": + + hist_kws = kwargs.copy() + + # Extract the parameters that will go directly to Histogram + estimate_defaults = {} + _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot) + + estimate_kws = {} + for key, default_val in estimate_defaults.items(): + estimate_kws[key] = hist_kws.pop(key, default_val) + + # Handle derivative defaults + if estimate_kws["discrete"] is None: + estimate_kws["discrete"] = p._default_discrete() + + hist_kws["estimate_kws"] = estimate_kws + + hist_kws.setdefault("color", color) + + if p.univariate: + + _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot) + p.plot_univariate_histogram(**hist_kws) + + else: + + _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot) + p.plot_bivariate_histogram(**hist_kws) + + elif kind == "kde": + + kde_kws = kwargs.copy() + + # Extract the parameters that will go directly to KDE + estimate_defaults = {} + _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot) + + estimate_kws = {} + for key, default_val in estimate_defaults.items(): + estimate_kws[key] = kde_kws.pop(key, default_val) + + kde_kws["estimate_kws"] = estimate_kws + kde_kws["color"] = color + + if p.univariate: + + _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot) + p.plot_univariate_density(**kde_kws) + + else: + + _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot) + p.plot_bivariate_density(**kde_kws) + + elif kind == "ecdf": + + ecdf_kws = kwargs.copy() + + # Extract the parameters that will go directly to the estimator + estimate_kws = {} + estimate_defaults = {} + _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot) + for key, default_val in estimate_defaults.items(): + estimate_kws[key] = ecdf_kws.pop(key, default_val) + + ecdf_kws["estimate_kws"] = estimate_kws + ecdf_kws["color"] = color + + if p.univariate: + + _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot) + p.plot_univariate_ecdf(**ecdf_kws) + + else: + + raise NotImplementedError("Bivariate ECDF plots are not implemented") + + # All plot kinds can include a rug + if rug: + # TODO with expand_margins=True, each facet expands margins... annoying! + if rug_kws is None: + rug_kws = {} + _assign_default_kwargs(rug_kws, p.plot_rug, rugplot) + rug_kws["legend"] = False + if color is not None: + rug_kws["color"] = color + p.plot_rug(**rug_kws) + + # Call FacetGrid annotation methods + # Note that the legend is currently set inside the plotting method + g.set_axis_labels( + x_var=p.variables.get("x", g.axes.flat[0].get_xlabel()), + y_var=p.variables.get("y", g.axes.flat[0].get_ylabel()), + ) + g.set_titles() + g.tight_layout() + + if data is not None and (x is not None or y is not None): + if not isinstance(data, pd.DataFrame): + data = pd.DataFrame(data) + g.data = pd.merge( + data, + g.data[g.data.columns.difference(data.columns)], + left_index=True, + right_index=True, + ) + else: + wide_cols = { + k: f"_{k}_" if v is None else v for k, v in p.variables.items() + } + g.data = p.plot_data.rename(columns=wide_cols) + + return g + + +displot.__doc__ = """\ +Figure-level interface for drawing distribution plots onto a FacetGrid. + +This function provides access to several approaches for visualizing the +univariate or bivariate distribution of data, including subsets of data +defined by semantic mapping and faceting across multiple subplots. The +``kind`` parameter selects the approach to use: + +- :func:`histplot` (with ``kind="hist"``; the default) +- :func:`kdeplot` (with ``kind="kde"``) +- :func:`ecdfplot` (with ``kind="ecdf"``; univariate-only) + +Additionally, a :func:`rugplot` can be added to any kind of plot to show +individual observations. + +Extra keyword arguments are passed to the underlying function, so you should +refer to the documentation for each to understand the complete set of options +for making plots with this interface. + +See the :doc:`distribution plots tutorial <../tutorial/distributions>` for a more +in-depth discussion of the relative strengths and weaknesses of each approach. +The distinction between figure-level and axes-level functions is explained +further in the :doc:`user guide <../tutorial/function_overview>`. + +Parameters +---------- +{params.core.data} +{params.core.xy} +{params.core.hue} +{params.facets.rowcol} +kind : {{"hist", "kde", "ecdf"}} + Approach for visualizing the data. Selects the underlying plotting function + and determines the additional set of valid parameters. +rug : bool + If True, show each observation with marginal ticks (as in :func:`rugplot`). +rug_kws : dict + Parameters to control the appearance of the rug plot. +{params.dist.log_scale} +{params.dist.legend} +{params.core.palette} +{params.core.hue_order} +{params.core.hue_norm} +{params.core.color} +{params.facets.col_wrap} +{params.facets.rowcol_order} +{params.facets.height} +{params.facets.aspect} +{params.facets.facet_kws} +kwargs + Other keyword arguments are documented with the relevant axes-level function: + + - :func:`histplot` (with ``kind="hist"``) + - :func:`kdeplot` (with ``kind="kde"``) + - :func:`ecdfplot` (with ``kind="ecdf"``) + +Returns +------- +{returns.facetgrid} + +See Also +-------- +{seealso.histplot} +{seealso.kdeplot} +{seealso.rugplot} +{seealso.ecdfplot} +{seealso.jointplot} + +Examples +-------- + +See the API documentation for the axes-level functions for more details +about the breadth of options available for each plot kind. + +.. include:: ../docstrings/displot.rst + +""".format( + params=_param_docs, + returns=_core_docs["returns"], + seealso=_core_docs["seealso"], +) + + +# =========================================================================== # +# DEPRECATED FUNCTIONS LIVE BELOW HERE +# =========================================================================== # + + +def _freedman_diaconis_bins(a): + """Calculate number of hist bins using Freedman-Diaconis rule.""" + # From https://stats.stackexchange.com/questions/798/ + a = np.asarray(a) + if len(a) < 2: + return 1 + iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25])) + h = 2 * iqr / (len(a) ** (1 / 3)) + # fall back to sqrt(a) bins if iqr is 0 + if h == 0: + return int(np.sqrt(a.size)) + else: + return int(np.ceil((a.max() - a.min()) / h)) + + +def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, + hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, + color=None, vertical=False, norm_hist=False, axlabel=None, + label=None, ax=None, x=None): + """ + DEPRECATED + + This function has been deprecated and will be removed in seaborn v0.14.0. + It has been replaced by :func:`histplot` and :func:`displot`, two functions + with a modern API and many more capabilities. + + For a guide to updating, please see this notebook: + + https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 + + """ + + if kde and not hist: + axes_level_suggestion = ( + "`kdeplot` (an axes-level function for kernel density plots)" + ) + else: + axes_level_suggestion = ( + "`histplot` (an axes-level function for histograms)" + ) + + msg = textwrap.dedent(f""" + + `distplot` is a deprecated function and will be removed in seaborn v0.14.0. + + Please adapt your code to use either `displot` (a figure-level function with + similar flexibility) or {axes_level_suggestion}. + + For a guide to updating your code to use the new functions, please see + https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 + """) + warnings.warn(msg, UserWarning, stacklevel=2) + + if ax is None: + ax = plt.gca() + + # Intelligently label the support axis + label_ax = bool(axlabel) + if axlabel is None and hasattr(a, "name"): + axlabel = a.name + if axlabel is not None: + label_ax = True + + # Support new-style API + if x is not None: + a = x + + # Make a a 1-d float array + a = np.asarray(a, float) + if a.ndim > 1: + a = a.squeeze() + + # Drop null values from array + a = remove_na(a) + + # Decide if the hist is normed + norm_hist = norm_hist or kde or (fit is not None) + + # Handle dictionary defaults + hist_kws = {} if hist_kws is None else hist_kws.copy() + kde_kws = {} if kde_kws is None else kde_kws.copy() + rug_kws = {} if rug_kws is None else rug_kws.copy() + fit_kws = {} if fit_kws is None else fit_kws.copy() + + # Get the color from the current color cycle + if color is None: + if vertical: + line, = ax.plot(0, a.mean()) + else: + line, = ax.plot(a.mean(), 0) + color = line.get_color() + line.remove() + + # Plug the label into the right kwarg dictionary + if label is not None: + if hist: + hist_kws["label"] = label + elif kde: + kde_kws["label"] = label + elif rug: + rug_kws["label"] = label + elif fit: + fit_kws["label"] = label + + if hist: + if bins is None: + bins = min(_freedman_diaconis_bins(a), 50) + hist_kws.setdefault("alpha", 0.4) + hist_kws.setdefault("density", norm_hist) + + orientation = "horizontal" if vertical else "vertical" + hist_color = hist_kws.pop("color", color) + ax.hist(a, bins, orientation=orientation, + color=hist_color, **hist_kws) + if hist_color != color: + hist_kws["color"] = hist_color + + axis = "y" if vertical else "x" + + if kde: + kde_color = kde_kws.pop("color", color) + kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws) + if kde_color != color: + kde_kws["color"] = kde_color + + if rug: + rug_color = rug_kws.pop("color", color) + rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws) + if rug_color != color: + rug_kws["color"] = rug_color + + if fit is not None: + + def pdf(x): + return fit.pdf(x, *params) + + fit_color = fit_kws.pop("color", "#282828") + gridsize = fit_kws.pop("gridsize", 200) + cut = fit_kws.pop("cut", 3) + clip = fit_kws.pop("clip", (-np.inf, np.inf)) + bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1) + x = _kde_support(a, bw, gridsize, cut, clip) + params = fit.fit(a) + y = pdf(x) + if vertical: + x, y = y, x + ax.plot(x, y, color=fit_color, **fit_kws) + if fit_color != "#282828": + fit_kws["color"] = fit_color + + if label_ax: + if vertical: + ax.set_ylabel(axlabel) + else: + ax.set_xlabel(axlabel) + + return ax diff --git a/testbed/mwaskom__seaborn/seaborn/external/__init__.py b/testbed/mwaskom__seaborn/seaborn/external/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/mwaskom__seaborn/seaborn/external/appdirs.py b/testbed/mwaskom__seaborn/seaborn/external/appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..70c382964824fe0fce175f44cf6061b44cd4f922 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/external/appdirs.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +# Copyright (c) 2005-2010 ActiveState Software Inc. +# Copyright (c) 2013 Eddy Petrișor + +# flake8: noqa + +""" +This file is directly from +https://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py + +The license of https://github.com/ActiveState/appdirs copied below: + + +# This is the MIT license + +Copyright (c) 2010 ActiveState Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" + +"""Utilities for determining application-specific dirs. + +See for details and usage. +""" +# Dev Notes: +# - MSDN on where to store app data files: +# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 +# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html +# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + +__version__ = "1.4.4" +__version_info__ = tuple(int(segment) for segment in __version__.split(".")) + + +import sys +import os + +unicode = str + +if sys.platform.startswith('java'): + import platform + os_name = platform.java_ver()[3][0] + if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. + system = 'win32' + elif os_name.startswith('Mac'): # "Mac OS X", etc. + system = 'darwin' + else: # "Linux", "SunOS", "FreeBSD", etc. + # Setting this to "linux2" is not ideal, but only Windows or Mac + # are actually checked for and the rest of the module expects + # *sys.platform* style strings. + system = 'linux2' +else: + system = sys.platform + + +def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific cache dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Cache" to the base app data dir for Windows. See + discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Caches/ + Unix: ~/.cache/ (XDG default) + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache + Vista: C:\Users\\AppData\Local\\\Cache + + On Windows the only suggestion in the MSDN docs is that local settings go in + the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming + app data dir (the default returned by `user_data_dir` above). Apps typically + put cache data somewhere *under* the given dir here. Some examples: + ...\Mozilla\Firefox\Profiles\\Cache + ...\Acme\SuperApp\Cache\1.0 + OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. + This can be disabled with the `opinion=False` option. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + if opinion: + path = os.path.join(path, "Cache") + elif system == 'darwin': + path = os.path.expanduser('~/Library/Caches') + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +#---- internal support stuff + +def _get_win_folder_from_registry(csidl_name): + """This is a fallback technique at best. I'm not sure if using the + registry for this guarantees us the correct answer for all CSIDL_* + names. + """ + import winreg as _winreg + + shell_folder_name = { + "CSIDL_APPDATA": "AppData", + "CSIDL_COMMON_APPDATA": "Common AppData", + "CSIDL_LOCAL_APPDATA": "Local AppData", + }[csidl_name] + + key = _winreg.OpenKey( + _winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" + ) + dir, type = _winreg.QueryValueEx(key, shell_folder_name) + return dir + + +def _get_win_folder_with_pywin32(csidl_name): + from win32com.shell import shellcon, shell + dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) + # Try to make this a unicode path because SHGetFolderPath does + # not return unicode strings when there is unicode data in the + # path. + try: + dir = unicode(dir) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + try: + import win32api + dir = win32api.GetShortPathName(dir) + except ImportError: + pass + except UnicodeError: + pass + return dir + + +def _get_win_folder_with_ctypes(csidl_name): + import ctypes + + csidl_const = { + "CSIDL_APPDATA": 26, + "CSIDL_COMMON_APPDATA": 35, + "CSIDL_LOCAL_APPDATA": 28, + }[csidl_name] + + buf = ctypes.create_unicode_buffer(1024) + ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in buf: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf2 = ctypes.create_unicode_buffer(1024) + if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): + buf = buf2 + + return buf.value + +def _get_win_folder_with_jna(csidl_name): + import array + from com.sun import jna + from com.sun.jna.platform import win32 + + buf_size = win32.WinDef.MAX_PATH * 2 + buf = array.zeros('c', buf_size) + shell = win32.Shell32.INSTANCE + shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf = array.zeros('c', buf_size) + kernel = win32.Kernel32.INSTANCE + if kernel.GetShortPathName(dir, buf, buf_size): + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + return dir + +if system == "win32": + try: + import win32com.shell + _get_win_folder = _get_win_folder_with_pywin32 + except ImportError: + try: + from ctypes import windll + _get_win_folder = _get_win_folder_with_ctypes + except ImportError: + try: + import com.sun.jna + _get_win_folder = _get_win_folder_with_jna + except ImportError: + _get_win_folder = _get_win_folder_from_registry diff --git a/testbed/mwaskom__seaborn/seaborn/external/docscrape.py b/testbed/mwaskom__seaborn/seaborn/external/docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..99dc3ff797f5faf21ec4f53bf0c6cd036e38c9c9 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/external/docscrape.py @@ -0,0 +1,715 @@ +"""Extract reference documentation from the NumPy source tree. + +Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +""" +import inspect +import textwrap +import re +import pydoc +from warnings import warn +from collections import namedtuple +from collections.abc import Callable, Mapping +import copy +import sys + + +def strip_blank_lines(l): + "Remove leading and trailing blank lines from a list of lines" + while l and not l[0].strip(): + del l[0] + while l and not l[-1].strip(): + del l[-1] + return l + + +class Reader: + """A line-based string reader. + + """ + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\n'. + + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split('\n') # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._l = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._l] + self._l += 1 + return out + else: + return '' + + def seek_next_non_empty_line(self): + for l in self[self._l:]: + if l.strip(): + break + else: + self._l += 1 + + def eof(self): + return self._l >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._l + for line in self[start:]: + if condition_func(line): + return self[start:self._l] + self._l += 1 + if self.eof(): + return self[start:self._l+1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return (line.strip() and (len(line.lstrip()) == len(line))) + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._l + n < len(self._str): + return self[self._l + n] + else: + return '' + + def is_empty(self): + return not ''.join(self._str).strip() + + +class ParseError(Exception): + def __str__(self): + message = self.args[0] + if hasattr(self, 'docstring'): + message = f"{message} in {self.docstring!r}" + return message + + +Parameter = namedtuple('Parameter', ['name', 'type', 'desc']) + + +class NumpyDocString(Mapping): + """Parses a numpydoc string to an abstract representation + + Instances define a mapping from section title to structured data. + + """ + + sections = { + 'Signature': '', + 'Summary': [''], + 'Extended Summary': [], + 'Parameters': [], + 'Returns': [], + 'Yields': [], + 'Receives': [], + 'Raises': [], + 'Warns': [], + 'Other Parameters': [], + 'Attributes': [], + 'Methods': [], + 'See Also': [], + 'Notes': [], + 'Warnings': [], + 'References': '', + 'Examples': '', + 'index': {} + } + + def __init__(self, docstring, config={}): + orig_docstring = docstring + docstring = textwrap.dedent(docstring).split('\n') + + self._doc = Reader(docstring) + self._parsed_data = copy.deepcopy(self.sections) + + try: + self._parse() + except ParseError as e: + e.docstring = orig_docstring + raise + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + self._error_location(f"Unknown section {key}", error=False) + else: + self._parsed_data[key] = val + + def __iter__(self): + return iter(self._parsed_data) + + def __len__(self): + return len(self._parsed_data) + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith('.. index::'): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i:len(doc)-j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [''] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith('..'): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content, single_element_is_type=False): + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if ' : ' in header: + arg_name, arg_type = header.split(' : ')[:2] + else: + if single_element_is_type: + arg_name, arg_type = '', header + else: + arg_name, arg_type = header, '' + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + desc = strip_blank_lines(desc) + + params.append(Parameter(arg_name, arg_type, desc)) + + return params + + # See also supports the following formats. + # + # + # SPACE* COLON SPACE+ SPACE* + # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE* + # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE* + + # is one of + # + # COLON COLON BACKTICK BACKTICK + # where + # is a legal function name, and + # is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # is a string describing the function. + + _role = r":(?P\w+):" + _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" + _funcplain = r"(?P[a-zA-Z0-9_\.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace('role', 'rolenext') + _funcnamenext = _funcnamenext.replace('name', 'namenext') + _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P" + # group for all function names + _funcname + + r"(?P([,]\s+" + _funcnamenext + r")*)" + + r")" + # end of "allfuncs" + r"(?P[,\.])?" + # Some function lists have a trailing comma (or period) '\s*' + _description) + + # Empty elements are replaced with '..' + empty_description = '..' + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + + """ + + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + raise ParseError(f"{text} is not a item name") + role = m.group('role') + name = m.group('name') if role else m.group('name2') + return name, role, m.end() + + rest = [] + for line in content: + if not line.strip(): + continue + + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group('desc') + if line_match.group('trailing') and description: + self._error_location( + 'Unexpected comma or period after function list at index %d of ' + 'line "%s"' % (line_match.end('trailing'), line), + error=False) + if not description and line.startswith(' '): + rest.append(line.strip()) + elif line_match: + funcs = [] + text = line_match.group('allfuncs') + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ',': + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + raise ParseError(f"{line} is not a item name") + return items + + def _parse_index(self, section, content): + """ + .. index: default + :refguide: something, else, and more + + """ + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split('::') + if len(section) > 1: + out['default'] = strip_each_in(section[1].split(','))[0] + for line in content: + line = line.split(':') + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(',')) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + compiled = re.compile(r'^([\w., ]+=)?\s*[\w\.]+\(.*\)$') + if compiled.match(summary_str): + self['Signature'] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self['Summary'] = summary + + if not self._is_at_section(): + self['Extended Summary'] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + sections = list(self._read_sections()) + section_names = {section for section, content in sections} + + has_returns = 'Returns' in section_names + has_yields = 'Yields' in section_names + # We could do more tests, but we are not. Arbitrarily. + if has_returns and has_yields: + msg = 'Docstring contains both a Returns and Yields section.' + raise ValueError(msg) + if not has_yields and 'Receives' in section_names: + msg = 'Docstring contains a Receives section but not Yields.' + raise ValueError(msg) + + for (section, content) in sections: + if not section.startswith('..'): + section = (s.capitalize() for s in section.split(' ')) + section = ' '.join(section) + if self.get(section): + self._error_location(f"The section {section} appears twice") + + if section in ('Parameters', 'Other Parameters', 'Attributes', + 'Methods'): + self[section] = self._parse_param_list(content) + elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'): + self[section] = self._parse_param_list( + content, single_element_is_type=True) + elif section.startswith('.. index::'): + self['index'] = self._parse_index(section, content) + elif section == 'See Also': + self['See Also'] = self._parse_see_also(content) + else: + self[section] = content + + def _error_location(self, msg, error=True): + if hasattr(self, '_obj'): + # we know where the docs came from: + try: + filename = inspect.getsourcefile(self._obj) + except TypeError: + filename = None + msg = msg + f" in the docstring of {self._obj} in {filename}." + if error: + raise ValueError(msg) + else: + warn(msg) + + # string conversion routines + + def _str_header(self, name, symbol='-'): + return [name, len(name)*symbol] + + def _str_indent(self, doc, indent=4): + out = [] + for line in doc: + out += [' '*indent + line] + return out + + def _str_signature(self): + if self['Signature']: + return [self['Signature'].replace('*', r'\*')] + [''] + else: + return [''] + + def _str_summary(self): + if self['Summary']: + return self['Summary'] + [''] + else: + return [] + + def _str_extended_summary(self): + if self['Extended Summary']: + return self['Extended Summary'] + [''] + else: + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) + if param.type: + parts.append(param.type) + out += [' : '.join(parts)] + if param.desc and ''.join(param.desc).strip(): + out += self._str_indent(param.desc) + out += [''] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [''] + return out + + def _str_see_also(self, func_role): + if not self['See Also']: + return [] + out = [] + out += self._str_header("See Also") + out += [''] + last_had_desc = True + for funcs, desc in self['See Also']: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = f':{role}:`{func}`' + elif func_role: + link = f':{func_role}:`{func}`' + else: + link = f"`{func}`_" + links.append(link) + link = ', '.join(links) + out += [link] + if desc: + out += self._str_indent([' '.join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [''] + out += [''] + return out + + def _str_index(self): + idx = self['index'] + out = [] + output_index = False + default_index = idx.get('default', '') + if default_index: + output_index = True + out += [f'.. index:: {default_index}'] + for section, references in idx.items(): + if section == 'default': + continue + output_index = True + out += [f" :{section}: {', '.join(references)}"] + if output_index: + return out + else: + return '' + + def __str__(self, func_role=''): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + for param_list in ('Parameters', 'Returns', 'Yields', 'Receives', + 'Other Parameters', 'Raises', 'Warns'): + out += self._str_param_list(param_list) + out += self._str_section('Warnings') + out += self._str_see_also(func_role) + for s in ('Notes', 'References', 'Examples'): + out += self._str_section(s) + for param_list in ('Attributes', 'Methods'): + out += self._str_param_list(param_list) + out += self._str_index() + return '\n'.join(out) + + +def indent(str, indent=4): + indent_str = ' '*indent + if str is None: + return indent_str + lines = str.split('\n') + return '\n'.join(indent_str + l for l in lines) + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +def header(text, style='-'): + return text + '\n' + style*len(text) + '\n' + + +class FunctionDoc(NumpyDocString): + def __init__(self, func, role='func', doc=None, config={}): + self._f = func + self._role = role # e.g. "func" or "meth" + + if doc is None: + if func is None: + raise ValueError("No function or docstring given") + doc = inspect.getdoc(func) or '' + NumpyDocString.__init__(self, doc, config) + + if not self['Signature'] and func is not None: + func, func_name = self.get_func() + try: + try: + signature = str(inspect.signature(func)) + except (AttributeError, ValueError): + # try to read signature, backward compat for older Python + if sys.version_info[0] >= 3: + argspec = inspect.getfullargspec(func) + else: + argspec = inspect.getargspec(func) + signature = inspect.formatargspec(*argspec) + signature = f'{func_name}{signature}' + except TypeError: + signature = f'{func_name}()' + self['Signature'] = signature + + def get_func(self): + func_name = getattr(self._f, '__name__', self.__class__.__name__) + if inspect.isclass(self._f): + func = getattr(self._f, '__call__', self._f.__init__) + else: + func = self._f + return func, func_name + + def __str__(self): + out = '' + + func, func_name = self.get_func() + + roles = {'func': 'function', + 'meth': 'method'} + + if self._role: + if self._role not in roles: + print(f"Warning: invalid role {self._role}") + out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" + + out += super().__str__(func_role=self._role) + return out + + +class ClassDoc(NumpyDocString): + + extra_public_methods = ['__call__'] + + def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, + config={}): + if not inspect.isclass(cls) and cls is not None: + raise ValueError(f"Expected a class or None, but got {cls!r}") + self._cls = cls + + if 'sphinx' in sys.modules: + from sphinx.ext.autodoc import ALL + else: + ALL = object() + + self.show_inherited_members = config.get( + 'show_inherited_class_members', True) + + if modulename and not modulename.endswith('.'): + modulename += '.' + self._mod = modulename + + if doc is None: + if cls is None: + raise ValueError("No class or documentation string given") + doc = pydoc.getdoc(cls) + + NumpyDocString.__init__(self, doc) + + _members = config.get('members', []) + if _members is ALL: + _members = None + _exclude = config.get('exclude-members', []) + + if config.get('show_class_members', True) and _exclude is not ALL: + def splitlines_x(s): + if not s: + return [] + else: + return s.splitlines() + for field, items in [('Methods', self.methods), + ('Attributes', self.properties)]: + if not self[field]: + doc_list = [] + for name in sorted(items): + if (name in _exclude or + (_members and name not in _members)): + continue + try: + doc_item = pydoc.getdoc(getattr(self._cls, name)) + doc_list.append( + Parameter(name, '', splitlines_x(doc_item))) + except AttributeError: + pass # method doesn't exist + self[field] = doc_list + + @property + def methods(self): + if self._cls is None: + return [] + return [name for name, func in inspect.getmembers(self._cls) + if ((not name.startswith('_') + or name in self.extra_public_methods) + and isinstance(func, Callable) + and self._is_show_member(name))] + + @property + def properties(self): + if self._cls is None: + return [] + return [name for name, func in inspect.getmembers(self._cls) + if (not name.startswith('_') and + (func is None or isinstance(func, property) or + inspect.isdatadescriptor(func)) + and self._is_show_member(name))] + + def _is_show_member(self, name): + if self.show_inherited_members: + return True # show all class members + if name not in self._cls.__dict__: + return False # class member is inherited, we do not show it + return True diff --git a/testbed/mwaskom__seaborn/seaborn/external/husl.py b/testbed/mwaskom__seaborn/seaborn/external/husl.py new file mode 100644 index 0000000000000000000000000000000000000000..63e98cbb71640f24a0d5e0eda697bc97d12ffc5b --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/external/husl.py @@ -0,0 +1,313 @@ +import operator +import math + +__version__ = "2.1.0" + + +m = [ + [3.2406, -1.5372, -0.4986], + [-0.9689, 1.8758, 0.0415], + [0.0557, -0.2040, 1.0570] +] + +m_inv = [ + [0.4124, 0.3576, 0.1805], + [0.2126, 0.7152, 0.0722], + [0.0193, 0.1192, 0.9505] +] + +# Hard-coded D65 illuminant +refX = 0.95047 +refY = 1.00000 +refZ = 1.08883 +refU = 0.19784 +refV = 0.46834 +lab_e = 0.008856 +lab_k = 903.3 + + +# Public API + +def husl_to_rgb(h, s, l): + return lch_to_rgb(*husl_to_lch([h, s, l])) + + +def husl_to_hex(h, s, l): + return rgb_to_hex(husl_to_rgb(h, s, l)) + + +def rgb_to_husl(r, g, b): + return lch_to_husl(rgb_to_lch(r, g, b)) + + +def hex_to_husl(hex): + return rgb_to_husl(*hex_to_rgb(hex)) + + +def huslp_to_rgb(h, s, l): + return lch_to_rgb(*huslp_to_lch([h, s, l])) + + +def huslp_to_hex(h, s, l): + return rgb_to_hex(huslp_to_rgb(h, s, l)) + + +def rgb_to_huslp(r, g, b): + return lch_to_huslp(rgb_to_lch(r, g, b)) + + +def hex_to_huslp(hex): + return rgb_to_huslp(*hex_to_rgb(hex)) + + +def lch_to_rgb(l, c, h): + return xyz_to_rgb(luv_to_xyz(lch_to_luv([l, c, h]))) + + +def rgb_to_lch(r, g, b): + return luv_to_lch(xyz_to_luv(rgb_to_xyz([r, g, b]))) + + +def max_chroma(L, H): + hrad = math.radians(H) + sinH = (math.sin(hrad)) + cosH = (math.cos(hrad)) + sub1 = (math.pow(L + 16, 3.0) / 1560896.0) + sub2 = sub1 if sub1 > 0.008856 else (L / 903.3) + result = float("inf") + for row in m: + m1 = row[0] + m2 = row[1] + m3 = row[2] + top = ((0.99915 * m1 + 1.05122 * m2 + 1.14460 * m3) * sub2) + rbottom = (0.86330 * m3 - 0.17266 * m2) + lbottom = (0.12949 * m3 - 0.38848 * m1) + bottom = (rbottom * sinH + lbottom * cosH) * sub2 + + for t in (0.0, 1.0): + C = (L * (top - 1.05122 * t) / (bottom + 0.17266 * sinH * t)) + if C > 0.0 and C < result: + result = C + return result + + +def _hrad_extremum(L): + lhs = (math.pow(L, 3.0) + 48.0 * math.pow(L, 2.0) + 768.0 * L + 4096.0) / 1560896.0 + rhs = 1107.0 / 125000.0 + sub = lhs if lhs > rhs else 10.0 * L / 9033.0 + chroma = float("inf") + result = None + for row in m: + for limit in (0.0, 1.0): + [m1, m2, m3] = row + top = -3015466475.0 * m3 * sub + 603093295.0 * m2 * sub - 603093295.0 * limit + bottom = 1356959916.0 * m1 * sub - 452319972.0 * m3 * sub + hrad = math.atan2(top, bottom) + # This is a math hack to deal with tan quadrants, I'm too lazy to figure + # out how to do this properly + if limit == 0.0: + hrad += math.pi + test = max_chroma(L, math.degrees(hrad)) + if test < chroma: + chroma = test + result = hrad + return result + + +def max_chroma_pastel(L): + H = math.degrees(_hrad_extremum(L)) + return max_chroma(L, H) + + +def dot_product(a, b): + return sum(map(operator.mul, a, b)) + + +def f(t): + if t > lab_e: + return (math.pow(t, 1.0 / 3.0)) + else: + return (7.787 * t + 16.0 / 116.0) + + +def f_inv(t): + if math.pow(t, 3.0) > lab_e: + return (math.pow(t, 3.0)) + else: + return (116.0 * t - 16.0) / lab_k + + +def from_linear(c): + if c <= 0.0031308: + return 12.92 * c + else: + return (1.055 * math.pow(c, 1.0 / 2.4) - 0.055) + + +def to_linear(c): + a = 0.055 + + if c > 0.04045: + return (math.pow((c + a) / (1.0 + a), 2.4)) + else: + return (c / 12.92) + + +def rgb_prepare(triple): + ret = [] + for ch in triple: + ch = round(ch, 3) + + if ch < -0.0001 or ch > 1.0001: + raise Exception(f"Illegal RGB value {ch:f}") + + if ch < 0: + ch = 0 + if ch > 1: + ch = 1 + + # Fix for Python 3 which by default rounds 4.5 down to 4.0 + # instead of Python 2 which is rounded to 5.0 which caused + # a couple off by one errors in the tests. Tests now all pass + # in Python 2 and Python 3 + ret.append(int(round(ch * 255 + 0.001, 0))) + + return ret + + +def hex_to_rgb(hex): + if hex.startswith('#'): + hex = hex[1:] + r = int(hex[0:2], 16) / 255.0 + g = int(hex[2:4], 16) / 255.0 + b = int(hex[4:6], 16) / 255.0 + return [r, g, b] + + +def rgb_to_hex(triple): + [r, g, b] = triple + return '#%02x%02x%02x' % tuple(rgb_prepare([r, g, b])) + + +def xyz_to_rgb(triple): + xyz = map(lambda row: dot_product(row, triple), m) + return list(map(from_linear, xyz)) + + +def rgb_to_xyz(triple): + rgbl = list(map(to_linear, triple)) + return list(map(lambda row: dot_product(row, rgbl), m_inv)) + + +def xyz_to_luv(triple): + X, Y, Z = triple + + if X == Y == Z == 0.0: + return [0.0, 0.0, 0.0] + + varU = (4.0 * X) / (X + (15.0 * Y) + (3.0 * Z)) + varV = (9.0 * Y) / (X + (15.0 * Y) + (3.0 * Z)) + L = 116.0 * f(Y / refY) - 16.0 + + # Black will create a divide-by-zero error + if L == 0.0: + return [0.0, 0.0, 0.0] + + U = 13.0 * L * (varU - refU) + V = 13.0 * L * (varV - refV) + + return [L, U, V] + + +def luv_to_xyz(triple): + L, U, V = triple + + if L == 0: + return [0.0, 0.0, 0.0] + + varY = f_inv((L + 16.0) / 116.0) + varU = U / (13.0 * L) + refU + varV = V / (13.0 * L) + refV + Y = varY * refY + X = 0.0 - (9.0 * Y * varU) / ((varU - 4.0) * varV - varU * varV) + Z = (9.0 * Y - (15.0 * varV * Y) - (varV * X)) / (3.0 * varV) + + return [X, Y, Z] + + +def luv_to_lch(triple): + L, U, V = triple + + C = (math.pow(math.pow(U, 2) + math.pow(V, 2), (1.0 / 2.0))) + hrad = (math.atan2(V, U)) + H = math.degrees(hrad) + if H < 0.0: + H = 360.0 + H + + return [L, C, H] + + +def lch_to_luv(triple): + L, C, H = triple + + Hrad = math.radians(H) + U = (math.cos(Hrad) * C) + V = (math.sin(Hrad) * C) + + return [L, U, V] + + +def husl_to_lch(triple): + H, S, L = triple + + if L > 99.9999999: + return [100, 0.0, H] + if L < 0.00000001: + return [0.0, 0.0, H] + + mx = max_chroma(L, H) + C = mx / 100.0 * S + + return [L, C, H] + + +def lch_to_husl(triple): + L, C, H = triple + + if L > 99.9999999: + return [H, 0.0, 100.0] + if L < 0.00000001: + return [H, 0.0, 0.0] + + mx = max_chroma(L, H) + S = C / mx * 100.0 + + return [H, S, L] + + +def huslp_to_lch(triple): + H, S, L = triple + + if L > 99.9999999: + return [100, 0.0, H] + if L < 0.00000001: + return [0.0, 0.0, H] + + mx = max_chroma_pastel(L) + C = mx / 100.0 * S + + return [L, C, H] + + +def lch_to_huslp(triple): + L, C, H = triple + + if L > 99.9999999: + return [H, 0.0, 100.0] + if L < 0.00000001: + return [H, 0.0, 0.0] + + mx = max_chroma_pastel(L) + S = C / mx * 100.0 + + return [H, S, L] diff --git a/testbed/mwaskom__seaborn/seaborn/external/kde.py b/testbed/mwaskom__seaborn/seaborn/external/kde.py new file mode 100644 index 0000000000000000000000000000000000000000..6add4e19127895817b42f8602b5deb43ba3b725d --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/external/kde.py @@ -0,0 +1,380 @@ +""" +This module was copied from the scipy project. + +In the process of copying, some methods were removed because they depended on +other parts of scipy (especially on compiled components), allowing seaborn to +have a simple and pure Python implementation. These include: + +- integrate_gaussian +- integrate_box +- integrate_box_1d +- integrate_kde +- logpdf +- resample + +Additionally, the numpy.linalg module was substituted for scipy.linalg, +and the examples section (with doctests) was removed from the docstring + +The original scipy license is copied below: + +Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" + +# ------------------------------------------------------------------------------- +# +# Define classes for (uni/multi)-variate kernel density estimation. +# +# Currently, only Gaussian kernels are implemented. +# +# Written by: Robert Kern +# +# Date: 2004-08-09 +# +# Modified: 2005-02-10 by Robert Kern. +# Contributed to SciPy +# 2005-10-07 by Robert Kern. +# Some fixes to match the new scipy_core +# +# Copyright 2004-2005 by Enthought, Inc. +# +# ------------------------------------------------------------------------------- + +import numpy as np +from numpy import (asarray, atleast_2d, reshape, zeros, newaxis, dot, exp, pi, + sqrt, power, atleast_1d, sum, ones, cov) +from numpy import linalg + + +__all__ = ['gaussian_kde'] + + +class gaussian_kde: + """Representation of a kernel-density estimate using Gaussian kernels. + + Kernel density estimation is a way to estimate the probability density + function (PDF) of a random variable in a non-parametric way. + `gaussian_kde` works for both uni-variate and multi-variate data. It + includes automatic bandwidth determination. The estimation works best for + a unimodal distribution; bimodal or multi-modal distributions tend to be + oversmoothed. + + Parameters + ---------- + dataset : array_like + Datapoints to estimate from. In case of univariate data this is a 1-D + array, otherwise a 2-D array with shape (# of dims, # of data). + bw_method : str, scalar or callable, optional + The method used to calculate the estimator bandwidth. This can be + 'scott', 'silverman', a scalar constant or a callable. If a scalar, + this will be used directly as `kde.factor`. If a callable, it should + take a `gaussian_kde` instance as only parameter and return a scalar. + If None (default), 'scott' is used. See Notes for more details. + weights : array_like, optional + weights of datapoints. This must be the same shape as dataset. + If None (default), the samples are assumed to be equally weighted + + Attributes + ---------- + dataset : ndarray + The dataset with which `gaussian_kde` was initialized. + d : int + Number of dimensions. + n : int + Number of datapoints. + neff : int + Effective number of datapoints. + + .. versionadded:: 1.2.0 + factor : float + The bandwidth factor, obtained from `kde.covariance_factor`, with which + the covariance matrix is multiplied. + covariance : ndarray + The covariance matrix of `dataset`, scaled by the calculated bandwidth + (`kde.factor`). + inv_cov : ndarray + The inverse of `covariance`. + + Methods + ------- + evaluate + __call__ + integrate_gaussian + integrate_box_1d + integrate_box + integrate_kde + pdf + logpdf + resample + set_bandwidth + covariance_factor + + Notes + ----- + Bandwidth selection strongly influences the estimate obtained from the KDE + (much more so than the actual shape of the kernel). Bandwidth selection + can be done by a "rule of thumb", by cross-validation, by "plug-in + methods" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde` + uses a rule of thumb, the default is Scott's Rule. + + Scott's Rule [1]_, implemented as `scotts_factor`, is:: + + n**(-1./(d+4)), + + with ``n`` the number of data points and ``d`` the number of dimensions. + In the case of unequally weighted points, `scotts_factor` becomes:: + + neff**(-1./(d+4)), + + with ``neff`` the effective number of datapoints. + Silverman's Rule [2]_, implemented as `silverman_factor`, is:: + + (n * (d + 2) / 4.)**(-1. / (d + 4)). + + or in the case of unequally weighted points:: + + (neff * (d + 2) / 4.)**(-1. / (d + 4)). + + Good general descriptions of kernel density estimation can be found in [1]_ + and [2]_, the mathematics for this multi-dimensional implementation can be + found in [1]_. + + With a set of weighted samples, the effective number of datapoints ``neff`` + is defined by:: + + neff = sum(weights)^2 / sum(weights^2) + + as detailed in [5]_. + + References + ---------- + .. [1] D.W. Scott, "Multivariate Density Estimation: Theory, Practice, and + Visualization", John Wiley & Sons, New York, Chicester, 1992. + .. [2] B.W. Silverman, "Density Estimation for Statistics and Data + Analysis", Vol. 26, Monographs on Statistics and Applied Probability, + Chapman and Hall, London, 1986. + .. [3] B.A. Turlach, "Bandwidth Selection in Kernel Density Estimation: A + Review", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993. + .. [4] D.M. Bashtannyk and R.J. Hyndman, "Bandwidth selection for kernel + conditional density estimation", Computational Statistics & Data + Analysis, Vol. 36, pp. 279-298, 2001. + .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society. + Series A (General), 132, 272 + + """ + def __init__(self, dataset, bw_method=None, weights=None): + self.dataset = atleast_2d(asarray(dataset)) + if not self.dataset.size > 1: + raise ValueError("`dataset` input should have multiple elements.") + + self.d, self.n = self.dataset.shape + + if weights is not None: + self._weights = atleast_1d(weights).astype(float) + self._weights /= sum(self._weights) + if self.weights.ndim != 1: + raise ValueError("`weights` input should be one-dimensional.") + if len(self._weights) != self.n: + raise ValueError("`weights` input should be of length n") + self._neff = 1/sum(self._weights**2) + + self.set_bandwidth(bw_method=bw_method) + + def evaluate(self, points): + """Evaluate the estimated pdf on a set of points. + + Parameters + ---------- + points : (# of dimensions, # of points)-array + Alternatively, a (# of dimensions,) vector can be passed in and + treated as a single point. + + Returns + ------- + values : (# of points,)-array + The values at each point. + + Raises + ------ + ValueError : if the dimensionality of the input points is different than + the dimensionality of the KDE. + + """ + points = atleast_2d(asarray(points)) + + d, m = points.shape + if d != self.d: + if d == 1 and m == self.d: + # points was passed in as a row vector + points = reshape(points, (self.d, 1)) + m = 1 + else: + msg = f"points have dimension {d}, dataset has dimension {self.d}" + raise ValueError(msg) + + output_dtype = np.common_type(self.covariance, points) + result = zeros((m,), dtype=output_dtype) + + whitening = linalg.cholesky(self.inv_cov) + scaled_dataset = dot(whitening, self.dataset) + scaled_points = dot(whitening, points) + + if m >= self.n: + # there are more points than data, so loop over data + for i in range(self.n): + diff = scaled_dataset[:, i, newaxis] - scaled_points + energy = sum(diff * diff, axis=0) / 2.0 + result += self.weights[i]*exp(-energy) + else: + # loop over points + for i in range(m): + diff = scaled_dataset - scaled_points[:, i, newaxis] + energy = sum(diff * diff, axis=0) / 2.0 + result[i] = sum(exp(-energy)*self.weights, axis=0) + + result = result / self._norm_factor + + return result + + __call__ = evaluate + + def scotts_factor(self): + """Compute Scott's factor. + + Returns + ------- + s : float + Scott's factor. + """ + return power(self.neff, -1./(self.d+4)) + + def silverman_factor(self): + """Compute the Silverman factor. + + Returns + ------- + s : float + The silverman factor. + """ + return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4)) + + # Default method to calculate bandwidth, can be overwritten by subclass + covariance_factor = scotts_factor + covariance_factor.__doc__ = """Computes the coefficient (`kde.factor`) that + multiplies the data covariance matrix to obtain the kernel covariance + matrix. The default is `scotts_factor`. A subclass can overwrite this + method to provide a different method, or set it through a call to + `kde.set_bandwidth`.""" + + def set_bandwidth(self, bw_method=None): + """Compute the estimator bandwidth with given method. + + The new bandwidth calculated after a call to `set_bandwidth` is used + for subsequent evaluations of the estimated density. + + Parameters + ---------- + bw_method : str, scalar or callable, optional + The method used to calculate the estimator bandwidth. This can be + 'scott', 'silverman', a scalar constant or a callable. If a + scalar, this will be used directly as `kde.factor`. If a callable, + it should take a `gaussian_kde` instance as only parameter and + return a scalar. If None (default), nothing happens; the current + `kde.covariance_factor` method is kept. + + Notes + ----- + .. versionadded:: 0.11 + + """ + if bw_method is None: + pass + elif bw_method == 'scott': + self.covariance_factor = self.scotts_factor + elif bw_method == 'silverman': + self.covariance_factor = self.silverman_factor + elif np.isscalar(bw_method) and not isinstance(bw_method, str): + self._bw_method = 'use constant' + self.covariance_factor = lambda: bw_method + elif callable(bw_method): + self._bw_method = bw_method + self.covariance_factor = lambda: self._bw_method(self) + else: + msg = "`bw_method` should be 'scott', 'silverman', a scalar " \ + "or a callable." + raise ValueError(msg) + + self._compute_covariance() + + def _compute_covariance(self): + """Computes the covariance matrix for each Gaussian kernel using + covariance_factor(). + """ + self.factor = self.covariance_factor() + # Cache covariance and inverse covariance of the data + if not hasattr(self, '_data_inv_cov'): + self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1, + bias=False, + aweights=self.weights)) + self._data_inv_cov = linalg.inv(self._data_covariance) + + self.covariance = self._data_covariance * self.factor**2 + self.inv_cov = self._data_inv_cov / self.factor**2 + self._norm_factor = sqrt(linalg.det(2*pi*self.covariance)) + + def pdf(self, x): + """ + Evaluate the estimated pdf on a provided set of points. + + Notes + ----- + This is an alias for `gaussian_kde.evaluate`. See the ``evaluate`` + docstring for more details. + + """ + return self.evaluate(x) + + @property + def weights(self): + try: + return self._weights + except AttributeError: + self._weights = ones(self.n)/self.n + return self._weights + + @property + def neff(self): + try: + return self._neff + except AttributeError: + self._neff = 1/sum(self.weights**2) + return self._neff diff --git a/testbed/mwaskom__seaborn/seaborn/external/version.py b/testbed/mwaskom__seaborn/seaborn/external/version.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb57d32ce3e811d4460b1b9a93513a986347e25 --- /dev/null +++ b/testbed/mwaskom__seaborn/seaborn/external/version.py @@ -0,0 +1,461 @@ +"""Extract reference documentation from the pypa/packaging source tree. + +In the process of copying, some unused methods / classes were removed. +These include: + +- parse() +- anything involving LegacyVersion + +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made +under the terms of *both* these licenses. + +Vendored from: +- https://github.com/pypa/packaging/ +- commit ba07d8287b4554754ac7178d177033ea3f75d489 (09/09/2021) +""" + + +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +import collections +import itertools +import re +from typing import Callable, Optional, SupportsInt, Tuple, Union + +__all__ = ["Version", "InvalidVersion", "VERSION_PATTERN"] + + +# Vendored from https://github.com/pypa/packaging/blob/main/packaging/_structures.py + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __ne__(self, other: object) -> bool: + return not isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __ne__(self, other: object) -> bool: + return not isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() + + +# Vendored from https://github.com/pypa/packaging/blob/main/packaging/version.py + +InfiniteTypes = Union[InfinityType, NegativeInfinityType] +PrePostDevType = Union[InfiniteTypes, Tuple[str, int]] +SubLocalType = Union[InfiniteTypes, int, str] +LocalType = Union[ + NegativeInfinityType, + Tuple[ + Union[ + SubLocalType, + Tuple[SubLocalType, str], + Tuple[NegativeInfinityType, SubLocalType], + ], + ..., + ], +] +CmpKey = Tuple[ + int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType +] +LegacyCmpKey = Tuple[int, Tuple[str, ...]] +VersionComparisonMethod = Callable[ + [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool +] + +_Version = collections.namedtuple( + "_Version", ["epoch", "release", "dev", "pre", "post", "local"] +) + + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + _key: Union[CmpKey, LegacyCmpKey] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+
+    def __init__(self, version: str) -> None:
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __str__(self) -> str:
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        _epoch: int = self._version.epoch
+        return _epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        _release: Tuple[int, ...] = self._version.release
+        return _release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        _pre: Optional[Tuple[str, int]] = self._version.pre
+        return _pre
+
+    @property
+    def post(self) -> Optional[int]:
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: str, number: Union[str, bytes, SupportsInt]
+) -> Optional[Tuple[str, int]]:
+
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str) -> Optional[LocalType]:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[Tuple[SubLocalType]],
+) -> CmpKey:
+
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: PrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: PrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: PrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: LocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/testbed/mwaskom__seaborn/seaborn/matrix.py b/testbed/mwaskom__seaborn/seaborn/matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..76f22b89afc38a52782eca9560394c60335de508
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/matrix.py
@@ -0,0 +1,1262 @@
+"""Functions to visualize matrices of data."""
+import warnings
+
+import matplotlib as mpl
+from matplotlib.collections import LineCollection
+import matplotlib.pyplot as plt
+from matplotlib import gridspec
+import numpy as np
+import pandas as pd
+try:
+    from scipy.cluster import hierarchy
+    _no_scipy = False
+except ImportError:
+    _no_scipy = True
+
+from . import cm
+from .axisgrid import Grid
+from ._compat import get_colormap
+from .utils import (
+    despine,
+    axis_ticklabels_overlap,
+    relative_luminance,
+    to_utf8,
+    _draw_figure,
+)
+
+
+__all__ = ["heatmap", "clustermap"]
+
+
+def _index_to_label(index):
+    """Convert a pandas index or multiindex to an axis label."""
+    if isinstance(index, pd.MultiIndex):
+        return "-".join(map(to_utf8, index.names))
+    else:
+        return index.name
+
+
+def _index_to_ticklabels(index):
+    """Convert a pandas index or multiindex into ticklabels."""
+    if isinstance(index, pd.MultiIndex):
+        return ["-".join(map(to_utf8, i)) for i in index.values]
+    else:
+        return index.values
+
+
+def _convert_colors(colors):
+    """Convert either a list of colors or nested lists of colors to RGB."""
+    to_rgb = mpl.colors.to_rgb
+
+    try:
+        to_rgb(colors[0])
+        # If this works, there is only one level of colors
+        return list(map(to_rgb, colors))
+    except ValueError:
+        # If we get here, we have nested lists
+        return [list(map(to_rgb, l)) for l in colors]
+
+
+def _matrix_mask(data, mask):
+    """Ensure that data and mask are compatible and add missing values.
+
+    Values will be plotted for cells where ``mask`` is ``False``.
+
+    ``data`` is expected to be a DataFrame; ``mask`` can be an array or
+    a DataFrame.
+
+    """
+    if mask is None:
+        mask = np.zeros(data.shape, bool)
+
+    if isinstance(mask, np.ndarray):
+        # For array masks, ensure that shape matches data then convert
+        if mask.shape != data.shape:
+            raise ValueError("Mask must have the same shape as data.")
+
+        mask = pd.DataFrame(mask,
+                            index=data.index,
+                            columns=data.columns,
+                            dtype=bool)
+
+    elif isinstance(mask, pd.DataFrame):
+        # For DataFrame masks, ensure that semantic labels match data
+        if not mask.index.equals(data.index) \
+           and mask.columns.equals(data.columns):
+            err = "Mask must have the same index and columns as data."
+            raise ValueError(err)
+
+    # Add any cells with missing data to the mask
+    # This works around an issue where `plt.pcolormesh` doesn't represent
+    # missing data properly
+    mask = mask | pd.isnull(data)
+
+    return mask
+
+
+class _HeatMapper:
+    """Draw a heatmap plot of a matrix with nice labels and colormaps."""
+
+    def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,
+                 annot_kws, cbar, cbar_kws,
+                 xticklabels=True, yticklabels=True, mask=None):
+        """Initialize the plotting object."""
+        # We always want to have a DataFrame with semantic information
+        # and an ndarray to pass to matplotlib
+        if isinstance(data, pd.DataFrame):
+            plot_data = data.values
+        else:
+            plot_data = np.asarray(data)
+            data = pd.DataFrame(plot_data)
+
+        # Validate the mask and convert to DataFrame
+        mask = _matrix_mask(data, mask)
+
+        plot_data = np.ma.masked_where(np.asarray(mask), plot_data)
+
+        # Get good names for the rows and columns
+        xtickevery = 1
+        if isinstance(xticklabels, int):
+            xtickevery = xticklabels
+            xticklabels = _index_to_ticklabels(data.columns)
+        elif xticklabels is True:
+            xticklabels = _index_to_ticklabels(data.columns)
+        elif xticklabels is False:
+            xticklabels = []
+
+        ytickevery = 1
+        if isinstance(yticklabels, int):
+            ytickevery = yticklabels
+            yticklabels = _index_to_ticklabels(data.index)
+        elif yticklabels is True:
+            yticklabels = _index_to_ticklabels(data.index)
+        elif yticklabels is False:
+            yticklabels = []
+
+        if not len(xticklabels):
+            self.xticks = []
+            self.xticklabels = []
+        elif isinstance(xticklabels, str) and xticklabels == "auto":
+            self.xticks = "auto"
+            self.xticklabels = _index_to_ticklabels(data.columns)
+        else:
+            self.xticks, self.xticklabels = self._skip_ticks(xticklabels,
+                                                             xtickevery)
+
+        if not len(yticklabels):
+            self.yticks = []
+            self.yticklabels = []
+        elif isinstance(yticklabels, str) and yticklabels == "auto":
+            self.yticks = "auto"
+            self.yticklabels = _index_to_ticklabels(data.index)
+        else:
+            self.yticks, self.yticklabels = self._skip_ticks(yticklabels,
+                                                             ytickevery)
+
+        # Get good names for the axis labels
+        xlabel = _index_to_label(data.columns)
+        ylabel = _index_to_label(data.index)
+        self.xlabel = xlabel if xlabel is not None else ""
+        self.ylabel = ylabel if ylabel is not None else ""
+
+        # Determine good default values for the colormapping
+        self._determine_cmap_params(plot_data, vmin, vmax,
+                                    cmap, center, robust)
+
+        # Sort out the annotations
+        if annot is None or annot is False:
+            annot = False
+            annot_data = None
+        else:
+            if isinstance(annot, bool):
+                annot_data = plot_data
+            else:
+                annot_data = np.asarray(annot)
+                if annot_data.shape != plot_data.shape:
+                    err = "`data` and `annot` must have same shape."
+                    raise ValueError(err)
+            annot = True
+
+        # Save other attributes to the object
+        self.data = data
+        self.plot_data = plot_data
+
+        self.annot = annot
+        self.annot_data = annot_data
+
+        self.fmt = fmt
+        self.annot_kws = {} if annot_kws is None else annot_kws.copy()
+        self.cbar = cbar
+        self.cbar_kws = {} if cbar_kws is None else cbar_kws.copy()
+
+    def _determine_cmap_params(self, plot_data, vmin, vmax,
+                               cmap, center, robust):
+        """Use some heuristics to set good defaults for colorbar and range."""
+
+        # plot_data is a np.ma.array instance
+        calc_data = plot_data.astype(float).filled(np.nan)
+        if vmin is None:
+            if robust:
+                vmin = np.nanpercentile(calc_data, 2)
+            else:
+                vmin = np.nanmin(calc_data)
+        if vmax is None:
+            if robust:
+                vmax = np.nanpercentile(calc_data, 98)
+            else:
+                vmax = np.nanmax(calc_data)
+        self.vmin, self.vmax = vmin, vmax
+
+        # Choose default colormaps if not provided
+        if cmap is None:
+            if center is None:
+                self.cmap = cm.rocket
+            else:
+                self.cmap = cm.icefire
+        elif isinstance(cmap, str):
+            self.cmap = get_colormap(cmap)
+        elif isinstance(cmap, list):
+            self.cmap = mpl.colors.ListedColormap(cmap)
+        else:
+            self.cmap = cmap
+
+        # Recenter a divergent colormap
+        if center is not None:
+
+            # Copy bad values
+            # in mpl<3.2 only masked values are honored with "bad" color spec
+            # (see https://github.com/matplotlib/matplotlib/pull/14257)
+            bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]
+
+            # under/over values are set for sure when cmap extremes
+            # do not map to the same color as +-inf
+            under = self.cmap(-np.inf)
+            over = self.cmap(np.inf)
+            under_set = under != self.cmap(0)
+            over_set = over != self.cmap(self.cmap.N - 1)
+
+            vrange = max(vmax - center, center - vmin)
+            normlize = mpl.colors.Normalize(center - vrange, center + vrange)
+            cmin, cmax = normlize([vmin, vmax])
+            cc = np.linspace(cmin, cmax, 256)
+            self.cmap = mpl.colors.ListedColormap(self.cmap(cc))
+            self.cmap.set_bad(bad)
+            if under_set:
+                self.cmap.set_under(under)
+            if over_set:
+                self.cmap.set_over(over)
+
+    def _annotate_heatmap(self, ax, mesh):
+        """Add textual labels with the value in each cell."""
+        mesh.update_scalarmappable()
+        height, width = self.annot_data.shape
+        xpos, ypos = np.meshgrid(np.arange(width) + .5, np.arange(height) + .5)
+        for x, y, m, color, val in zip(xpos.flat, ypos.flat,
+                                       mesh.get_array(), mesh.get_facecolors(),
+                                       self.annot_data.flat):
+            if m is not np.ma.masked:
+                lum = relative_luminance(color)
+                text_color = ".15" if lum > .408 else "w"
+                annotation = ("{:" + self.fmt + "}").format(val)
+                text_kwargs = dict(color=text_color, ha="center", va="center")
+                text_kwargs.update(self.annot_kws)
+                ax.text(x, y, annotation, **text_kwargs)
+
+    def _skip_ticks(self, labels, tickevery):
+        """Return ticks and labels at evenly spaced intervals."""
+        n = len(labels)
+        if tickevery == 0:
+            ticks, labels = [], []
+        elif tickevery == 1:
+            ticks, labels = np.arange(n) + .5, labels
+        else:
+            start, end, step = 0, n, tickevery
+            ticks = np.arange(start, end, step) + .5
+            labels = labels[start:end:step]
+        return ticks, labels
+
+    def _auto_ticks(self, ax, labels, axis):
+        """Determine ticks and ticklabels that minimize overlap."""
+        transform = ax.figure.dpi_scale_trans.inverted()
+        bbox = ax.get_window_extent().transformed(transform)
+        size = [bbox.width, bbox.height][axis]
+        axis = [ax.xaxis, ax.yaxis][axis]
+        tick, = axis.set_ticks([0])
+        fontsize = tick.label1.get_size()
+        max_ticks = int(size // (fontsize / 72))
+        if max_ticks < 1:
+            return [], []
+        tick_every = len(labels) // max_ticks + 1
+        tick_every = 1 if tick_every == 0 else tick_every
+        ticks, labels = self._skip_ticks(labels, tick_every)
+        return ticks, labels
+
+    def plot(self, ax, cax, kws):
+        """Draw the heatmap on the provided Axes."""
+        # Remove all the Axes spines
+        despine(ax=ax, left=True, bottom=True)
+
+        # setting vmin/vmax in addition to norm is deprecated
+        # so avoid setting if norm is set
+        if "norm" not in kws:
+            kws.setdefault("vmin", self.vmin)
+            kws.setdefault("vmax", self.vmax)
+
+        # Draw the heatmap
+        mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws)
+
+        # Set the axis limits
+        ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))
+
+        # Invert the y axis to show the plot in matrix form
+        ax.invert_yaxis()
+
+        # Possibly add a colorbar
+        if self.cbar:
+            cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws)
+            cb.outline.set_linewidth(0)
+            # If rasterized is passed to pcolormesh, also rasterize the
+            # colorbar to avoid white lines on the PDF rendering
+            if kws.get('rasterized', False):
+                cb.solids.set_rasterized(True)
+
+        # Add row and column labels
+        if isinstance(self.xticks, str) and self.xticks == "auto":
+            xticks, xticklabels = self._auto_ticks(ax, self.xticklabels, 0)
+        else:
+            xticks, xticklabels = self.xticks, self.xticklabels
+
+        if isinstance(self.yticks, str) and self.yticks == "auto":
+            yticks, yticklabels = self._auto_ticks(ax, self.yticklabels, 1)
+        else:
+            yticks, yticklabels = self.yticks, self.yticklabels
+
+        ax.set(xticks=xticks, yticks=yticks)
+        xtl = ax.set_xticklabels(xticklabels)
+        ytl = ax.set_yticklabels(yticklabels, rotation="vertical")
+        plt.setp(ytl, va="center")  # GH2484
+
+        # Possibly rotate them if they overlap
+        _draw_figure(ax.figure)
+
+        if axis_ticklabels_overlap(xtl):
+            plt.setp(xtl, rotation="vertical")
+        if axis_ticklabels_overlap(ytl):
+            plt.setp(ytl, rotation="horizontal")
+
+        # Add the axis labels
+        ax.set(xlabel=self.xlabel, ylabel=self.ylabel)
+
+        # Annotate the cells with the formatted values
+        if self.annot:
+            self._annotate_heatmap(ax, mesh)
+
+
+def heatmap(
+    data, *,
+    vmin=None, vmax=None, cmap=None, center=None, robust=False,
+    annot=None, fmt=".2g", annot_kws=None,
+    linewidths=0, linecolor="white",
+    cbar=True, cbar_kws=None, cbar_ax=None,
+    square=False, xticklabels="auto", yticklabels="auto",
+    mask=None, ax=None,
+    **kwargs
+):
+    """Plot rectangular data as a color-encoded matrix.
+
+    This is an Axes-level function and will draw the heatmap into the
+    currently-active Axes if none is provided to the ``ax`` argument.  Part of
+    this Axes space will be taken and used to plot a colormap, unless ``cbar``
+    is False or a separate Axes is provided to ``cbar_ax``.
+
+    Parameters
+    ----------
+    data : rectangular dataset
+        2D dataset that can be coerced into an ndarray. If a Pandas DataFrame
+        is provided, the index/column information will be used to label the
+        columns and rows.
+    vmin, vmax : floats, optional
+        Values to anchor the colormap, otherwise they are inferred from the
+        data and other keyword arguments.
+    cmap : matplotlib colormap name or object, or list of colors, optional
+        The mapping from data values to color space. If not provided, the
+        default will depend on whether ``center`` is set.
+    center : float, optional
+        The value at which to center the colormap when plotting divergent data.
+        Using this parameter will change the default ``cmap`` if none is
+        specified.
+    robust : bool, optional
+        If True and ``vmin`` or ``vmax`` are absent, the colormap range is
+        computed with robust quantiles instead of the extreme values.
+    annot : bool or rectangular dataset, optional
+        If True, write the data value in each cell. If an array-like with the
+        same shape as ``data``, then use this to annotate the heatmap instead
+        of the data. Note that DataFrames will match on position, not index.
+    fmt : str, optional
+        String formatting code to use when adding annotations.
+    annot_kws : dict of key, value mappings, optional
+        Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``
+        is True.
+    linewidths : float, optional
+        Width of the lines that will divide each cell.
+    linecolor : color, optional
+        Color of the lines that will divide each cell.
+    cbar : bool, optional
+        Whether to draw a colorbar.
+    cbar_kws : dict of key, value mappings, optional
+        Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.
+    cbar_ax : matplotlib Axes, optional
+        Axes in which to draw the colorbar, otherwise take space from the
+        main Axes.
+    square : bool, optional
+        If True, set the Axes aspect to "equal" so each cell will be
+        square-shaped.
+    xticklabels, yticklabels : "auto", bool, list-like, or int, optional
+        If True, plot the column names of the dataframe. If False, don't plot
+        the column names. If list-like, plot these alternate labels as the
+        xticklabels. If an integer, use the column names but plot only every
+        n label. If "auto", try to densely plot non-overlapping labels.
+    mask : bool array or DataFrame, optional
+        If passed, data will not be shown in cells where ``mask`` is True.
+        Cells with missing values are automatically masked.
+    ax : matplotlib Axes, optional
+        Axes in which to draw the plot, otherwise use the currently-active
+        Axes.
+    kwargs : other keyword arguments
+        All other keyword arguments are passed to
+        :meth:`matplotlib.axes.Axes.pcolormesh`.
+
+    Returns
+    -------
+    ax : matplotlib Axes
+        Axes object with the heatmap.
+
+    See Also
+    --------
+    clustermap : Plot a matrix using hierarchical clustering to arrange the
+                 rows and columns.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/heatmap.rst
+
+    """
+    # Initialize the plotter object
+    plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,
+                          annot_kws, cbar, cbar_kws, xticklabels,
+                          yticklabels, mask)
+
+    # Add the pcolormesh kwargs here
+    kwargs["linewidths"] = linewidths
+    kwargs["edgecolor"] = linecolor
+
+    # Draw the plot and return the Axes
+    if ax is None:
+        ax = plt.gca()
+    if square:
+        ax.set_aspect("equal")
+    plotter.plot(ax, cbar_ax, kwargs)
+    return ax
+
+
+class _DendrogramPlotter:
+    """Object for drawing tree of similarities between data rows/columns"""
+
+    def __init__(self, data, linkage, metric, method, axis, label, rotate):
+        """Plot a dendrogram of the relationships between the columns of data
+
+        Parameters
+        ----------
+        data : pandas.DataFrame
+            Rectangular data
+        """
+        self.axis = axis
+        if self.axis == 1:
+            data = data.T
+
+        if isinstance(data, pd.DataFrame):
+            array = data.values
+        else:
+            array = np.asarray(data)
+            data = pd.DataFrame(array)
+
+        self.array = array
+        self.data = data
+
+        self.shape = self.data.shape
+        self.metric = metric
+        self.method = method
+        self.axis = axis
+        self.label = label
+        self.rotate = rotate
+
+        if linkage is None:
+            self.linkage = self.calculated_linkage
+        else:
+            self.linkage = linkage
+        self.dendrogram = self.calculate_dendrogram()
+
+        # Dendrogram ends are always at multiples of 5, who knows why
+        ticks = 10 * np.arange(self.data.shape[0]) + 5
+
+        if self.label:
+            ticklabels = _index_to_ticklabels(self.data.index)
+            ticklabels = [ticklabels[i] for i in self.reordered_ind]
+            if self.rotate:
+                self.xticks = []
+                self.yticks = ticks
+                self.xticklabels = []
+
+                self.yticklabels = ticklabels
+                self.ylabel = _index_to_label(self.data.index)
+                self.xlabel = ''
+            else:
+                self.xticks = ticks
+                self.yticks = []
+                self.xticklabels = ticklabels
+                self.yticklabels = []
+                self.ylabel = ''
+                self.xlabel = _index_to_label(self.data.index)
+        else:
+            self.xticks, self.yticks = [], []
+            self.yticklabels, self.xticklabels = [], []
+            self.xlabel, self.ylabel = '', ''
+
+        self.dependent_coord = self.dendrogram['dcoord']
+        self.independent_coord = self.dendrogram['icoord']
+
+    def _calculate_linkage_scipy(self):
+        linkage = hierarchy.linkage(self.array, method=self.method,
+                                    metric=self.metric)
+        return linkage
+
+    def _calculate_linkage_fastcluster(self):
+        import fastcluster
+        # Fastcluster has a memory-saving vectorized version, but only
+        # with certain linkage methods, and mostly with euclidean metric
+        # vector_methods = ('single', 'centroid', 'median', 'ward')
+        euclidean_methods = ('centroid', 'median', 'ward')
+        euclidean = self.metric == 'euclidean' and self.method in \
+            euclidean_methods
+        if euclidean or self.method == 'single':
+            return fastcluster.linkage_vector(self.array,
+                                              method=self.method,
+                                              metric=self.metric)
+        else:
+            linkage = fastcluster.linkage(self.array, method=self.method,
+                                          metric=self.metric)
+            return linkage
+
+    @property
+    def calculated_linkage(self):
+
+        try:
+            return self._calculate_linkage_fastcluster()
+        except ImportError:
+            if np.product(self.shape) >= 10000:
+                msg = ("Clustering large matrix with scipy. Installing "
+                       "`fastcluster` may give better performance.")
+                warnings.warn(msg)
+
+        return self._calculate_linkage_scipy()
+
+    def calculate_dendrogram(self):
+        """Calculates a dendrogram based on the linkage matrix
+
+        Made a separate function, not a property because don't want to
+        recalculate the dendrogram every time it is accessed.
+
+        Returns
+        -------
+        dendrogram : dict
+            Dendrogram dictionary as returned by scipy.cluster.hierarchy
+            .dendrogram. The important key-value pairing is
+            "reordered_ind" which indicates the re-ordering of the matrix
+        """
+        return hierarchy.dendrogram(self.linkage, no_plot=True,
+                                    color_threshold=-np.inf)
+
+    @property
+    def reordered_ind(self):
+        """Indices of the matrix, reordered by the dendrogram"""
+        return self.dendrogram['leaves']
+
+    def plot(self, ax, tree_kws):
+        """Plots a dendrogram of the similarities between data on the axes
+
+        Parameters
+        ----------
+        ax : matplotlib.axes.Axes
+            Axes object upon which the dendrogram is plotted
+
+        """
+        tree_kws = {} if tree_kws is None else tree_kws.copy()
+        tree_kws.setdefault("linewidths", .5)
+        tree_kws.setdefault("colors", tree_kws.pop("color", (.2, .2, .2)))
+
+        if self.rotate and self.axis == 0:
+            coords = zip(self.dependent_coord, self.independent_coord)
+        else:
+            coords = zip(self.independent_coord, self.dependent_coord)
+        lines = LineCollection([list(zip(x, y)) for x, y in coords],
+                               **tree_kws)
+
+        ax.add_collection(lines)
+        number_of_leaves = len(self.reordered_ind)
+        max_dependent_coord = max(map(max, self.dependent_coord))
+
+        if self.rotate:
+            ax.yaxis.set_ticks_position('right')
+
+            # Constants 10 and 1.05 come from
+            # `scipy.cluster.hierarchy._plot_dendrogram`
+            ax.set_ylim(0, number_of_leaves * 10)
+            ax.set_xlim(0, max_dependent_coord * 1.05)
+
+            ax.invert_xaxis()
+            ax.invert_yaxis()
+        else:
+            # Constants 10 and 1.05 come from
+            # `scipy.cluster.hierarchy._plot_dendrogram`
+            ax.set_xlim(0, number_of_leaves * 10)
+            ax.set_ylim(0, max_dependent_coord * 1.05)
+
+        despine(ax=ax, bottom=True, left=True)
+
+        ax.set(xticks=self.xticks, yticks=self.yticks,
+               xlabel=self.xlabel, ylabel=self.ylabel)
+        xtl = ax.set_xticklabels(self.xticklabels)
+        ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical')
+
+        # Force a draw of the plot to avoid matplotlib window error
+        _draw_figure(ax.figure)
+
+        if len(ytl) > 0 and axis_ticklabels_overlap(ytl):
+            plt.setp(ytl, rotation="horizontal")
+        if len(xtl) > 0 and axis_ticklabels_overlap(xtl):
+            plt.setp(xtl, rotation="vertical")
+        return self
+
+
+def dendrogram(
+    data, *,
+    linkage=None, axis=1, label=True, metric='euclidean',
+    method='average', rotate=False, tree_kws=None, ax=None
+):
+    """Draw a tree diagram of relationships within a matrix
+
+    Parameters
+    ----------
+    data : pandas.DataFrame
+        Rectangular data
+    linkage : numpy.array, optional
+        Linkage matrix
+    axis : int, optional
+        Which axis to use to calculate linkage. 0 is rows, 1 is columns.
+    label : bool, optional
+        If True, label the dendrogram at leaves with column or row names
+    metric : str, optional
+        Distance metric. Anything valid for scipy.spatial.distance.pdist
+    method : str, optional
+        Linkage method to use. Anything valid for
+        scipy.cluster.hierarchy.linkage
+    rotate : bool, optional
+        When plotting the matrix, whether to rotate it 90 degrees
+        counter-clockwise, so the leaves face right
+    tree_kws : dict, optional
+        Keyword arguments for the ``matplotlib.collections.LineCollection``
+        that is used for plotting the lines of the dendrogram tree.
+    ax : matplotlib axis, optional
+        Axis to plot on, otherwise uses current axis
+
+    Returns
+    -------
+    dendrogramplotter : _DendrogramPlotter
+        A Dendrogram plotter object.
+
+    Notes
+    -----
+    Access the reordered dendrogram indices with
+    dendrogramplotter.reordered_ind
+
+    """
+    if _no_scipy:
+        raise RuntimeError("dendrogram requires scipy to be installed")
+
+    plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis,
+                                 metric=metric, method=method,
+                                 label=label, rotate=rotate)
+    if ax is None:
+        ax = plt.gca()
+
+    return plotter.plot(ax=ax, tree_kws=tree_kws)
+
+
+class ClusterGrid(Grid):
+
+    def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,
+                 figsize=None, row_colors=None, col_colors=None, mask=None,
+                 dendrogram_ratio=None, colors_ratio=None, cbar_pos=None):
+        """Grid object for organizing clustered heatmap input on to axes"""
+        if _no_scipy:
+            raise RuntimeError("ClusterGrid requires scipy to be available")
+
+        if isinstance(data, pd.DataFrame):
+            self.data = data
+        else:
+            self.data = pd.DataFrame(data)
+
+        self.data2d = self.format_data(self.data, pivot_kws, z_score,
+                                       standard_scale)
+
+        self.mask = _matrix_mask(self.data2d, mask)
+
+        self._figure = plt.figure(figsize=figsize)
+
+        self.row_colors, self.row_color_labels = \
+            self._preprocess_colors(data, row_colors, axis=0)
+        self.col_colors, self.col_color_labels = \
+            self._preprocess_colors(data, col_colors, axis=1)
+
+        try:
+            row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio
+        except TypeError:
+            row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio
+
+        try:
+            row_colors_ratio, col_colors_ratio = colors_ratio
+        except TypeError:
+            row_colors_ratio = col_colors_ratio = colors_ratio
+
+        width_ratios = self.dim_ratios(self.row_colors,
+                                       row_dendrogram_ratio,
+                                       row_colors_ratio)
+        height_ratios = self.dim_ratios(self.col_colors,
+                                        col_dendrogram_ratio,
+                                        col_colors_ratio)
+
+        nrows = 2 if self.col_colors is None else 3
+        ncols = 2 if self.row_colors is None else 3
+
+        self.gs = gridspec.GridSpec(nrows, ncols,
+                                    width_ratios=width_ratios,
+                                    height_ratios=height_ratios)
+
+        self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0])
+        self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1])
+        self.ax_row_dendrogram.set_axis_off()
+        self.ax_col_dendrogram.set_axis_off()
+
+        self.ax_row_colors = None
+        self.ax_col_colors = None
+
+        if self.row_colors is not None:
+            self.ax_row_colors = self._figure.add_subplot(
+                self.gs[-1, 1])
+        if self.col_colors is not None:
+            self.ax_col_colors = self._figure.add_subplot(
+                self.gs[1, -1])
+
+        self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1])
+        if cbar_pos is None:
+            self.ax_cbar = self.cax = None
+        else:
+            # Initialize the colorbar axes in the gridspec so that tight_layout
+            # works. We will move it where it belongs later. This is a hack.
+            self.ax_cbar = self._figure.add_subplot(self.gs[0, 0])
+            self.cax = self.ax_cbar  # Backwards compatibility
+        self.cbar_pos = cbar_pos
+
+        self.dendrogram_row = None
+        self.dendrogram_col = None
+
+    def _preprocess_colors(self, data, colors, axis):
+        """Preprocess {row/col}_colors to extract labels and convert colors."""
+        labels = None
+
+        if colors is not None:
+            if isinstance(colors, (pd.DataFrame, pd.Series)):
+
+                # If data is unindexed, raise
+                if (not hasattr(data, "index") and axis == 0) or (
+                    not hasattr(data, "columns") and axis == 1
+                ):
+                    axis_name = "col" if axis else "row"
+                    msg = (f"{axis_name}_colors indices can't be matched with data "
+                           f"indices. Provide {axis_name}_colors as a non-indexed "
+                           "datatype, e.g. by using `.to_numpy()``")
+                    raise TypeError(msg)
+
+                # Ensure colors match data indices
+                if axis == 0:
+                    colors = colors.reindex(data.index)
+                else:
+                    colors = colors.reindex(data.columns)
+
+                # Replace na's with white color
+                # TODO We should set these to transparent instead
+                colors = colors.astype(object).fillna('white')
+
+                # Extract color values and labels from frame/series
+                if isinstance(colors, pd.DataFrame):
+                    labels = list(colors.columns)
+                    colors = colors.T.values
+                else:
+                    if colors.name is None:
+                        labels = [""]
+                    else:
+                        labels = [colors.name]
+                    colors = colors.values
+
+            colors = _convert_colors(colors)
+
+        return colors, labels
+
+    def format_data(self, data, pivot_kws, z_score=None,
+                    standard_scale=None):
+        """Extract variables from data or use directly."""
+
+        # Either the data is already in 2d matrix format, or need to do a pivot
+        if pivot_kws is not None:
+            data2d = data.pivot(**pivot_kws)
+        else:
+            data2d = data
+
+        if z_score is not None and standard_scale is not None:
+            raise ValueError(
+                'Cannot perform both z-scoring and standard-scaling on data')
+
+        if z_score is not None:
+            data2d = self.z_score(data2d, z_score)
+        if standard_scale is not None:
+            data2d = self.standard_scale(data2d, standard_scale)
+        return data2d
+
+    @staticmethod
+    def z_score(data2d, axis=1):
+        """Standarize the mean and variance of the data axis
+
+        Parameters
+        ----------
+        data2d : pandas.DataFrame
+            Data to normalize
+        axis : int
+            Which axis to normalize across. If 0, normalize across rows, if 1,
+            normalize across columns.
+
+        Returns
+        -------
+        normalized : pandas.DataFrame
+            Noramlized data with a mean of 0 and variance of 1 across the
+            specified axis.
+        """
+        if axis == 1:
+            z_scored = data2d
+        else:
+            z_scored = data2d.T
+
+        z_scored = (z_scored - z_scored.mean()) / z_scored.std()
+
+        if axis == 1:
+            return z_scored
+        else:
+            return z_scored.T
+
+    @staticmethod
+    def standard_scale(data2d, axis=1):
+        """Divide the data by the difference between the max and min
+
+        Parameters
+        ----------
+        data2d : pandas.DataFrame
+            Data to normalize
+        axis : int
+            Which axis to normalize across. If 0, normalize across rows, if 1,
+            normalize across columns.
+
+        Returns
+        -------
+        standardized : pandas.DataFrame
+            Noramlized data with a mean of 0 and variance of 1 across the
+            specified axis.
+
+        """
+        # Normalize these values to range from 0 to 1
+        if axis == 1:
+            standardized = data2d
+        else:
+            standardized = data2d.T
+
+        subtract = standardized.min()
+        standardized = (standardized - subtract) / (
+            standardized.max() - standardized.min())
+
+        if axis == 1:
+            return standardized
+        else:
+            return standardized.T
+
+    def dim_ratios(self, colors, dendrogram_ratio, colors_ratio):
+        """Get the proportions of the figure taken up by each axes."""
+        ratios = [dendrogram_ratio]
+
+        if colors is not None:
+            # Colors are encoded as rgb, so there is an extra dimension
+            if np.ndim(colors) > 2:
+                n_colors = len(colors)
+            else:
+                n_colors = 1
+
+            ratios += [n_colors * colors_ratio]
+
+        # Add the ratio for the heatmap itself
+        ratios.append(1 - sum(ratios))
+
+        return ratios
+
+    @staticmethod
+    def color_list_to_matrix_and_cmap(colors, ind, axis=0):
+        """Turns a list of colors into a numpy matrix and matplotlib colormap
+
+        These arguments can now be plotted using heatmap(matrix, cmap)
+        and the provided colors will be plotted.
+
+        Parameters
+        ----------
+        colors : list of matplotlib colors
+            Colors to label the rows or columns of a dataframe.
+        ind : list of ints
+            Ordering of the rows or columns, to reorder the original colors
+            by the clustered dendrogram order
+        axis : int
+            Which axis this is labeling
+
+        Returns
+        -------
+        matrix : numpy.array
+            A numpy array of integer values, where each indexes into the cmap
+        cmap : matplotlib.colors.ListedColormap
+
+        """
+        try:
+            mpl.colors.to_rgb(colors[0])
+        except ValueError:
+            # We have a 2D color structure
+            m, n = len(colors), len(colors[0])
+            if not all(len(c) == n for c in colors[1:]):
+                raise ValueError("Multiple side color vectors must have same size")
+        else:
+            # We have one vector of colors
+            m, n = 1, len(colors)
+            colors = [colors]
+
+        # Map from unique colors to colormap index value
+        unique_colors = {}
+        matrix = np.zeros((m, n), int)
+        for i, inner in enumerate(colors):
+            for j, color in enumerate(inner):
+                idx = unique_colors.setdefault(color, len(unique_colors))
+                matrix[i, j] = idx
+
+        # Reorder for clustering and transpose for axis
+        matrix = matrix[:, ind]
+        if axis == 0:
+            matrix = matrix.T
+
+        cmap = mpl.colors.ListedColormap(list(unique_colors))
+        return matrix, cmap
+
+    def plot_dendrograms(self, row_cluster, col_cluster, metric, method,
+                         row_linkage, col_linkage, tree_kws):
+        # Plot the row dendrogram
+        if row_cluster:
+            self.dendrogram_row = dendrogram(
+                self.data2d, metric=metric, method=method, label=False, axis=0,
+                ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage,
+                tree_kws=tree_kws
+            )
+        else:
+            self.ax_row_dendrogram.set_xticks([])
+            self.ax_row_dendrogram.set_yticks([])
+        # PLot the column dendrogram
+        if col_cluster:
+            self.dendrogram_col = dendrogram(
+                self.data2d, metric=metric, method=method, label=False,
+                axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage,
+                tree_kws=tree_kws
+            )
+        else:
+            self.ax_col_dendrogram.set_xticks([])
+            self.ax_col_dendrogram.set_yticks([])
+        despine(ax=self.ax_row_dendrogram, bottom=True, left=True)
+        despine(ax=self.ax_col_dendrogram, bottom=True, left=True)
+
+    def plot_colors(self, xind, yind, **kws):
+        """Plots color labels between the dendrogram and the heatmap
+
+        Parameters
+        ----------
+        heatmap_kws : dict
+            Keyword arguments heatmap
+
+        """
+        # Remove any custom colormap and centering
+        # TODO this code has consistently caused problems when we
+        # have missed kwargs that need to be excluded that it might
+        # be better to rewrite *in*clusively.
+        kws = kws.copy()
+        kws.pop('cmap', None)
+        kws.pop('norm', None)
+        kws.pop('center', None)
+        kws.pop('annot', None)
+        kws.pop('vmin', None)
+        kws.pop('vmax', None)
+        kws.pop('robust', None)
+        kws.pop('xticklabels', None)
+        kws.pop('yticklabels', None)
+
+        # Plot the row colors
+        if self.row_colors is not None:
+            matrix, cmap = self.color_list_to_matrix_and_cmap(
+                self.row_colors, yind, axis=0)
+
+            # Get row_color labels
+            if self.row_color_labels is not None:
+                row_color_labels = self.row_color_labels
+            else:
+                row_color_labels = False
+
+            heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors,
+                    xticklabels=row_color_labels, yticklabels=False, **kws)
+
+            # Adjust rotation of labels
+            if row_color_labels is not False:
+                plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90)
+        else:
+            despine(self.ax_row_colors, left=True, bottom=True)
+
+        # Plot the column colors
+        if self.col_colors is not None:
+            matrix, cmap = self.color_list_to_matrix_and_cmap(
+                self.col_colors, xind, axis=1)
+
+            # Get col_color labels
+            if self.col_color_labels is not None:
+                col_color_labels = self.col_color_labels
+            else:
+                col_color_labels = False
+
+            heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors,
+                    xticklabels=False, yticklabels=col_color_labels, **kws)
+
+            # Adjust rotation of labels, place on right side
+            if col_color_labels is not False:
+                self.ax_col_colors.yaxis.tick_right()
+                plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0)
+        else:
+            despine(self.ax_col_colors, left=True, bottom=True)
+
+    def plot_matrix(self, colorbar_kws, xind, yind, **kws):
+        self.data2d = self.data2d.iloc[yind, xind]
+        self.mask = self.mask.iloc[yind, xind]
+
+        # Try to reorganize specified tick labels, if provided
+        xtl = kws.pop("xticklabels", "auto")
+        try:
+            xtl = np.asarray(xtl)[xind]
+        except (TypeError, IndexError):
+            pass
+        ytl = kws.pop("yticklabels", "auto")
+        try:
+            ytl = np.asarray(ytl)[yind]
+        except (TypeError, IndexError):
+            pass
+
+        # Reorganize the annotations to match the heatmap
+        annot = kws.pop("annot", None)
+        if annot is None or annot is False:
+            pass
+        else:
+            if isinstance(annot, bool):
+                annot_data = self.data2d
+            else:
+                annot_data = np.asarray(annot)
+                if annot_data.shape != self.data2d.shape:
+                    err = "`data` and `annot` must have same shape."
+                    raise ValueError(err)
+                annot_data = annot_data[yind][:, xind]
+            annot = annot_data
+
+        # Setting ax_cbar=None in clustermap call implies no colorbar
+        kws.setdefault("cbar", self.ax_cbar is not None)
+        heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar,
+                cbar_kws=colorbar_kws, mask=self.mask,
+                xticklabels=xtl, yticklabels=ytl, annot=annot, **kws)
+
+        ytl = self.ax_heatmap.get_yticklabels()
+        ytl_rot = None if not ytl else ytl[0].get_rotation()
+        self.ax_heatmap.yaxis.set_ticks_position('right')
+        self.ax_heatmap.yaxis.set_label_position('right')
+        if ytl_rot is not None:
+            ytl = self.ax_heatmap.get_yticklabels()
+            plt.setp(ytl, rotation=ytl_rot)
+
+        tight_params = dict(h_pad=.02, w_pad=.02)
+        if self.ax_cbar is None:
+            self._figure.tight_layout(**tight_params)
+        else:
+            # Turn the colorbar axes off for tight layout so that its
+            # ticks don't interfere with the rest of the plot layout.
+            # Then move it.
+            self.ax_cbar.set_axis_off()
+            self._figure.tight_layout(**tight_params)
+            self.ax_cbar.set_axis_on()
+            self.ax_cbar.set_position(self.cbar_pos)
+
+    def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster,
+             row_linkage, col_linkage, tree_kws, **kws):
+
+        # heatmap square=True sets the aspect ratio on the axes, but that is
+        # not compatible with the multi-axes layout of clustergrid
+        if kws.get("square", False):
+            msg = "``square=True`` ignored in clustermap"
+            warnings.warn(msg)
+            kws.pop("square")
+
+        colorbar_kws = {} if colorbar_kws is None else colorbar_kws
+
+        self.plot_dendrograms(row_cluster, col_cluster, metric, method,
+                              row_linkage=row_linkage, col_linkage=col_linkage,
+                              tree_kws=tree_kws)
+        try:
+            xind = self.dendrogram_col.reordered_ind
+        except AttributeError:
+            xind = np.arange(self.data2d.shape[1])
+        try:
+            yind = self.dendrogram_row.reordered_ind
+        except AttributeError:
+            yind = np.arange(self.data2d.shape[0])
+
+        self.plot_colors(xind, yind, **kws)
+        self.plot_matrix(colorbar_kws, xind, yind, **kws)
+        return self
+
+
+def clustermap(
+    data, *,
+    pivot_kws=None, method='average', metric='euclidean',
+    z_score=None, standard_scale=None, figsize=(10, 10),
+    cbar_kws=None, row_cluster=True, col_cluster=True,
+    row_linkage=None, col_linkage=None,
+    row_colors=None, col_colors=None, mask=None,
+    dendrogram_ratio=.2, colors_ratio=0.03,
+    cbar_pos=(.02, .8, .05, .18), tree_kws=None,
+    **kwargs
+):
+    """
+    Plot a matrix dataset as a hierarchically-clustered heatmap.
+
+    This function requires scipy to be available.
+
+    Parameters
+    ----------
+    data : 2D array-like
+        Rectangular data for clustering. Cannot contain NAs.
+    pivot_kws : dict, optional
+        If `data` is a tidy dataframe, can provide keyword arguments for
+        pivot to create a rectangular dataframe.
+    method : str, optional
+        Linkage method to use for calculating clusters. See
+        :func:`scipy.cluster.hierarchy.linkage` documentation for more
+        information.
+    metric : str, optional
+        Distance metric to use for the data. See
+        :func:`scipy.spatial.distance.pdist` documentation for more options.
+        To use different metrics (or methods) for rows and columns, you may
+        construct each linkage matrix yourself and provide them as
+        `{row,col}_linkage`.
+    z_score : int or None, optional
+        Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores
+        for the rows or the columns. Z scores are: z = (x - mean)/std, so
+        values in each row (column) will get the mean of the row (column)
+        subtracted, then divided by the standard deviation of the row (column).
+        This ensures that each row (column) has mean of 0 and variance of 1.
+    standard_scale : int or None, optional
+        Either 0 (rows) or 1 (columns). Whether or not to standardize that
+        dimension, meaning for each row or column, subtract the minimum and
+        divide each by its maximum.
+    figsize : tuple of (width, height), optional
+        Overall size of the figure.
+    cbar_kws : dict, optional
+        Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to
+        add a label to the colorbar.
+    {row,col}_cluster : bool, optional
+        If ``True``, cluster the {rows, columns}.
+    {row,col}_linkage : :class:`numpy.ndarray`, optional
+        Precomputed linkage matrix for the rows or columns. See
+        :func:`scipy.cluster.hierarchy.linkage` for specific formats.
+    {row,col}_colors : list-like or pandas DataFrame/Series, optional
+        List of colors to label for either the rows or columns. Useful to evaluate
+        whether samples within a group are clustered together. Can use nested lists or
+        DataFrame for multiple color levels of labeling. If given as a
+        :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are
+        extracted from the DataFrames column names or from the name of the Series.
+        DataFrame/Series colors are also matched to the data by their index, ensuring
+        colors are drawn in the correct order.
+    mask : bool array or DataFrame, optional
+        If passed, data will not be shown in cells where `mask` is True.
+        Cells with missing values are automatically masked. Only used for
+        visualizing, not for calculating.
+    {dendrogram,colors}_ratio : float, or pair of floats, optional
+        Proportion of the figure size devoted to the two marginal elements. If
+        a pair is given, they correspond to (row, col) ratios.
+    cbar_pos : tuple of (left, bottom, width, height), optional
+        Position of the colorbar axes in the figure. Setting to ``None`` will
+        disable the colorbar.
+    tree_kws : dict, optional
+        Parameters for the :class:`matplotlib.collections.LineCollection`
+        that is used to plot the lines of the dendrogram tree.
+    kwargs : other keyword arguments
+        All other keyword arguments are passed to :func:`heatmap`.
+
+    Returns
+    -------
+    :class:`ClusterGrid`
+        A :class:`ClusterGrid` instance.
+
+    See Also
+    --------
+    heatmap : Plot rectangular data as a color-encoded matrix.
+
+    Notes
+    -----
+    The returned object has a ``savefig`` method that should be used if you
+    want to save the figure object without clipping the dendrograms.
+
+    To access the reordered row indices, use:
+    ``clustergrid.dendrogram_row.reordered_ind``
+
+    Column indices, use:
+    ``clustergrid.dendrogram_col.reordered_ind``
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/clustermap.rst
+
+    """
+    if _no_scipy:
+        raise RuntimeError("clustermap requires scipy to be available")
+
+    plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize,
+                          row_colors=row_colors, col_colors=col_colors,
+                          z_score=z_score, standard_scale=standard_scale,
+                          mask=mask, dendrogram_ratio=dendrogram_ratio,
+                          colors_ratio=colors_ratio, cbar_pos=cbar_pos)
+
+    return plotter.plot(metric=metric, method=method,
+                        colorbar_kws=cbar_kws,
+                        row_cluster=row_cluster, col_cluster=col_cluster,
+                        row_linkage=row_linkage, col_linkage=col_linkage,
+                        tree_kws=tree_kws, **kwargs)
diff --git a/testbed/mwaskom__seaborn/seaborn/miscplot.py b/testbed/mwaskom__seaborn/seaborn/miscplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..717c0ac40b07dafb60a1216be6f239f59b3ed524
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/miscplot.py
@@ -0,0 +1,48 @@
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+import matplotlib.ticker as ticker
+
+__all__ = ["palplot", "dogplot"]
+
+
+def palplot(pal, size=1):
+    """Plot the values in a color palette as a horizontal array.
+
+    Parameters
+    ----------
+    pal : sequence of matplotlib colors
+        colors, i.e. as returned by seaborn.color_palette()
+    size :
+        scaling factor for size of plot
+
+    """
+    n = len(pal)
+    f, ax = plt.subplots(1, 1, figsize=(n * size, size))
+    ax.imshow(np.arange(n).reshape(1, n),
+              cmap=mpl.colors.ListedColormap(list(pal)),
+              interpolation="nearest", aspect="auto")
+    ax.set_xticks(np.arange(n) - .5)
+    ax.set_yticks([-.5, .5])
+    # Ensure nice border between colors
+    ax.set_xticklabels(["" for _ in range(n)])
+    # The proper way to set no ticks
+    ax.yaxis.set_major_locator(ticker.NullLocator())
+
+
+def dogplot(*_, **__):
+    """Who's a good boy?"""
+    try:
+        from urllib.request import urlopen
+    except ImportError:
+        from urllib2 import urlopen
+    from io import BytesIO
+
+    url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png"
+    pic = np.random.randint(2, 7)
+    data = BytesIO(urlopen(url.format(pic)).read())
+    img = plt.imread(data)
+    f, ax = plt.subplots(figsize=(5, 5), dpi=100)
+    f.subplots_adjust(0, 0, 1, 1)
+    ax.imshow(img)
+    ax.set_axis_off()
diff --git a/testbed/mwaskom__seaborn/seaborn/objects.py b/testbed/mwaskom__seaborn/seaborn/objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..123e57f0a936e8e73c684dd647b9813da86a3f60
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/objects.py
@@ -0,0 +1,49 @@
+"""
+A declarative, object-oriented interface for creating statistical graphics.
+
+The seaborn.objects namespace contains a number of classes that can be composed
+together to build a customized visualization.
+
+The main object is :class:`Plot`, which is the starting point for all figures.
+Pass :class:`Plot` a dataset and specify assignments from its variables to
+roles in the plot. Build up the visualization by calling its methods.
+
+There are four other general types of objects in this interface:
+
+- :class:`Mark` subclasses, which create matplotlib artists for visualization
+- :class:`Stat` subclasses, which apply statistical transforms before plotting
+- :class:`Move` subclasses, which make further adjustments to reduce overplotting
+
+These classes are passed to :meth:`Plot.add` to define a layer in the plot.
+Each layer has a :class:`Mark` and optional :class:`Stat` and/or :class:`Move`.
+Plots can have multiple layers.
+
+The other general type of object is a :class:`Scale` subclass, which provide an
+interface for controlling the mappings between data values and visual properties.
+Pass :class:`Scale` objects to :meth:`Plot.scale`.
+
+See the documentation for other :class:`Plot` methods to learn about the many
+ways that a plot can be enhanced and customized.
+
+"""
+from seaborn._core.plot import Plot  # noqa: F401
+
+from seaborn._marks.base import Mark  # noqa: F401
+from seaborn._marks.area import Area, Band  # noqa: F401
+from seaborn._marks.bar import Bar, Bars  # noqa: F401
+from seaborn._marks.dot import Dot, Dots  # noqa: F401
+from seaborn._marks.line import Dash, Line, Lines, Path, Paths, Range  # noqa: F401
+from seaborn._marks.text import Text  # noqa: F401
+
+from seaborn._stats.base import Stat  # noqa: F401
+from seaborn._stats.aggregation import Agg, Est  # noqa: F401
+from seaborn._stats.counting import Count, Hist  # noqa: F401
+from seaborn._stats.density import KDE  # noqa: F401
+from seaborn._stats.order import Perc  # noqa: F401
+from seaborn._stats.regression import PolyFit  # noqa: F401
+
+from seaborn._core.moves import Dodge, Jitter, Norm, Shift, Stack, Move  # noqa: F401
+
+from seaborn._core.scales import (  # noqa: F401
+    Boolean, Continuous, Nominal, Temporal, Scale
+)
diff --git a/testbed/mwaskom__seaborn/seaborn/palettes.py b/testbed/mwaskom__seaborn/seaborn/palettes.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1214b2a0f8d22339c0acaa05aea6af27a2e080c
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/palettes.py
@@ -0,0 +1,842 @@
+import colorsys
+from itertools import cycle
+
+import numpy as np
+import matplotlib as mpl
+
+from .external import husl
+
+from .utils import desaturate, get_color_cycle
+from .colors import xkcd_rgb, crayons
+from ._compat import get_colormap
+
+
+__all__ = ["color_palette", "hls_palette", "husl_palette", "mpl_palette",
+           "dark_palette", "light_palette", "diverging_palette",
+           "blend_palette", "xkcd_palette", "crayon_palette",
+           "cubehelix_palette", "set_color_codes"]
+
+
+SEABORN_PALETTES = dict(
+    deep=["#4C72B0", "#DD8452", "#55A868", "#C44E52", "#8172B3",
+          "#937860", "#DA8BC3", "#8C8C8C", "#CCB974", "#64B5CD"],
+    deep6=["#4C72B0", "#55A868", "#C44E52",
+           "#8172B3", "#CCB974", "#64B5CD"],
+    muted=["#4878D0", "#EE854A", "#6ACC64", "#D65F5F", "#956CB4",
+           "#8C613C", "#DC7EC0", "#797979", "#D5BB67", "#82C6E2"],
+    muted6=["#4878D0", "#6ACC64", "#D65F5F",
+            "#956CB4", "#D5BB67", "#82C6E2"],
+    pastel=["#A1C9F4", "#FFB482", "#8DE5A1", "#FF9F9B", "#D0BBFF",
+            "#DEBB9B", "#FAB0E4", "#CFCFCF", "#FFFEA3", "#B9F2F0"],
+    pastel6=["#A1C9F4", "#8DE5A1", "#FF9F9B",
+             "#D0BBFF", "#FFFEA3", "#B9F2F0"],
+    bright=["#023EFF", "#FF7C00", "#1AC938", "#E8000B", "#8B2BE2",
+            "#9F4800", "#F14CC1", "#A3A3A3", "#FFC400", "#00D7FF"],
+    bright6=["#023EFF", "#1AC938", "#E8000B",
+             "#8B2BE2", "#FFC400", "#00D7FF"],
+    dark=["#001C7F", "#B1400D", "#12711C", "#8C0800", "#591E71",
+          "#592F0D", "#A23582", "#3C3C3C", "#B8850A", "#006374"],
+    dark6=["#001C7F", "#12711C", "#8C0800",
+           "#591E71", "#B8850A", "#006374"],
+    colorblind=["#0173B2", "#DE8F05", "#029E73", "#D55E00", "#CC78BC",
+                "#CA9161", "#FBAFE4", "#949494", "#ECE133", "#56B4E9"],
+    colorblind6=["#0173B2", "#029E73", "#D55E00",
+                 "#CC78BC", "#ECE133", "#56B4E9"]
+)
+
+
+MPL_QUAL_PALS = {
+    "tab10": 10, "tab20": 20, "tab20b": 20, "tab20c": 20,
+    "Set1": 9, "Set2": 8, "Set3": 12,
+    "Accent": 8, "Paired": 12,
+    "Pastel1": 9, "Pastel2": 8, "Dark2": 8,
+}
+
+
+QUAL_PALETTE_SIZES = MPL_QUAL_PALS.copy()
+QUAL_PALETTE_SIZES.update({k: len(v) for k, v in SEABORN_PALETTES.items()})
+QUAL_PALETTES = list(QUAL_PALETTE_SIZES.keys())
+
+
+class _ColorPalette(list):
+    """Set the color palette in a with statement, otherwise be a list."""
+    def __enter__(self):
+        """Open the context."""
+        from .rcmod import set_palette
+        self._orig_palette = color_palette()
+        set_palette(self)
+        return self
+
+    def __exit__(self, *args):
+        """Close the context."""
+        from .rcmod import set_palette
+        set_palette(self._orig_palette)
+
+    def as_hex(self):
+        """Return a color palette with hex codes instead of RGB values."""
+        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
+        return _ColorPalette(hex)
+
+    def _repr_html_(self):
+        """Rich display of the color palette in an HTML frontend."""
+        s = 55
+        n = len(self)
+        html = f''
+        for i, c in enumerate(self.as_hex()):
+            html += (
+                f''
+            )
+        html += ''
+        return html
+
+
+def _patch_colormap_display():
+    """Simplify the rich display of matplotlib color maps in a notebook."""
+    def _repr_png_(self):
+        """Generate a PNG representation of the Colormap."""
+        import io
+        from PIL import Image
+        import numpy as np
+        IMAGE_SIZE = (400, 50)
+        X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))
+        pixels = self(X, bytes=True)
+        png_bytes = io.BytesIO()
+        Image.fromarray(pixels).save(png_bytes, format='png')
+        return png_bytes.getvalue()
+
+    def _repr_html_(self):
+        """Generate an HTML representation of the Colormap."""
+        import base64
+        png_bytes = self._repr_png_()
+        png_base64 = base64.b64encode(png_bytes).decode('ascii')
+        return ('')
+
+    mpl.colors.Colormap._repr_png_ = _repr_png_
+    mpl.colors.Colormap._repr_html_ = _repr_html_
+
+
+def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False):
+    """Return a list of colors or continuous colormap defining a palette.
+
+    Possible ``palette`` values include:
+        - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)
+        - Name of matplotlib colormap
+        - 'husl' or 'hls'
+        - 'ch:'
+        - 'light:', 'dark:', 'blend:,',
+        - A sequence of colors in any format matplotlib accepts
+
+    Calling this function with ``palette=None`` will return the current
+    matplotlib color cycle.
+
+    This function can also be used in a ``with`` statement to temporarily
+    set the color cycle for a plot or set of plots.
+
+    See the :ref:`tutorial ` for more information.
+
+    Parameters
+    ----------
+    palette : None, string, or sequence, optional
+        Name of palette or None to return current palette. If a sequence, input
+        colors are used but possibly cycled and desaturated.
+    n_colors : int, optional
+        Number of colors in the palette. If ``None``, the default will depend
+        on how ``palette`` is specified. Named palettes default to 6 colors,
+        but grabbing the current palette or passing in a list of colors will
+        not change the number of colors unless this is specified. Asking for
+        more colors than exist in the palette will cause it to cycle. Ignored
+        when ``as_cmap`` is True.
+    desat : float, optional
+        Proportion to desaturate each color by.
+    as_cmap : bool
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+
+    Returns
+    -------
+    list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    set_palette : Set the default color cycle for all plots.
+    set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
+                      colors from one of the seaborn palettes.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/color_palette.rst
+
+    """
+    if palette is None:
+        palette = get_color_cycle()
+        if n_colors is None:
+            n_colors = len(palette)
+
+    elif not isinstance(palette, str):
+        palette = palette
+        if n_colors is None:
+            n_colors = len(palette)
+    else:
+
+        if n_colors is None:
+            # Use all colors in a qualitative palette or 6 of another kind
+            n_colors = QUAL_PALETTE_SIZES.get(palette, 6)
+
+        if palette in SEABORN_PALETTES:
+            # Named "seaborn variant" of matplotlib default color cycle
+            palette = SEABORN_PALETTES[palette]
+
+        elif palette == "hls":
+            # Evenly spaced colors in cylindrical RGB space
+            palette = hls_palette(n_colors, as_cmap=as_cmap)
+
+        elif palette == "husl":
+            # Evenly spaced colors in cylindrical Lab space
+            palette = husl_palette(n_colors, as_cmap=as_cmap)
+
+        elif palette.lower() == "jet":
+            # Paternalism
+            raise ValueError("No.")
+
+        elif palette.startswith("ch:"):
+            # Cubehelix palette with params specified in string
+            args, kwargs = _parse_cubehelix_args(palette)
+            palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap)
+
+        elif palette.startswith("light:"):
+            # light palette to color specified in string
+            _, color = palette.split(":")
+            reverse = color.endswith("_r")
+            if reverse:
+                color = color[:-2]
+            palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
+
+        elif palette.startswith("dark:"):
+            # light palette to color specified in string
+            _, color = palette.split(":")
+            reverse = color.endswith("_r")
+            if reverse:
+                color = color[:-2]
+            palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
+
+        elif palette.startswith("blend:"):
+            # blend palette between colors specified in string
+            _, colors = palette.split(":")
+            colors = colors.split(",")
+            palette = blend_palette(colors, n_colors, as_cmap=as_cmap)
+
+        else:
+            try:
+                # Perhaps a named matplotlib colormap?
+                palette = mpl_palette(palette, n_colors, as_cmap=as_cmap)
+            except (ValueError, KeyError):  # Error class changed in mpl36
+                raise ValueError(f"{palette!r} is not a valid palette name")
+
+    if desat is not None:
+        palette = [desaturate(c, desat) for c in palette]
+
+    if not as_cmap:
+
+        # Always return as many colors as we asked for
+        pal_cycle = cycle(palette)
+        palette = [next(pal_cycle) for _ in range(n_colors)]
+
+        # Always return in r, g, b tuple format
+        try:
+            palette = map(mpl.colors.colorConverter.to_rgb, palette)
+            palette = _ColorPalette(palette)
+        except ValueError:
+            raise ValueError(f"Could not generate a palette for {palette}")
+
+    return palette
+
+
+def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False):  # noqa
+    """
+    Return hues with constant lightness and saturation in the HLS system.
+
+    The hues are evenly sampled along a circular path. The resulting palette will be
+    appropriate for categorical or cyclical data.
+
+    The `h`, `l`, and `s` values should be between 0 and 1.
+
+    .. note::
+        While the separation of the resulting colors will be mathematically
+        constant, the HLS system does not construct a perceptually-uniform space,
+        so their apparent intensity will vary.
+
+    Parameters
+    ----------
+    n_colors : int
+        Number of colors in the palette.
+    h : float
+        The value of the first hue.
+    l : float
+        The lightness value.
+    s : float
+        The saturation intensity.
+    as_cmap : bool
+        If True, return a matplotlib colormap object.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    husl_palette : Make a palette using evenly spaced hues in the HUSL system.
+
+    Examples
+    --------
+    .. include:: ../docstrings/hls_palette.rst
+
+    """
+    if as_cmap:
+        n_colors = 256
+    hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]
+    hues += h
+    hues %= 1
+    hues -= hues.astype(int)
+    palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]
+    if as_cmap:
+        return mpl.colors.ListedColormap(palette, "hls")
+    else:
+        return _ColorPalette(palette)
+
+
+def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False):  # noqa
+    """
+    Return hues with constant lightness and saturation in the HUSL system.
+
+    The hues are evenly sampled along a circular path. The resulting palette will be
+    appropriate for categorical or cyclical data.
+
+    The `h`, `l`, and `s` values should be between 0 and 1.
+
+    This function is similar to :func:`hls_palette`, but it uses a nonlinear color
+    space that is more perceptually uniform.
+
+    Parameters
+    ----------
+    n_colors : int
+        Number of colors in the palette.
+    h : float
+        The value of the first hue.
+    l : float
+        The lightness value.
+    s : float
+        The saturation intensity.
+    as_cmap : bool
+        If True, return a matplotlib colormap object.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    hls_palette : Make a palette using evenly spaced hues in the HSL system.
+
+    Examples
+    --------
+    .. include:: ../docstrings/husl_palette.rst
+
+    """
+    if as_cmap:
+        n_colors = 256
+    hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]
+    hues += h
+    hues %= 1
+    hues *= 359
+    s *= 99
+    l *= 99  # noqa
+    palette = [_color_to_rgb((h_i, s, l), input="husl") for h_i in hues]
+    if as_cmap:
+        return mpl.colors.ListedColormap(palette, "hsl")
+    else:
+        return _ColorPalette(palette)
+
+
+def mpl_palette(name, n_colors=6, as_cmap=False):
+    """
+    Return a palette or colormap from the matplotlib registry.
+
+    For continuous palettes, evenly-spaced discrete samples are chosen while
+    excluding the minimum and maximum value in the colormap to provide better
+    contrast at the extremes.
+
+    For qualitative palettes (e.g. those from colorbrewer), exact values are
+    indexed (rather than interpolated), but fewer than `n_colors` can be returned
+    if the palette does not define that many.
+
+    Parameters
+    ----------
+    name : string
+        Name of the palette. This should be a named matplotlib colormap.
+    n_colors : int
+        Number of discrete colors in the palette.
+
+    Returns
+    -------
+    list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    Examples
+    --------
+    .. include: ../docstrings/mpl_palette.rst
+
+    """
+    if name.endswith("_d"):
+        sub_name = name[:-2]
+        if sub_name.endswith("_r"):
+            reverse = True
+            sub_name = sub_name[:-2]
+        else:
+            reverse = False
+        pal = color_palette(sub_name, 2) + ["#333333"]
+        if reverse:
+            pal = pal[::-1]
+        cmap = blend_palette(pal, n_colors, as_cmap=True)
+    else:
+        cmap = get_colormap(name)
+
+    if name in MPL_QUAL_PALS:
+        bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors]
+    else:
+        bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1]
+    palette = list(map(tuple, cmap(bins)[:, :3]))
+
+    if as_cmap:
+        return cmap
+    else:
+        return _ColorPalette(palette)
+
+
+def _color_to_rgb(color, input):
+    """Add some more flexibility to color choices."""
+    if input == "hls":
+        color = colorsys.hls_to_rgb(*color)
+    elif input == "husl":
+        color = husl.husl_to_rgb(*color)
+        color = tuple(np.clip(color, 0, 1))
+    elif input == "xkcd":
+        color = xkcd_rgb[color]
+
+    return mpl.colors.to_rgb(color)
+
+
+def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
+    """Make a sequential palette that blends from dark to ``color``.
+
+    This kind of palette is good for data that range between relatively
+    uninteresting low values and interesting high values.
+
+    The ``color`` parameter can be specified in a number of ways, including
+    all options for defining a color in matplotlib and several additional
+    color spaces that are handled by seaborn. You can also use the database
+    of named colors from the XKCD color survey.
+
+    If you are using the IPython notebook, you can also choose this palette
+    interactively with the :func:`choose_dark_palette` function.
+
+    Parameters
+    ----------
+    color : base color for high values
+        hex, rgb-tuple, or html color name
+    n_colors : int, optional
+        number of colors in the palette
+    reverse : bool, optional
+        if True, reverse the direction of the blend
+    as_cmap : bool, optional
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+    input : {'rgb', 'hls', 'husl', xkcd'}
+        Color space to interpret the input color. The first three options
+        apply to tuple inputs and the latter applies to string inputs.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    light_palette : Create a sequential palette with bright low values.
+    diverging_palette : Create a diverging palette with two colors.
+
+    Examples
+    --------
+    .. include:: ../docstrings/dark_palette.rst
+
+    """
+    rgb = _color_to_rgb(color, input)
+    h, s, l = husl.rgb_to_husl(*rgb)
+    gray_s, gray_l = .15 * s, 15
+    gray = _color_to_rgb((h, gray_s, gray_l), input="husl")
+    colors = [rgb, gray] if reverse else [gray, rgb]
+    return blend_palette(colors, n_colors, as_cmap)
+
+
+def light_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
+    """Make a sequential palette that blends from light to ``color``.
+
+    The ``color`` parameter can be specified in a number of ways, including
+    all options for defining a color in matplotlib and several additional
+    color spaces that are handled by seaborn. You can also use the database
+    of named colors from the XKCD color survey.
+
+    If you are using a Jupyter notebook, you can also choose this palette
+    interactively with the :func:`choose_light_palette` function.
+
+    Parameters
+    ----------
+    color : base color for high values
+        hex code, html color name, or tuple in `input` space.
+    n_colors : int, optional
+        number of colors in the palette
+    reverse : bool, optional
+        if True, reverse the direction of the blend
+    as_cmap : bool, optional
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+    input : {'rgb', 'hls', 'husl', xkcd'}
+        Color space to interpret the input color. The first three options
+        apply to tuple inputs and the latter applies to string inputs.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    dark_palette : Create a sequential palette with dark low values.
+    diverging_palette : Create a diverging palette with two colors.
+
+    Examples
+    --------
+    .. include:: ../docstrings/light_palette.rst
+
+    """
+    rgb = _color_to_rgb(color, input)
+    h, s, l = husl.rgb_to_husl(*rgb)
+    gray_s, gray_l = .15 * s, 95
+    gray = _color_to_rgb((h, gray_s, gray_l), input="husl")
+    colors = [rgb, gray] if reverse else [gray, rgb]
+    return blend_palette(colors, n_colors, as_cmap)
+
+
+def diverging_palette(h_neg, h_pos, s=75, l=50, sep=1, n=6,  # noqa
+                      center="light", as_cmap=False):
+    """Make a diverging palette between two HUSL colors.
+
+    If you are using the IPython notebook, you can also choose this palette
+    interactively with the :func:`choose_diverging_palette` function.
+
+    Parameters
+    ----------
+    h_neg, h_pos : float in [0, 359]
+        Anchor hues for negative and positive extents of the map.
+    s : float in [0, 100], optional
+        Anchor saturation for both extents of the map.
+    l : float in [0, 100], optional
+        Anchor lightness for both extents of the map.
+    sep : int, optional
+        Size of the intermediate region.
+    n : int, optional
+        Number of colors in the palette (if not returning a cmap)
+    center : {"light", "dark"}, optional
+        Whether the center of the palette is light or dark
+    as_cmap : bool, optional
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    dark_palette : Create a sequential palette with dark values.
+    light_palette : Create a sequential palette with light values.
+
+    Examples
+    --------
+    .. include: ../docstrings/diverging_palette.rst
+
+    """
+    palfunc = dict(dark=dark_palette, light=light_palette)[center]
+    n_half = int(128 - (sep // 2))
+    neg = palfunc((h_neg, s, l), n_half, reverse=True, input="husl")
+    pos = palfunc((h_pos, s, l), n_half, input="husl")
+    midpoint = dict(light=[(.95, .95, .95)], dark=[(.133, .133, .133)])[center]
+    mid = midpoint * sep
+    pal = blend_palette(np.concatenate([neg, mid, pos]), n, as_cmap=as_cmap)
+    return pal
+
+
+def blend_palette(colors, n_colors=6, as_cmap=False, input="rgb"):
+    """Make a palette that blends between a list of colors.
+
+    Parameters
+    ----------
+    colors : sequence of colors in various formats interpreted by `input`
+        hex code, html color name, or tuple in `input` space.
+    n_colors : int, optional
+        Number of colors in the palette.
+    as_cmap : bool, optional
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    Examples
+    --------
+    .. include: ../docstrings/blend_palette.rst
+
+    """
+    colors = [_color_to_rgb(color, input) for color in colors]
+    name = "blend"
+    pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)
+    if not as_cmap:
+        rgb_array = pal(np.linspace(0, 1, int(n_colors)))[:, :3]  # no alpha
+        pal = _ColorPalette(map(tuple, rgb_array))
+    return pal
+
+
+def xkcd_palette(colors):
+    """Make a palette with color names from the xkcd color survey.
+
+    See xkcd for the full list of colors: https://xkcd.com/color/rgb/
+
+    This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.
+
+    Parameters
+    ----------
+    colors : list of strings
+        List of keys in the `seaborn.xkcd_rgb` dictionary.
+
+    Returns
+    -------
+    palette
+        A list of colors as RGB tuples.
+
+    See Also
+    --------
+    crayon_palette : Make a palette with Crayola crayon colors.
+
+    """
+    palette = [xkcd_rgb[name] for name in colors]
+    return color_palette(palette, len(palette))
+
+
+def crayon_palette(colors):
+    """Make a palette with color names from Crayola crayons.
+
+    Colors are taken from here:
+    https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
+
+    This is just a simple wrapper around the `seaborn.crayons` dictionary.
+
+    Parameters
+    ----------
+    colors : list of strings
+        List of keys in the `seaborn.crayons` dictionary.
+
+    Returns
+    -------
+    palette
+        A list of colors as RGB tuples.
+
+    See Also
+    --------
+    xkcd_palette : Make a palette with named colors from the XKCD color survey.
+
+    """
+    palette = [crayons[name] for name in colors]
+    return color_palette(palette, len(palette))
+
+
+def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,
+                      light=.85, dark=.15, reverse=False, as_cmap=False):
+    """Make a sequential palette from the cubehelix system.
+
+    This produces a colormap with linearly-decreasing (or increasing)
+    brightness. That means that information will be preserved if printed to
+    black and white or viewed by someone who is colorblind.  "cubehelix" is
+    also available as a matplotlib-based palette, but this function gives the
+    user more control over the look of the palette and has a different set of
+    defaults.
+
+    In addition to using this function, it is also possible to generate a
+    cubehelix palette generally in seaborn using a string starting with
+    `ch:` and containing other parameters (e.g. `"ch:s=.25,r=-.5"`).
+
+    Parameters
+    ----------
+    n_colors : int
+        Number of colors in the palette.
+    start : float, 0 <= start <= 3
+        The hue value at the start of the helix.
+    rot : float
+        Rotations around the hue wheel over the range of the palette.
+    gamma : float 0 <= gamma
+        Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.
+    hue : float, 0 <= hue <= 1
+        Saturation of the colors.
+    dark : float 0 <= dark <= 1
+        Intensity of the darkest color in the palette.
+    light : float 0 <= light <= 1
+        Intensity of the lightest color in the palette.
+    reverse : bool
+        If True, the palette will go from dark to light.
+    as_cmap : bool
+        If True, return a :class:`matplotlib.colors.ListedColormap`.
+
+    Returns
+    -------
+    palette
+        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
+
+    See Also
+    --------
+    choose_cubehelix_palette : Launch an interactive widget to select cubehelix
+                               palette parameters.
+    dark_palette : Create a sequential palette with dark low values.
+    light_palette : Create a sequential palette with bright low values.
+
+    References
+    ----------
+    Green, D. A. (2011). "A colour scheme for the display of astronomical
+    intensity images". Bulletin of the Astromical Society of India, Vol. 39,
+    p. 289-295.
+
+    Examples
+    --------
+    .. include:: ../docstrings/cubehelix_palette.rst
+
+    """
+    def get_color_function(p0, p1):
+        # Copied from matplotlib because it lives in private module
+        def color(x):
+            # Apply gamma factor to emphasise low or high intensity values
+            xg = x ** gamma
+
+            # Calculate amplitude and angle of deviation from the black
+            # to white diagonal in the plane of constant
+            # perceived intensity.
+            a = hue * xg * (1 - xg) / 2
+
+            phi = 2 * np.pi * (start / 3 + rot * x)
+
+            return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
+        return color
+
+    cdict = {
+        "red": get_color_function(-0.14861, 1.78277),
+        "green": get_color_function(-0.29227, -0.90649),
+        "blue": get_color_function(1.97294, 0.0),
+    }
+
+    cmap = mpl.colors.LinearSegmentedColormap("cubehelix", cdict)
+
+    x = np.linspace(light, dark, int(n_colors))
+    pal = cmap(x)[:, :3].tolist()
+    if reverse:
+        pal = pal[::-1]
+
+    if as_cmap:
+        x_256 = np.linspace(light, dark, 256)
+        if reverse:
+            x_256 = x_256[::-1]
+        pal_256 = cmap(x_256)
+        cmap = mpl.colors.ListedColormap(pal_256, "seaborn_cubehelix")
+        return cmap
+    else:
+        return _ColorPalette(pal)
+
+
+def _parse_cubehelix_args(argstr):
+    """Turn stringified cubehelix params into args/kwargs."""
+
+    if argstr.startswith("ch:"):
+        argstr = argstr[3:]
+
+    if argstr.endswith("_r"):
+        reverse = True
+        argstr = argstr[:-2]
+    else:
+        reverse = False
+
+    if not argstr:
+        return [], {"reverse": reverse}
+
+    all_args = argstr.split(",")
+
+    args = [float(a.strip(" ")) for a in all_args if "=" not in a]
+
+    kwargs = [a.split("=") for a in all_args if "=" in a]
+    kwargs = {k.strip(" "): float(v.strip(" ")) for k, v in kwargs}
+
+    kwarg_map = dict(
+        s="start", r="rot", g="gamma",
+        h="hue", l="light", d="dark",  # noqa: E741
+    )
+
+    kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()}
+
+    if reverse:
+        kwargs["reverse"] = True
+
+    return args, kwargs
+
+
+def set_color_codes(palette="deep"):
+    """Change how matplotlib color shorthands are interpreted.
+
+    Calling this will change how shorthand codes like "b" or "g"
+    are interpreted by matplotlib in subsequent plots.
+
+    Parameters
+    ----------
+    palette : {deep, muted, pastel, dark, bright, colorblind}
+        Named seaborn palette to use as the source of colors.
+
+    See Also
+    --------
+    set : Color codes can be set through the high-level seaborn style
+          manager.
+    set_palette : Color codes can also be set through the function that
+                  sets the matplotlib color cycle.
+
+    """
+    if palette == "reset":
+        colors = [
+            (0., 0., 1.),
+            (0., .5, 0.),
+            (1., 0., 0.),
+            (.75, 0., .75),
+            (.75, .75, 0.),
+            (0., .75, .75),
+            (0., 0., 0.)
+        ]
+    elif not isinstance(palette, str):
+        err = "set_color_codes requires a named seaborn palette"
+        raise TypeError(err)
+    elif palette in SEABORN_PALETTES:
+        if not palette.endswith("6"):
+            palette = palette + "6"
+        colors = SEABORN_PALETTES[palette] + [(.1, .1, .1)]
+    else:
+        err = f"Cannot set colors with palette '{palette}'"
+        raise ValueError(err)
+
+    for code, color in zip("bgrmyck", colors):
+        rgb = mpl.colors.colorConverter.to_rgb(color)
+        mpl.colors.colorConverter.colors[code] = rgb
+        mpl.colors.colorConverter.cache[code] = rgb
diff --git a/testbed/mwaskom__seaborn/seaborn/rcmod.py b/testbed/mwaskom__seaborn/seaborn/rcmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca70a44695b4f7573df1e23bec2b0be8bd8b5905
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/rcmod.py
@@ -0,0 +1,534 @@
+"""Control plot style and scaling using the matplotlib rcParams interface."""
+import functools
+import matplotlib as mpl
+from cycler import cycler
+from . import palettes
+
+
+__all__ = ["set_theme", "set", "reset_defaults", "reset_orig",
+           "axes_style", "set_style", "plotting_context", "set_context",
+           "set_palette"]
+
+
+_style_keys = [
+
+    "axes.facecolor",
+    "axes.edgecolor",
+    "axes.grid",
+    "axes.axisbelow",
+    "axes.labelcolor",
+
+    "figure.facecolor",
+
+    "grid.color",
+    "grid.linestyle",
+
+    "text.color",
+
+    "xtick.color",
+    "ytick.color",
+    "xtick.direction",
+    "ytick.direction",
+    "lines.solid_capstyle",
+
+    "patch.edgecolor",
+    "patch.force_edgecolor",
+
+    "image.cmap",
+    "font.family",
+    "font.sans-serif",
+
+    "xtick.bottom",
+    "xtick.top",
+    "ytick.left",
+    "ytick.right",
+
+    "axes.spines.left",
+    "axes.spines.bottom",
+    "axes.spines.right",
+    "axes.spines.top",
+
+]
+
+_context_keys = [
+
+    "font.size",
+    "axes.labelsize",
+    "axes.titlesize",
+    "xtick.labelsize",
+    "ytick.labelsize",
+    "legend.fontsize",
+    "legend.title_fontsize",
+
+    "axes.linewidth",
+    "grid.linewidth",
+    "lines.linewidth",
+    "lines.markersize",
+    "patch.linewidth",
+
+    "xtick.major.width",
+    "ytick.major.width",
+    "xtick.minor.width",
+    "ytick.minor.width",
+
+    "xtick.major.size",
+    "ytick.major.size",
+    "xtick.minor.size",
+    "ytick.minor.size",
+
+]
+
+
+def set_theme(context="notebook", style="darkgrid", palette="deep",
+              font="sans-serif", font_scale=1, color_codes=True, rc=None):
+    """
+    Set aspects of the visual theme for all matplotlib and seaborn plots.
+
+    This function changes the global defaults for all plots using the
+    matplotlib rcParams system. The themeing is decomposed into several distinct
+    sets of parameter values.
+
+    The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`
+    and :doc:`color palette <../tutorial/color_palettes>` tutorials.
+
+    Parameters
+    ----------
+    context : string or dict
+        Scaling parameters, see :func:`plotting_context`.
+    style : string or dict
+        Axes style parameters, see :func:`axes_style`.
+    palette : string or sequence
+        Color palette, see :func:`color_palette`.
+    font : string
+        Font family, see matplotlib font manager.
+    font_scale : float, optional
+        Separate scaling factor to independently scale the size of the
+        font elements.
+    color_codes : bool
+        If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
+        color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
+    rc : dict or None
+        Dictionary of rc parameter mappings to override the above.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/set_theme.rst
+
+    """
+    set_context(context, font_scale)
+    set_style(style, rc={"font.family": font})
+    set_palette(palette, color_codes=color_codes)
+    if rc is not None:
+        mpl.rcParams.update(rc)
+
+
+def set(*args, **kwargs):
+    """
+    Alias for :func:`set_theme`, which is the preferred interface.
+
+    This function may be removed in the future.
+    """
+    set_theme(*args, **kwargs)
+
+
+def reset_defaults():
+    """Restore all RC params to default settings."""
+    mpl.rcParams.update(mpl.rcParamsDefault)
+
+
+def reset_orig():
+    """Restore all RC params to original settings (respects custom rc)."""
+    from . import _orig_rc_params
+    mpl.rcParams.update(_orig_rc_params)
+
+
+def axes_style(style=None, rc=None):
+    """
+    Get the parameters that control the general style of the plots.
+
+    The style parameters control properties like the color of the background and
+    whether a grid is enabled by default. This is accomplished using the
+    matplotlib rcParams system.
+
+    The options are illustrated in the
+    :doc:`aesthetics tutorial <../tutorial/aesthetics>`.
+
+    This function can also be used as a context manager to temporarily
+    alter the global defaults. See :func:`set_theme` or :func:`set_style`
+    to modify the global defaults for all plots.
+
+    Parameters
+    ----------
+    style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}
+        A dictionary of parameters or the name of a preconfigured style.
+    rc : dict, optional
+        Parameter mappings to override the values in the preset seaborn
+        style dictionaries. This only updates parameters that are
+        considered part of the style definition.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/axes_style.rst
+
+    """
+    if style is None:
+        style_dict = {k: mpl.rcParams[k] for k in _style_keys}
+
+    elif isinstance(style, dict):
+        style_dict = style
+
+    else:
+        styles = ["white", "dark", "whitegrid", "darkgrid", "ticks"]
+        if style not in styles:
+            raise ValueError(f"style must be one of {', '.join(styles)}")
+
+        # Define colors here
+        dark_gray = ".15"
+        light_gray = ".8"
+
+        # Common parameters
+        style_dict = {
+
+            "figure.facecolor": "white",
+            "axes.labelcolor": dark_gray,
+
+            "xtick.direction": "out",
+            "ytick.direction": "out",
+            "xtick.color": dark_gray,
+            "ytick.color": dark_gray,
+
+            "axes.axisbelow": True,
+            "grid.linestyle": "-",
+
+
+            "text.color": dark_gray,
+            "font.family": ["sans-serif"],
+            "font.sans-serif": ["Arial", "DejaVu Sans", "Liberation Sans",
+                                "Bitstream Vera Sans", "sans-serif"],
+
+
+            "lines.solid_capstyle": "round",
+            "patch.edgecolor": "w",
+            "patch.force_edgecolor": True,
+
+            "image.cmap": "rocket",
+
+            "xtick.top": False,
+            "ytick.right": False,
+
+        }
+
+        # Set grid on or off
+        if "grid" in style:
+            style_dict.update({
+                "axes.grid": True,
+            })
+        else:
+            style_dict.update({
+                "axes.grid": False,
+            })
+
+        # Set the color of the background, spines, and grids
+        if style.startswith("dark"):
+            style_dict.update({
+
+                "axes.facecolor": "#EAEAF2",
+                "axes.edgecolor": "white",
+                "grid.color": "white",
+
+                "axes.spines.left": True,
+                "axes.spines.bottom": True,
+                "axes.spines.right": True,
+                "axes.spines.top": True,
+
+            })
+
+        elif style == "whitegrid":
+            style_dict.update({
+
+                "axes.facecolor": "white",
+                "axes.edgecolor": light_gray,
+                "grid.color": light_gray,
+
+                "axes.spines.left": True,
+                "axes.spines.bottom": True,
+                "axes.spines.right": True,
+                "axes.spines.top": True,
+
+            })
+
+        elif style in ["white", "ticks"]:
+            style_dict.update({
+
+                "axes.facecolor": "white",
+                "axes.edgecolor": dark_gray,
+                "grid.color": light_gray,
+
+                "axes.spines.left": True,
+                "axes.spines.bottom": True,
+                "axes.spines.right": True,
+                "axes.spines.top": True,
+
+            })
+
+        # Show or hide the axes ticks
+        if style == "ticks":
+            style_dict.update({
+                "xtick.bottom": True,
+                "ytick.left": True,
+            })
+        else:
+            style_dict.update({
+                "xtick.bottom": False,
+                "ytick.left": False,
+            })
+
+    # Remove entries that are not defined in the base list of valid keys
+    # This lets us handle matplotlib <=/> 2.0
+    style_dict = {k: v for k, v in style_dict.items() if k in _style_keys}
+
+    # Override these settings with the provided rc dictionary
+    if rc is not None:
+        rc = {k: v for k, v in rc.items() if k in _style_keys}
+        style_dict.update(rc)
+
+    # Wrap in an _AxesStyle object so this can be used in a with statement
+    style_object = _AxesStyle(style_dict)
+
+    return style_object
+
+
+def set_style(style=None, rc=None):
+    """
+    Set the parameters that control the general style of the plots.
+
+    The style parameters control properties like the color of the background and
+    whether a grid is enabled by default. This is accomplished using the
+    matplotlib rcParams system.
+
+    The options are illustrated in the
+    :doc:`aesthetics tutorial <../tutorial/aesthetics>`.
+
+    See :func:`axes_style` to get the parameter values.
+
+    Parameters
+    ----------
+    style : dict, or one of {darkgrid, whitegrid, dark, white, ticks}
+        A dictionary of parameters or the name of a preconfigured style.
+    rc : dict, optional
+        Parameter mappings to override the values in the preset seaborn
+        style dictionaries. This only updates parameters that are
+        considered part of the style definition.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/set_style.rst
+
+    """
+    style_object = axes_style(style, rc)
+    mpl.rcParams.update(style_object)
+
+
+def plotting_context(context=None, font_scale=1, rc=None):
+    """
+    Get the parameters that control the scaling of plot elements.
+
+    This affects things like the size of the labels, lines, and other elements
+    of the plot, but not the overall style. This is accomplished using the
+    matplotlib rcParams system.
+
+    The base context is "notebook", and the other contexts are "paper", "talk",
+    and "poster", which are version of the notebook parameters scaled by different
+    values. Font elements can also be scaled independently of (but relative to)
+    the other values.
+
+    This function can also be used as a context manager to temporarily
+    alter the global defaults. See :func:`set_theme` or :func:`set_context`
+    to modify the global defaults for all plots.
+
+    Parameters
+    ----------
+    context : None, dict, or one of {paper, notebook, talk, poster}
+        A dictionary of parameters or the name of a preconfigured set.
+    font_scale : float, optional
+        Separate scaling factor to independently scale the size of the
+        font elements.
+    rc : dict, optional
+        Parameter mappings to override the values in the preset seaborn
+        context dictionaries. This only updates parameters that are
+        considered part of the context definition.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/plotting_context.rst
+
+    """
+    if context is None:
+        context_dict = {k: mpl.rcParams[k] for k in _context_keys}
+
+    elif isinstance(context, dict):
+        context_dict = context
+
+    else:
+
+        contexts = ["paper", "notebook", "talk", "poster"]
+        if context not in contexts:
+            raise ValueError(f"context must be in {', '.join(contexts)}")
+
+        # Set up dictionary of default parameters
+        texts_base_context = {
+
+            "font.size": 12,
+            "axes.labelsize": 12,
+            "axes.titlesize": 12,
+            "xtick.labelsize": 11,
+            "ytick.labelsize": 11,
+            "legend.fontsize": 11,
+            "legend.title_fontsize": 12,
+
+        }
+
+        base_context = {
+
+            "axes.linewidth": 1.25,
+            "grid.linewidth": 1,
+            "lines.linewidth": 1.5,
+            "lines.markersize": 6,
+            "patch.linewidth": 1,
+
+            "xtick.major.width": 1.25,
+            "ytick.major.width": 1.25,
+            "xtick.minor.width": 1,
+            "ytick.minor.width": 1,
+
+            "xtick.major.size": 6,
+            "ytick.major.size": 6,
+            "xtick.minor.size": 4,
+            "ytick.minor.size": 4,
+
+        }
+        base_context.update(texts_base_context)
+
+        # Scale all the parameters by the same factor depending on the context
+        scaling = dict(paper=.8, notebook=1, talk=1.5, poster=2)[context]
+        context_dict = {k: v * scaling for k, v in base_context.items()}
+
+        # Now independently scale the fonts
+        font_keys = texts_base_context.keys()
+        font_dict = {k: context_dict[k] * font_scale for k in font_keys}
+        context_dict.update(font_dict)
+
+    # Override these settings with the provided rc dictionary
+    if rc is not None:
+        rc = {k: v for k, v in rc.items() if k in _context_keys}
+        context_dict.update(rc)
+
+    # Wrap in a _PlottingContext object so this can be used in a with statement
+    context_object = _PlottingContext(context_dict)
+
+    return context_object
+
+
+def set_context(context=None, font_scale=1, rc=None):
+    """
+    Set the parameters that control the scaling of plot elements.
+
+    This affects things like the size of the labels, lines, and other elements
+    of the plot, but not the overall style. This is accomplished using the
+    matplotlib rcParams system.
+
+    The base context is "notebook", and the other contexts are "paper", "talk",
+    and "poster", which are version of the notebook parameters scaled by different
+    values. Font elements can also be scaled independently of (but relative to)
+    the other values.
+
+    See :func:`plotting_context` to get the parameter values.
+
+    Parameters
+    ----------
+    context : dict, or one of {paper, notebook, talk, poster}
+        A dictionary of parameters or the name of a preconfigured set.
+    font_scale : float, optional
+        Separate scaling factor to independently scale the size of the
+        font elements.
+    rc : dict, optional
+        Parameter mappings to override the values in the preset seaborn
+        context dictionaries. This only updates parameters that are
+        considered part of the context definition.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/set_context.rst
+
+    """
+    context_object = plotting_context(context, font_scale, rc)
+    mpl.rcParams.update(context_object)
+
+
+class _RCAesthetics(dict):
+    def __enter__(self):
+        rc = mpl.rcParams
+        self._orig = {k: rc[k] for k in self._keys}
+        self._set(self)
+
+    def __exit__(self, exc_type, exc_value, exc_tb):
+        self._set(self._orig)
+
+    def __call__(self, func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            with self:
+                return func(*args, **kwargs)
+        return wrapper
+
+
+class _AxesStyle(_RCAesthetics):
+    """Light wrapper on a dict to set style temporarily."""
+    _keys = _style_keys
+    _set = staticmethod(set_style)
+
+
+class _PlottingContext(_RCAesthetics):
+    """Light wrapper on a dict to set context temporarily."""
+    _keys = _context_keys
+    _set = staticmethod(set_context)
+
+
+def set_palette(palette, n_colors=None, desat=None, color_codes=False):
+    """Set the matplotlib color cycle using a seaborn palette.
+
+    Parameters
+    ----------
+    palette : seaborn color paltte | matplotlib colormap | hls | husl
+        Palette definition. Should be something :func:`color_palette` can process.
+    n_colors : int
+        Number of colors in the cycle. The default number of colors will depend
+        on the format of ``palette``, see the :func:`color_palette`
+        documentation for more information.
+    desat : float
+        Proportion to desaturate each color by.
+    color_codes : bool
+        If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
+        color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
+
+    See Also
+    --------
+    color_palette : build a color palette or set the color cycle temporarily
+                    in a ``with`` statement.
+    set_context : set parameters to scale plot elements
+    set_style : set the default parameters for figure style
+
+    """
+    colors = palettes.color_palette(palette, n_colors, desat)
+    cyl = cycler('color', colors)
+    mpl.rcParams['axes.prop_cycle'] = cyl
+    if color_codes:
+        try:
+            palettes.set_color_codes(palette)
+        except (ValueError, TypeError):
+            pass
diff --git a/testbed/mwaskom__seaborn/seaborn/regression.py b/testbed/mwaskom__seaborn/seaborn/regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7d804e26228a8370ab4ffa107043b144c4fa1c
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/regression.py
@@ -0,0 +1,924 @@
+"""Plotting functions for linear models (broadly construed)."""
+import copy
+from textwrap import dedent
+import warnings
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+
+try:
+    import statsmodels
+    assert statsmodels
+    _has_statsmodels = True
+except ImportError:
+    _has_statsmodels = False
+
+from . import utils
+from . import algorithms as algo
+from .axisgrid import FacetGrid, _facet_docs
+
+
+__all__ = ["lmplot", "regplot", "residplot"]
+
+
+class _LinearPlotter:
+    """Base class for plotting relational data in tidy format.
+
+    To get anything useful done you'll have to inherit from this, but setup
+    code that can be abstracted out should be put here.
+
+    """
+    def establish_variables(self, data, **kws):
+        """Extract variables from data or use directly."""
+        self.data = data
+
+        # Validate the inputs
+        any_strings = any([isinstance(v, str) for v in kws.values()])
+        if any_strings and data is None:
+            raise ValueError("Must pass `data` if using named variables.")
+
+        # Set the variables
+        for var, val in kws.items():
+            if isinstance(val, str):
+                vector = data[val]
+            elif isinstance(val, list):
+                vector = np.asarray(val)
+            else:
+                vector = val
+            if vector is not None and vector.shape != (1,):
+                vector = np.squeeze(vector)
+            if np.ndim(vector) > 1:
+                err = "regplot inputs must be 1d"
+                raise ValueError(err)
+            setattr(self, var, vector)
+
+    def dropna(self, *vars):
+        """Remove observations with missing data."""
+        vals = [getattr(self, var) for var in vars]
+        vals = [v for v in vals if v is not None]
+        not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1)
+        for var in vars:
+            val = getattr(self, var)
+            if val is not None:
+                setattr(self, var, val[not_na])
+
+    def plot(self, ax):
+        raise NotImplementedError
+
+
+class _RegressionPlotter(_LinearPlotter):
+    """Plotter for numeric independent variables with regression model.
+
+    This does the computations and drawing for the `regplot` function, and
+    is thus also used indirectly by `lmplot`.
+    """
+    def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,
+                 x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000,
+                 units=None, seed=None, order=1, logistic=False, lowess=False,
+                 robust=False, logx=False, x_partial=None, y_partial=None,
+                 truncate=False, dropna=True, x_jitter=None, y_jitter=None,
+                 color=None, label=None):
+
+        # Set member attributes
+        self.x_estimator = x_estimator
+        self.ci = ci
+        self.x_ci = ci if x_ci == "ci" else x_ci
+        self.n_boot = n_boot
+        self.seed = seed
+        self.scatter = scatter
+        self.fit_reg = fit_reg
+        self.order = order
+        self.logistic = logistic
+        self.lowess = lowess
+        self.robust = robust
+        self.logx = logx
+        self.truncate = truncate
+        self.x_jitter = x_jitter
+        self.y_jitter = y_jitter
+        self.color = color
+        self.label = label
+
+        # Validate the regression options:
+        if sum((order > 1, logistic, robust, lowess, logx)) > 1:
+            raise ValueError("Mutually exclusive regression options.")
+
+        # Extract the data vals from the arguments or passed dataframe
+        self.establish_variables(data, x=x, y=y, units=units,
+                                 x_partial=x_partial, y_partial=y_partial)
+
+        # Drop null observations
+        if dropna:
+            self.dropna("x", "y", "units", "x_partial", "y_partial")
+
+        # Regress nuisance variables out of the data
+        if self.x_partial is not None:
+            self.x = self.regress_out(self.x, self.x_partial)
+        if self.y_partial is not None:
+            self.y = self.regress_out(self.y, self.y_partial)
+
+        # Possibly bin the predictor variable, which implies a point estimate
+        if x_bins is not None:
+            self.x_estimator = np.mean if x_estimator is None else x_estimator
+            x_discrete, x_bins = self.bin_predictor(x_bins)
+            self.x_discrete = x_discrete
+        else:
+            self.x_discrete = self.x
+
+        # Disable regression in case of singleton inputs
+        if len(self.x) <= 1:
+            self.fit_reg = False
+
+        # Save the range of the x variable for the grid later
+        if self.fit_reg:
+            self.x_range = self.x.min(), self.x.max()
+
+    @property
+    def scatter_data(self):
+        """Data where each observation is a point."""
+        x_j = self.x_jitter
+        if x_j is None:
+            x = self.x
+        else:
+            x = self.x + np.random.uniform(-x_j, x_j, len(self.x))
+
+        y_j = self.y_jitter
+        if y_j is None:
+            y = self.y
+        else:
+            y = self.y + np.random.uniform(-y_j, y_j, len(self.y))
+
+        return x, y
+
+    @property
+    def estimate_data(self):
+        """Data with a point estimate and CI for each discrete x value."""
+        x, y = self.x_discrete, self.y
+        vals = sorted(np.unique(x))
+        points, cis = [], []
+
+        for val in vals:
+
+            # Get the point estimate of the y variable
+            _y = y[x == val]
+            est = self.x_estimator(_y)
+            points.append(est)
+
+            # Compute the confidence interval for this estimate
+            if self.x_ci is None:
+                cis.append(None)
+            else:
+                units = None
+                if self.x_ci == "sd":
+                    sd = np.std(_y)
+                    _ci = est - sd, est + sd
+                else:
+                    if self.units is not None:
+                        units = self.units[x == val]
+                    boots = algo.bootstrap(_y,
+                                           func=self.x_estimator,
+                                           n_boot=self.n_boot,
+                                           units=units,
+                                           seed=self.seed)
+                    _ci = utils.ci(boots, self.x_ci)
+                cis.append(_ci)
+
+        return vals, points, cis
+
+    def fit_regression(self, ax=None, x_range=None, grid=None):
+        """Fit the regression model."""
+        # Create the grid for the regression
+        if grid is None:
+            if self.truncate:
+                x_min, x_max = self.x_range
+            else:
+                if ax is None:
+                    x_min, x_max = x_range
+                else:
+                    x_min, x_max = ax.get_xlim()
+            grid = np.linspace(x_min, x_max, 100)
+        ci = self.ci
+
+        # Fit the regression
+        if self.order > 1:
+            yhat, yhat_boots = self.fit_poly(grid, self.order)
+        elif self.logistic:
+            from statsmodels.genmod.generalized_linear_model import GLM
+            from statsmodels.genmod.families import Binomial
+            yhat, yhat_boots = self.fit_statsmodels(grid, GLM,
+                                                    family=Binomial())
+        elif self.lowess:
+            ci = None
+            grid, yhat = self.fit_lowess()
+        elif self.robust:
+            from statsmodels.robust.robust_linear_model import RLM
+            yhat, yhat_boots = self.fit_statsmodels(grid, RLM)
+        elif self.logx:
+            yhat, yhat_boots = self.fit_logx(grid)
+        else:
+            yhat, yhat_boots = self.fit_fast(grid)
+
+        # Compute the confidence interval at each grid point
+        if ci is None:
+            err_bands = None
+        else:
+            err_bands = utils.ci(yhat_boots, ci, axis=0)
+
+        return grid, yhat, err_bands
+
+    def fit_fast(self, grid):
+        """Low-level regression and prediction using linear algebra."""
+        def reg_func(_x, _y):
+            return np.linalg.pinv(_x).dot(_y)
+
+        X, y = np.c_[np.ones(len(self.x)), self.x], self.y
+        grid = np.c_[np.ones(len(grid)), grid]
+        yhat = grid.dot(reg_func(X, y))
+        if self.ci is None:
+            return yhat, None
+
+        beta_boots = algo.bootstrap(X, y,
+                                    func=reg_func,
+                                    n_boot=self.n_boot,
+                                    units=self.units,
+                                    seed=self.seed).T
+        yhat_boots = grid.dot(beta_boots).T
+        return yhat, yhat_boots
+
+    def fit_poly(self, grid, order):
+        """Regression using numpy polyfit for higher-order trends."""
+        def reg_func(_x, _y):
+            return np.polyval(np.polyfit(_x, _y, order), grid)
+
+        x, y = self.x, self.y
+        yhat = reg_func(x, y)
+        if self.ci is None:
+            return yhat, None
+
+        yhat_boots = algo.bootstrap(x, y,
+                                    func=reg_func,
+                                    n_boot=self.n_boot,
+                                    units=self.units,
+                                    seed=self.seed)
+        return yhat, yhat_boots
+
+    def fit_statsmodels(self, grid, model, **kwargs):
+        """More general regression function using statsmodels objects."""
+        import statsmodels.genmod.generalized_linear_model as glm
+        X, y = np.c_[np.ones(len(self.x)), self.x], self.y
+        grid = np.c_[np.ones(len(grid)), grid]
+
+        def reg_func(_x, _y):
+            try:
+                yhat = model(_y, _x, **kwargs).fit().predict(grid)
+            except glm.PerfectSeparationError:
+                yhat = np.empty(len(grid))
+                yhat.fill(np.nan)
+            return yhat
+
+        yhat = reg_func(X, y)
+        if self.ci is None:
+            return yhat, None
+
+        yhat_boots = algo.bootstrap(X, y,
+                                    func=reg_func,
+                                    n_boot=self.n_boot,
+                                    units=self.units,
+                                    seed=self.seed)
+        return yhat, yhat_boots
+
+    def fit_lowess(self):
+        """Fit a locally-weighted regression, which returns its own grid."""
+        from statsmodels.nonparametric.smoothers_lowess import lowess
+        grid, yhat = lowess(self.y, self.x).T
+        return grid, yhat
+
+    def fit_logx(self, grid):
+        """Fit the model in log-space."""
+        X, y = np.c_[np.ones(len(self.x)), self.x], self.y
+        grid = np.c_[np.ones(len(grid)), np.log(grid)]
+
+        def reg_func(_x, _y):
+            _x = np.c_[_x[:, 0], np.log(_x[:, 1])]
+            return np.linalg.pinv(_x).dot(_y)
+
+        yhat = grid.dot(reg_func(X, y))
+        if self.ci is None:
+            return yhat, None
+
+        beta_boots = algo.bootstrap(X, y,
+                                    func=reg_func,
+                                    n_boot=self.n_boot,
+                                    units=self.units,
+                                    seed=self.seed).T
+        yhat_boots = grid.dot(beta_boots).T
+        return yhat, yhat_boots
+
+    def bin_predictor(self, bins):
+        """Discretize a predictor by assigning value to closest bin."""
+        x = np.asarray(self.x)
+        if np.isscalar(bins):
+            percentiles = np.linspace(0, 100, bins + 2)[1:-1]
+            bins = np.percentile(x, percentiles)
+        else:
+            bins = np.ravel(bins)
+
+        dist = np.abs(np.subtract.outer(x, bins))
+        x_binned = bins[np.argmin(dist, axis=1)].ravel()
+
+        return x_binned, bins
+
+    def regress_out(self, a, b):
+        """Regress b from a keeping a's original mean."""
+        a_mean = a.mean()
+        a = a - a_mean
+        b = b - b.mean()
+        b = np.c_[b]
+        a_prime = a - b.dot(np.linalg.pinv(b).dot(a))
+        return np.asarray(a_prime + a_mean).reshape(a.shape)
+
+    def plot(self, ax, scatter_kws, line_kws):
+        """Draw the full plot."""
+        # Insert the plot label into the correct set of keyword arguments
+        if self.scatter:
+            scatter_kws["label"] = self.label
+        else:
+            line_kws["label"] = self.label
+
+        # Use the current color cycle state as a default
+        if self.color is None:
+            lines, = ax.plot([], [])
+            color = lines.get_color()
+            lines.remove()
+        else:
+            color = self.color
+
+        # Ensure that color is hex to avoid matplotlib weirdness
+        color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color))
+
+        # Let color in keyword arguments override overall plot color
+        scatter_kws.setdefault("color", color)
+        line_kws.setdefault("color", color)
+
+        # Draw the constituent plots
+        if self.scatter:
+            self.scatterplot(ax, scatter_kws)
+
+        if self.fit_reg:
+            self.lineplot(ax, line_kws)
+
+        # Label the axes
+        if hasattr(self.x, "name"):
+            ax.set_xlabel(self.x.name)
+        if hasattr(self.y, "name"):
+            ax.set_ylabel(self.y.name)
+
+    def scatterplot(self, ax, kws):
+        """Draw the data."""
+        # Treat the line-based markers specially, explicitly setting larger
+        # linewidth than is provided by the seaborn style defaults.
+        # This would ideally be handled better in matplotlib (i.e., distinguish
+        # between edgewidth for solid glyphs and linewidth for line glyphs
+        # but this should do for now.
+        line_markers = ["1", "2", "3", "4", "+", "x", "|", "_"]
+        if self.x_estimator is None:
+            if "marker" in kws and kws["marker"] in line_markers:
+                lw = mpl.rcParams["lines.linewidth"]
+            else:
+                lw = mpl.rcParams["lines.markeredgewidth"]
+            kws.setdefault("linewidths", lw)
+
+            if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4:
+                kws.setdefault("alpha", .8)
+
+            x, y = self.scatter_data
+            ax.scatter(x, y, **kws)
+        else:
+            # TODO abstraction
+            ci_kws = {"color": kws["color"]}
+            if "alpha" in kws:
+                ci_kws["alpha"] = kws["alpha"]
+            ci_kws["linewidth"] = mpl.rcParams["lines.linewidth"] * 1.75
+            kws.setdefault("s", 50)
+
+            xs, ys, cis = self.estimate_data
+            if [ci for ci in cis if ci is not None]:
+                for x, ci in zip(xs, cis):
+                    ax.plot([x, x], ci, **ci_kws)
+            ax.scatter(xs, ys, **kws)
+
+    def lineplot(self, ax, kws):
+        """Draw the model."""
+        # Fit the regression model
+        grid, yhat, err_bands = self.fit_regression(ax)
+        edges = grid[0], grid[-1]
+
+        # Get set default aesthetics
+        fill_color = kws["color"]
+        lw = kws.pop("lw", mpl.rcParams["lines.linewidth"] * 1.5)
+        kws.setdefault("linewidth", lw)
+
+        # Draw the regression line and confidence interval
+        line, = ax.plot(grid, yhat, **kws)
+        if not self.truncate:
+            line.sticky_edges.x[:] = edges  # Prevent mpl from adding margin
+        if err_bands is not None:
+            ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)
+
+
+_regression_docs = dict(
+
+    model_api=dedent("""\
+    There are a number of mutually exclusive options for estimating the
+    regression model. See the :ref:`tutorial ` for more
+    information.\
+    """),
+    regplot_vs_lmplot=dedent("""\
+    The :func:`regplot` and :func:`lmplot` functions are closely related, but
+    the former is an axes-level function while the latter is a figure-level
+    function that combines :func:`regplot` and :class:`FacetGrid`.\
+    """),
+    x_estimator=dedent("""\
+    x_estimator : callable that maps vector -> scalar, optional
+        Apply this function to each unique value of ``x`` and plot the
+        resulting estimate. This is useful when ``x`` is a discrete variable.
+        If ``x_ci`` is given, this estimate will be bootstrapped and a
+        confidence interval will be drawn.\
+    """),
+    x_bins=dedent("""\
+    x_bins : int or vector, optional
+        Bin the ``x`` variable into discrete bins and then estimate the central
+        tendency and a confidence interval. This binning only influences how
+        the scatterplot is drawn; the regression is still fit to the original
+        data.  This parameter is interpreted either as the number of
+        evenly-sized (not necessary spaced) bins or the positions of the bin
+        centers. When this parameter is used, it implies that the default of
+        ``x_estimator`` is ``numpy.mean``.\
+    """),
+    x_ci=dedent("""\
+    x_ci : "ci", "sd", int in [0, 100] or None, optional
+        Size of the confidence interval used when plotting a central tendency
+        for discrete values of ``x``. If ``"ci"``, defer to the value of the
+        ``ci`` parameter. If ``"sd"``, skip bootstrapping and show the
+        standard deviation of the observations in each bin.\
+    """),
+    scatter=dedent("""\
+    scatter : bool, optional
+        If ``True``, draw a scatterplot with the underlying observations (or
+        the ``x_estimator`` values).\
+    """),
+    fit_reg=dedent("""\
+    fit_reg : bool, optional
+        If ``True``, estimate and plot a regression model relating the ``x``
+        and ``y`` variables.\
+    """),
+    ci=dedent("""\
+    ci : int in [0, 100] or None, optional
+        Size of the confidence interval for the regression estimate. This will
+        be drawn using translucent bands around the regression line. The
+        confidence interval is estimated using a bootstrap; for large
+        datasets, it may be advisable to avoid that computation by setting
+        this parameter to None.\
+    """),
+    n_boot=dedent("""\
+    n_boot : int, optional
+        Number of bootstrap resamples used to estimate the ``ci``. The default
+        value attempts to balance time and stability; you may want to increase
+        this value for "final" versions of plots.\
+    """),
+    units=dedent("""\
+    units : variable name in ``data``, optional
+        If the ``x`` and ``y`` observations are nested within sampling units,
+        those can be specified here. This will be taken into account when
+        computing the confidence intervals by performing a multilevel bootstrap
+        that resamples both units and observations (within unit). This does not
+        otherwise influence how the regression is estimated or drawn.\
+    """),
+    seed=dedent("""\
+    seed : int, numpy.random.Generator, or numpy.random.RandomState, optional
+        Seed or random number generator for reproducible bootstrapping.\
+    """),
+    order=dedent("""\
+    order : int, optional
+        If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a
+        polynomial regression.\
+    """),
+    logistic=dedent("""\
+    logistic : bool, optional
+        If ``True``, assume that ``y`` is a binary variable and use
+        ``statsmodels`` to estimate a logistic regression model. Note that this
+        is substantially more computationally intensive than linear regression,
+        so you may wish to decrease the number of bootstrap resamples
+        (``n_boot``) or set ``ci`` to None.\
+    """),
+    lowess=dedent("""\
+    lowess : bool, optional
+        If ``True``, use ``statsmodels`` to estimate a nonparametric lowess
+        model (locally weighted linear regression). Note that confidence
+        intervals cannot currently be drawn for this kind of model.\
+    """),
+    robust=dedent("""\
+    robust : bool, optional
+        If ``True``, use ``statsmodels`` to estimate a robust regression. This
+        will de-weight outliers. Note that this is substantially more
+        computationally intensive than standard linear regression, so you may
+        wish to decrease the number of bootstrap resamples (``n_boot``) or set
+        ``ci`` to None.\
+    """),
+    logx=dedent("""\
+    logx : bool, optional
+        If ``True``, estimate a linear regression of the form y ~ log(x), but
+        plot the scatterplot and regression model in the input space. Note that
+        ``x`` must be positive for this to work.\
+    """),
+    xy_partial=dedent("""\
+    {x,y}_partial : strings in ``data`` or matrices
+        Confounding variables to regress out of the ``x`` or ``y`` variables
+        before plotting.\
+    """),
+    truncate=dedent("""\
+    truncate : bool, optional
+        If ``True``, the regression line is bounded by the data limits. If
+        ``False``, it extends to the ``x`` axis limits.
+    """),
+    xy_jitter=dedent("""\
+    {x,y}_jitter : floats, optional
+        Add uniform random noise of this size to either the ``x`` or ``y``
+        variables. The noise is added to a copy of the data after fitting the
+        regression, and only influences the look of the scatterplot. This can
+        be helpful when plotting variables that take discrete values.\
+    """),
+    scatter_line_kws=dedent("""\
+    {scatter,line}_kws : dictionaries
+        Additional keyword arguments to pass to ``plt.scatter`` and
+        ``plt.plot``.\
+    """),
+)
+_regression_docs.update(_facet_docs)
+
+
+def lmplot(
+    data=None, *,
+    x=None, y=None, hue=None, col=None, row=None,
+    palette=None, col_wrap=None, height=5, aspect=1, markers="o",
+    sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None,
+    legend=True, legend_out=None, x_estimator=None, x_bins=None,
+    x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000,
+    units=None, seed=None, order=1, logistic=False, lowess=False,
+    robust=False, logx=False, x_partial=None, y_partial=None,
+    truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None,
+    line_kws=None, facet_kws=None,
+):
+
+    if facet_kws is None:
+        facet_kws = {}
+
+    def facet_kw_deprecation(key, val):
+        msg = (
+            f"{key} is deprecated from the `lmplot` function signature. "
+            "Please update your code to pass it using `facet_kws`."
+        )
+        if val is not None:
+            warnings.warn(msg, UserWarning)
+            facet_kws[key] = val
+
+    facet_kw_deprecation("sharex", sharex)
+    facet_kw_deprecation("sharey", sharey)
+    facet_kw_deprecation("legend_out", legend_out)
+
+    if data is None:
+        raise TypeError("Missing required keyword argument `data`.")
+
+    # Reduce the dataframe to only needed columns
+    need_cols = [x, y, hue, col, row, units, x_partial, y_partial]
+    cols = np.unique([a for a in need_cols if a is not None]).tolist()
+    data = data[cols]
+
+    # Initialize the grid
+    facets = FacetGrid(
+        data, row=row, col=col, hue=hue,
+        palette=palette,
+        row_order=row_order, col_order=col_order, hue_order=hue_order,
+        height=height, aspect=aspect, col_wrap=col_wrap,
+        **facet_kws,
+    )
+
+    # Add the markers here as FacetGrid has figured out how many levels of the
+    # hue variable are needed and we don't want to duplicate that process
+    if facets.hue_names is None:
+        n_markers = 1
+    else:
+        n_markers = len(facets.hue_names)
+    if not isinstance(markers, list):
+        markers = [markers] * n_markers
+    if len(markers) != n_markers:
+        raise ValueError("markers must be a singleton or a list of markers "
+                         "for each level of the hue variable")
+    facets.hue_kws = {"marker": markers}
+
+    def update_datalim(data, x, y, ax, **kws):
+        xys = data[[x, y]].to_numpy().astype(float)
+        ax.update_datalim(xys, updatey=False)
+        ax.autoscale_view(scaley=False)
+
+    facets.map_dataframe(update_datalim, x=x, y=y)
+
+    # Draw the regression plot on each facet
+    regplot_kws = dict(
+        x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci,
+        scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units,
+        seed=seed, order=order, logistic=logistic, lowess=lowess,
+        robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial,
+        truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter,
+        scatter_kws=scatter_kws, line_kws=line_kws,
+    )
+    facets.map_dataframe(regplot, x=x, y=y, **regplot_kws)
+    facets.set_axis_labels(x, y)
+
+    # Add a legend
+    if legend and (hue is not None) and (hue not in [col, row]):
+        facets.add_legend()
+    return facets
+
+
+lmplot.__doc__ = dedent("""\
+    Plot data and regression model fits across a FacetGrid.
+
+    This function combines :func:`regplot` and :class:`FacetGrid`. It is
+    intended as a convenient interface to fit regression models across
+    conditional subsets of a dataset.
+
+    When thinking about how to assign variables to different facets, a general
+    rule is that it makes sense to use ``hue`` for the most important
+    comparison, followed by ``col`` and ``row``. However, always think about
+    your particular dataset and the goals of the visualization you are
+    creating.
+
+    {model_api}
+
+    The parameters to this function span most of the options in
+    :class:`FacetGrid`, although there may be occasional cases where you will
+    want to use that class and :func:`regplot` directly.
+
+    Parameters
+    ----------
+    {data}
+    x, y : strings, optional
+        Input variables; these should be column names in ``data``.
+    hue, col, row : strings
+        Variables that define subsets of the data, which will be drawn on
+        separate facets in the grid. See the ``*_order`` parameters to control
+        the order of levels of this variable.
+    {palette}
+    {col_wrap}
+    {height}
+    {aspect}
+    markers : matplotlib marker code or list of marker codes, optional
+        Markers for the scatterplot. If a list, each marker in the list will be
+        used for each level of the ``hue`` variable.
+    {share_xy}
+
+        .. deprecated:: 0.12.0
+            Pass using the `facet_kws` dictionary.
+
+    {{hue,col,row}}_order : lists, optional
+        Order for the levels of the faceting variables. By default, this will
+        be the order that the levels appear in ``data`` or, if the variables
+        are pandas categoricals, the category order.
+    legend : bool, optional
+        If ``True`` and there is a ``hue`` variable, add a legend.
+    {legend_out}
+
+        .. deprecated:: 0.12.0
+            Pass using the `facet_kws` dictionary.
+
+    {x_estimator}
+    {x_bins}
+    {x_ci}
+    {scatter}
+    {fit_reg}
+    {ci}
+    {n_boot}
+    {units}
+    {seed}
+    {order}
+    {logistic}
+    {lowess}
+    {robust}
+    {logx}
+    {xy_partial}
+    {truncate}
+    {xy_jitter}
+    {scatter_line_kws}
+    facet_kws : dict
+        Dictionary of keyword arguments for :class:`FacetGrid`.
+
+    See Also
+    --------
+    regplot : Plot data and a conditional model fit.
+    FacetGrid : Subplot grid for plotting conditional relationships.
+    pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with
+               ``kind="reg"``).
+
+    Notes
+    -----
+
+    {regplot_vs_lmplot}
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/lmplot.rst
+
+    """).format(**_regression_docs)
+
+
+def regplot(
+    data=None, *, x=None, y=None,
+    x_estimator=None, x_bins=None, x_ci="ci",
+    scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None,
+    seed=None, order=1, logistic=False, lowess=False, robust=False,
+    logx=False, x_partial=None, y_partial=None,
+    truncate=True, dropna=True, x_jitter=None, y_jitter=None,
+    label=None, color=None, marker="o",
+    scatter_kws=None, line_kws=None, ax=None
+):
+
+    plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci,
+                                 scatter, fit_reg, ci, n_boot, units, seed,
+                                 order, logistic, lowess, robust, logx,
+                                 x_partial, y_partial, truncate, dropna,
+                                 x_jitter, y_jitter, color, label)
+
+    if ax is None:
+        ax = plt.gca()
+
+    scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws)
+    scatter_kws["marker"] = marker
+    line_kws = {} if line_kws is None else copy.copy(line_kws)
+    plotter.plot(ax, scatter_kws, line_kws)
+    return ax
+
+
+regplot.__doc__ = dedent("""\
+    Plot data and a linear regression model fit.
+
+    {model_api}
+
+    Parameters
+    ----------
+    x, y: string, series, or vector array
+        Input variables. If strings, these should correspond with column names
+        in ``data``. When pandas objects are used, axes will be labeled with
+        the series name.
+    {data}
+    {x_estimator}
+    {x_bins}
+    {x_ci}
+    {scatter}
+    {fit_reg}
+    {ci}
+    {n_boot}
+    {units}
+    {seed}
+    {order}
+    {logistic}
+    {lowess}
+    {robust}
+    {logx}
+    {xy_partial}
+    {truncate}
+    {xy_jitter}
+    label : string
+        Label to apply to either the scatterplot or regression line (if
+        ``scatter`` is ``False``) for use in a legend.
+    color : matplotlib color
+        Color to apply to all plot elements; will be superseded by colors
+        passed in ``scatter_kws`` or ``line_kws``.
+    marker : matplotlib marker code
+        Marker to use for the scatterplot glyphs.
+    {scatter_line_kws}
+    ax : matplotlib Axes, optional
+        Axes object to draw the plot onto, otherwise uses the current Axes.
+
+    Returns
+    -------
+    ax : matplotlib Axes
+        The Axes object containing the plot.
+
+    See Also
+    --------
+    lmplot : Combine :func:`regplot` and :class:`FacetGrid` to plot multiple
+             linear relationships in a dataset.
+    jointplot : Combine :func:`regplot` and :class:`JointGrid` (when used with
+                ``kind="reg"``).
+    pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with
+               ``kind="reg"``).
+    residplot : Plot the residuals of a linear regression model.
+
+    Notes
+    -----
+
+    {regplot_vs_lmplot}
+
+
+    It's also easy to combine :func:`regplot` and :class:`JointGrid` or
+    :class:`PairGrid` through the :func:`jointplot` and :func:`pairplot`
+    functions, although these do not directly accept all of :func:`regplot`'s
+    parameters.
+
+    Examples
+    --------
+
+    .. include: ../docstrings/regplot.rst
+
+    """).format(**_regression_docs)
+
+
+def residplot(
+    data=None, *, x=None, y=None,
+    x_partial=None, y_partial=None, lowess=False,
+    order=1, robust=False, dropna=True, label=None, color=None,
+    scatter_kws=None, line_kws=None, ax=None
+):
+    """Plot the residuals of a linear regression.
+
+    This function will regress y on x (possibly as a robust or polynomial
+    regression) and then draw a scatterplot of the residuals. You can
+    optionally fit a lowess smoother to the residual plot, which can
+    help in determining if there is structure to the residuals.
+
+    Parameters
+    ----------
+    data : DataFrame, optional
+        DataFrame to use if `x` and `y` are column names.
+    x : vector or string
+        Data or column name in `data` for the predictor variable.
+    y : vector or string
+        Data or column name in `data` for the response variable.
+    {x, y}_partial : vectors or string(s) , optional
+        These variables are treated as confounding and are removed from
+        the `x` or `y` variables before plotting.
+    lowess : boolean, optional
+        Fit a lowess smoother to the residual scatterplot.
+    order : int, optional
+        Order of the polynomial to fit when calculating the residuals.
+    robust : boolean, optional
+        Fit a robust linear regression when calculating the residuals.
+    dropna : boolean, optional
+        If True, ignore observations with missing data when fitting and
+        plotting.
+    label : string, optional
+        Label that will be used in any plot legends.
+    color : matplotlib color, optional
+        Color to use for all elements of the plot.
+    {scatter, line}_kws : dictionaries, optional
+        Additional keyword arguments passed to scatter() and plot() for drawing
+        the components of the plot.
+    ax : matplotlib axis, optional
+        Plot into this axis, otherwise grab the current axis or make a new
+        one if not existing.
+
+    Returns
+    -------
+    ax: matplotlib axes
+        Axes with the regression plot.
+
+    See Also
+    --------
+    regplot : Plot a simple linear regression model.
+    jointplot : Draw a :func:`residplot` with univariate marginal distributions
+                (when used with ``kind="resid"``).
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/residplot.rst
+
+    """
+    plotter = _RegressionPlotter(x, y, data, ci=None,
+                                 order=order, robust=robust,
+                                 x_partial=x_partial, y_partial=y_partial,
+                                 dropna=dropna, color=color, label=label)
+
+    if ax is None:
+        ax = plt.gca()
+
+    # Calculate the residual from a linear regression
+    _, yhat, _ = plotter.fit_regression(grid=plotter.x)
+    plotter.y = plotter.y - yhat
+
+    # Set the regression option on the plotter
+    if lowess:
+        plotter.lowess = True
+    else:
+        plotter.fit_reg = False
+
+    # Plot a horizontal line at 0
+    ax.axhline(0, ls=":", c=".2")
+
+    # Draw the scatterplot
+    scatter_kws = {} if scatter_kws is None else scatter_kws.copy()
+    line_kws = {} if line_kws is None else line_kws.copy()
+    plotter.plot(ax, scatter_kws, line_kws)
+    return ax
diff --git a/testbed/mwaskom__seaborn/seaborn/relational.py b/testbed/mwaskom__seaborn/seaborn/relational.py
new file mode 100644
index 0000000000000000000000000000000000000000..18e18bb64ca8dc6a51ab8e554a31cf4cfccdbef5
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/relational.py
@@ -0,0 +1,1071 @@
+import warnings
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+
+from ._oldcore import (
+    VectorPlotter,
+)
+from .utils import (
+    locator_to_legend_entries,
+    adjust_legend_subtitles,
+    _default_color,
+    _deprecate_ci,
+)
+from ._statistics import EstimateAggregator
+from .axisgrid import FacetGrid, _facet_docs
+from ._docstrings import DocstringComponents, _core_docs
+
+
+__all__ = ["relplot", "scatterplot", "lineplot"]
+
+
+_relational_narrative = DocstringComponents(dict(
+
+    # ---  Introductory prose
+    main_api="""
+The relationship between `x` and `y` can be shown for different subsets
+of the data using the `hue`, `size`, and `style` parameters. These
+parameters control what visual semantics are used to identify the different
+subsets. It is possible to show up to three dimensions independently by
+using all three semantic types, but this style of plot can be hard to
+interpret and is often ineffective. Using redundant semantics (i.e. both
+`hue` and `style` for the same variable) can be helpful for making
+graphics more accessible.
+
+See the :ref:`tutorial ` for more information.
+    """,
+
+    relational_semantic="""
+The default treatment of the `hue` (and to a lesser extent, `size`)
+semantic, if present, depends on whether the variable is inferred to
+represent "numeric" or "categorical" data. In particular, numeric variables
+are represented with a sequential colormap by default, and the legend
+entries show regular "ticks" with values that may or may not exist in the
+data. This behavior can be controlled through various parameters, as
+described and illustrated below.
+    """,
+))
+
+_relational_docs = dict(
+
+    # --- Shared function parameters
+    data_vars="""
+x, y : names of variables in `data` or vector data
+    Input data variables; must be numeric. Can pass data directly or
+    reference columns in `data`.
+    """,
+    data="""
+data : DataFrame, array, or list of arrays
+    Input data structure. If `x` and `y` are specified as names, this
+    should be a "long-form" DataFrame containing those columns. Otherwise
+    it is treated as "wide-form" data and grouping variables are ignored.
+    See the examples for the various ways this parameter can be specified
+    and the different effects of each.
+    """,
+    palette="""
+palette : string, list, dict, or matplotlib colormap
+    An object that determines how colors are chosen when `hue` is used.
+    It can be the name of a seaborn palette or matplotlib colormap, a list
+    of colors (anything matplotlib understands), a dict mapping levels
+    of the `hue` variable to colors, or a matplotlib colormap object.
+    """,
+    hue_order="""
+hue_order : list
+    Specified order for the appearance of the `hue` variable levels,
+    otherwise they are determined from the data. Not relevant when the
+    `hue` variable is numeric.
+    """,
+    hue_norm="""
+hue_norm : tuple or :class:`matplotlib.colors.Normalize` object
+    Normalization in data units for colormap applied to the `hue`
+    variable when it is numeric. Not relevant if `hue` is categorical.
+    """,
+    sizes="""
+sizes : list, dict, or tuple
+    An object that determines how sizes are chosen when `size` is used.
+    List or dict arguments should provide a size for each unique data value,
+    which forces a categorical interpretation. The argument may also be a
+    min, max tuple.
+    """,
+    size_order="""
+size_order : list
+    Specified order for appearance of the `size` variable levels,
+    otherwise they are determined from the data. Not relevant when the
+    `size` variable is numeric.
+    """,
+    size_norm="""
+size_norm : tuple or Normalize object
+    Normalization in data units for scaling plot objects when the
+    `size` variable is numeric.
+    """,
+    dashes="""
+dashes : boolean, list, or dictionary
+    Object determining how to draw the lines for different levels of the
+    `style` variable. Setting to `True` will use default dash codes, or
+    you can pass a list of dash codes or a dictionary mapping levels of the
+    `style` variable to dash codes. Setting to `False` will use solid
+    lines for all subsets. Dashes are specified as in matplotlib: a tuple
+    of `(segment, gap)` lengths, or an empty string to draw a solid line.
+    """,
+    markers="""
+markers : boolean, list, or dictionary
+    Object determining how to draw the markers for different levels of the
+    `style` variable. Setting to `True` will use default markers, or
+    you can pass a list of markers or a dictionary mapping levels of the
+    `style` variable to markers. Setting to `False` will draw
+    marker-less lines.  Markers are specified as in matplotlib.
+    """,
+    style_order="""
+style_order : list
+    Specified order for appearance of the `style` variable levels
+    otherwise they are determined from the data. Not relevant when the
+    `style` variable is numeric.
+    """,
+    units="""
+units : vector or key in `data`
+    Grouping variable identifying sampling units. When used, a separate
+    line will be drawn for each unit with appropriate semantics, but no
+    legend entry will be added. Useful for showing distribution of
+    experimental replicates when exact identities are not needed.
+    """,
+    estimator="""
+estimator : name of pandas method or callable or None
+    Method for aggregating across multiple observations of the `y`
+    variable at the same `x` level. If `None`, all observations will
+    be drawn.
+    """,
+    ci="""
+ci : int or "sd" or None
+    Size of the confidence interval to draw when aggregating.
+
+    .. deprecated:: 0.12.0
+        Use the new `errorbar` parameter for more flexibility.
+
+    """,
+    n_boot="""
+n_boot : int
+    Number of bootstraps to use for computing the confidence interval.
+    """,
+    seed="""
+seed : int, numpy.random.Generator, or numpy.random.RandomState
+    Seed or random number generator for reproducible bootstrapping.
+    """,
+    legend="""
+legend : "auto", "brief", "full", or False
+    How to draw the legend. If "brief", numeric `hue` and `size`
+    variables will be represented with a sample of evenly spaced values.
+    If "full", every group will get an entry in the legend. If "auto",
+    choose between brief or full representation based on number of levels.
+    If `False`, no legend data is added and no legend is drawn.
+    """,
+    ax_in="""
+ax : matplotlib Axes
+    Axes object to draw the plot onto, otherwise uses the current Axes.
+    """,
+    ax_out="""
+ax : matplotlib Axes
+    Returns the Axes object with the plot drawn onto it.
+    """,
+
+)
+
+
+_param_docs = DocstringComponents.from_nested_components(
+    core=_core_docs["params"],
+    facets=DocstringComponents(_facet_docs),
+    rel=DocstringComponents(_relational_docs),
+    stat=DocstringComponents.from_function_params(EstimateAggregator.__init__),
+)
+
+
+class _RelationalPlotter(VectorPlotter):
+
+    wide_structure = {
+        "x": "@index", "y": "@values", "hue": "@columns", "style": "@columns",
+    }
+
+    # TODO where best to define default parameters?
+    sort = True
+
+    def add_legend_data(self, ax):
+        """Add labeled artists to represent the different plot semantics."""
+        verbosity = self.legend
+        if isinstance(verbosity, str) and verbosity not in ["auto", "brief", "full"]:
+            err = "`legend` must be 'auto', 'brief', 'full', or a boolean."
+            raise ValueError(err)
+        elif verbosity is True:
+            verbosity = "auto"
+
+        legend_kwargs = {}
+        keys = []
+
+        # Assign a legend title if there is only going to be one sub-legend,
+        # otherwise, subtitles will be inserted into the texts list with an
+        # invisible handle (which is a hack)
+        titles = {
+            title for title in
+            (self.variables.get(v, None) for v in ["hue", "size", "style"])
+            if title is not None
+        }
+        if len(titles) == 1:
+            legend_title = titles.pop()
+        else:
+            legend_title = ""
+
+        title_kws = dict(
+            visible=False, color="w", s=0, linewidth=0, marker="", dashes=""
+        )
+
+        def update(var_name, val_name, **kws):
+
+            key = var_name, val_name
+            if key in legend_kwargs:
+                legend_kwargs[key].update(**kws)
+            else:
+                keys.append(key)
+
+                legend_kwargs[key] = dict(**kws)
+
+        # Define the maximum number of ticks to use for "brief" legends
+        brief_ticks = 6
+
+        # -- Add a legend for hue semantics
+        brief_hue = self._hue_map.map_type == "numeric" and (
+            verbosity == "brief"
+            or (verbosity == "auto" and len(self._hue_map.levels) > brief_ticks)
+        )
+        if brief_hue:
+            if isinstance(self._hue_map.norm, mpl.colors.LogNorm):
+                locator = mpl.ticker.LogLocator(numticks=brief_ticks)
+            else:
+                locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)
+            limits = min(self._hue_map.levels), max(self._hue_map.levels)
+            hue_levels, hue_formatted_levels = locator_to_legend_entries(
+                locator, limits, self.plot_data["hue"].infer_objects().dtype
+            )
+        elif self._hue_map.levels is None:
+            hue_levels = hue_formatted_levels = []
+        else:
+            hue_levels = hue_formatted_levels = self._hue_map.levels
+
+        # Add the hue semantic subtitle
+        if not legend_title and self.variables.get("hue", None) is not None:
+            update((self.variables["hue"], "title"),
+                   self.variables["hue"], **title_kws)
+
+        # Add the hue semantic labels
+        for level, formatted_level in zip(hue_levels, hue_formatted_levels):
+            if level is not None:
+                color = self._hue_map(level)
+                update(self.variables["hue"], formatted_level, color=color)
+
+        # -- Add a legend for size semantics
+        brief_size = self._size_map.map_type == "numeric" and (
+            verbosity == "brief"
+            or (verbosity == "auto" and len(self._size_map.levels) > brief_ticks)
+        )
+        if brief_size:
+            # Define how ticks will interpolate between the min/max data values
+            if isinstance(self._size_map.norm, mpl.colors.LogNorm):
+                locator = mpl.ticker.LogLocator(numticks=brief_ticks)
+            else:
+                locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)
+            # Define the min/max data values
+            limits = min(self._size_map.levels), max(self._size_map.levels)
+            size_levels, size_formatted_levels = locator_to_legend_entries(
+                locator, limits, self.plot_data["size"].infer_objects().dtype
+            )
+        elif self._size_map.levels is None:
+            size_levels = size_formatted_levels = []
+        else:
+            size_levels = size_formatted_levels = self._size_map.levels
+
+        # Add the size semantic subtitle
+        if not legend_title and self.variables.get("size", None) is not None:
+            update((self.variables["size"], "title"),
+                   self.variables["size"], **title_kws)
+
+        # Add the size semantic labels
+        for level, formatted_level in zip(size_levels, size_formatted_levels):
+            if level is not None:
+                size = self._size_map(level)
+                update(
+                    self.variables["size"],
+                    formatted_level,
+                    linewidth=size,
+                    s=size,
+                )
+
+        # -- Add a legend for style semantics
+
+        # Add the style semantic title
+        if not legend_title and self.variables.get("style", None) is not None:
+            update((self.variables["style"], "title"),
+                   self.variables["style"], **title_kws)
+
+        # Add the style semantic labels
+        if self._style_map.levels is not None:
+            for level in self._style_map.levels:
+                if level is not None:
+                    attrs = self._style_map(level)
+                    update(
+                        self.variables["style"],
+                        level,
+                        marker=attrs.get("marker", ""),
+                        dashes=attrs.get("dashes", ""),
+                    )
+
+        func = getattr(ax, self._legend_func)
+
+        legend_data = {}
+        legend_order = []
+
+        for key in keys:
+
+            _, label = key
+            kws = legend_kwargs[key]
+            kws.setdefault("color", ".2")
+            use_kws = {}
+            for attr in self._legend_attributes + ["visible"]:
+                if attr in kws:
+                    use_kws[attr] = kws[attr]
+            artist = func([], [], label=label, **use_kws)
+            if self._legend_func == "plot":
+                artist = artist[0]
+            legend_data[key] = artist
+            legend_order.append(key)
+
+        self.legend_title = legend_title
+        self.legend_data = legend_data
+        self.legend_order = legend_order
+
+
+class _LinePlotter(_RelationalPlotter):
+
+    _legend_attributes = ["color", "linewidth", "marker", "dashes"]
+    _legend_func = "plot"
+
+    def __init__(
+        self, *,
+        data=None, variables={},
+        estimator=None, n_boot=None, seed=None, errorbar=None,
+        sort=True, orient="x", err_style=None, err_kws=None, legend=None
+    ):
+
+        # TODO this is messy, we want the mapping to be agnostic about
+        # the kind of plot to draw, but for the time being we need to set
+        # this information so the SizeMapping can use it
+        self._default_size_range = (
+            np.r_[.5, 2] * mpl.rcParams["lines.linewidth"]
+        )
+
+        super().__init__(data=data, variables=variables)
+
+        self.estimator = estimator
+        self.errorbar = errorbar
+        self.n_boot = n_boot
+        self.seed = seed
+        self.sort = sort
+        self.orient = orient
+        self.err_style = err_style
+        self.err_kws = {} if err_kws is None else err_kws
+
+        self.legend = legend
+
+    def plot(self, ax, kws):
+        """Draw the plot onto an axes, passing matplotlib kwargs."""
+
+        # Draw a test plot, using the passed in kwargs. The goal here is to
+        # honor both (a) the current state of the plot cycler and (b) the
+        # specified kwargs on all the lines we will draw, overriding when
+        # relevant with the data semantics. Note that we won't cycle
+        # internally; in other words, if `hue` is not used, all elements will
+        # have the same color, but they will have the color that you would have
+        # gotten from the corresponding matplotlib function, and calling the
+        # function will advance the axes property cycle.
+
+        kws.setdefault("markeredgewidth", kws.pop("mew", .75))
+        kws.setdefault("markeredgecolor", kws.pop("mec", "w"))
+
+        # Set default error kwargs
+        err_kws = self.err_kws.copy()
+        if self.err_style == "band":
+            err_kws.setdefault("alpha", .2)
+        elif self.err_style == "bars":
+            pass
+        elif self.err_style is not None:
+            err = "`err_style` must be 'band' or 'bars', not {}"
+            raise ValueError(err.format(self.err_style))
+
+        # Initialize the aggregation object
+        agg = EstimateAggregator(
+            self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,
+        )
+
+        # TODO abstract variable to aggregate over here-ish. Better name?
+        orient = self.orient
+        if orient not in {"x", "y"}:
+            err = f"`orient` must be either 'x' or 'y', not {orient!r}."
+            raise ValueError(err)
+        other = {"x": "y", "y": "x"}[orient]
+
+        # TODO How to handle NA? We don't want NA to propagate through to the
+        # estimate/CI when some values are present, but we would also like
+        # matplotlib to show "gaps" in the line when all values are missing.
+        # This is straightforward absent aggregation, but complicated with it.
+        # If we want to use nas, we need to conditionalize dropna in iter_data.
+
+        # Loop over the semantic subsets and add to the plot
+        grouping_vars = "hue", "size", "style"
+        for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):
+
+            if self.sort:
+                sort_vars = ["units", orient, other]
+                sort_cols = [var for var in sort_vars if var in self.variables]
+                sub_data = sub_data.sort_values(sort_cols)
+
+            if (
+                self.estimator is not None
+                and sub_data[orient].value_counts().max() > 1
+            ):
+                if "units" in self.variables:
+                    # TODO eventually relax this constraint
+                    err = "estimator must be None when specifying units"
+                    raise ValueError(err)
+                grouped = sub_data.groupby(orient, sort=self.sort)
+                # Could pass as_index=False instead of reset_index,
+                # but that fails on a corner case with older pandas.
+                sub_data = grouped.apply(agg, other).reset_index()
+            else:
+                sub_data[f"{other}min"] = np.nan
+                sub_data[f"{other}max"] = np.nan
+
+            # TODO this is pretty ad hoc ; see GH2409
+            for var in "xy":
+                if self._log_scaled(var):
+                    for col in sub_data.filter(regex=f"^{var}"):
+                        sub_data[col] = np.power(10, sub_data[col])
+
+            # --- Draw the main line(s)
+
+            if "units" in self.variables:   # XXX why not add to grouping variables?
+                lines = []
+                for _, unit_data in sub_data.groupby("units"):
+                    lines.extend(ax.plot(unit_data["x"], unit_data["y"], **kws))
+            else:
+                lines = ax.plot(sub_data["x"], sub_data["y"], **kws)
+
+            for line in lines:
+
+                if "hue" in sub_vars:
+                    line.set_color(self._hue_map(sub_vars["hue"]))
+
+                if "size" in sub_vars:
+                    line.set_linewidth(self._size_map(sub_vars["size"]))
+
+                if "style" in sub_vars:
+                    attributes = self._style_map(sub_vars["style"])
+                    if "dashes" in attributes:
+                        line.set_dashes(attributes["dashes"])
+                    if "marker" in attributes:
+                        line.set_marker(attributes["marker"])
+
+            line_color = line.get_color()
+            line_alpha = line.get_alpha()
+            line_capstyle = line.get_solid_capstyle()
+
+            # --- Draw the confidence intervals
+
+            if self.estimator is not None and self.errorbar is not None:
+
+                # TODO handling of orientation will need to happen here
+
+                if self.err_style == "band":
+
+                    func = {"x": ax.fill_between, "y": ax.fill_betweenx}[orient]
+                    func(
+                        sub_data[orient],
+                        sub_data[f"{other}min"], sub_data[f"{other}max"],
+                        color=line_color, **err_kws
+                    )
+
+                elif self.err_style == "bars":
+
+                    error_param = {
+                        f"{other}err": (
+                            sub_data[other] - sub_data[f"{other}min"],
+                            sub_data[f"{other}max"] - sub_data[other],
+                        )
+                    }
+                    ebars = ax.errorbar(
+                        sub_data["x"], sub_data["y"], **error_param,
+                        linestyle="", color=line_color, alpha=line_alpha,
+                        **err_kws
+                    )
+
+                    # Set the capstyle properly on the error bars
+                    for obj in ebars.get_children():
+                        if isinstance(obj, mpl.collections.LineCollection):
+                            obj.set_capstyle(line_capstyle)
+
+        # Finalize the axes details
+        self._add_axis_labels(ax)
+        if self.legend:
+            self.add_legend_data(ax)
+            handles, _ = ax.get_legend_handles_labels()
+            if handles:
+                legend = ax.legend(title=self.legend_title)
+                adjust_legend_subtitles(legend)
+
+
+class _ScatterPlotter(_RelationalPlotter):
+
+    _legend_attributes = ["color", "s", "marker"]
+    _legend_func = "scatter"
+
+    def __init__(self, *, data=None, variables={}, legend=None):
+
+        # TODO this is messy, we want the mapping to be agnostic about
+        # the kind of plot to draw, but for the time being we need to set
+        # this information so the SizeMapping can use it
+        self._default_size_range = (
+            np.r_[.5, 2] * np.square(mpl.rcParams["lines.markersize"])
+        )
+
+        super().__init__(data=data, variables=variables)
+
+        self.legend = legend
+
+    def plot(self, ax, kws):
+
+        # --- Determine the visual attributes of the plot
+
+        data = self.plot_data.dropna()
+        if data.empty:
+            return
+
+        # Define the vectors of x and y positions
+        empty = np.full(len(data), np.nan)
+        x = data.get("x", empty)
+        y = data.get("y", empty)
+
+        if "style" in self.variables:
+            # Use a representative marker so scatter sets the edgecolor
+            # properly for line art markers. We currently enforce either
+            # all or none line art so this works.
+            example_level = self._style_map.levels[0]
+            example_marker = self._style_map(example_level, "marker")
+            kws.setdefault("marker", example_marker)
+
+        # Conditionally set the marker edgecolor based on whether the marker is "filled"
+        # See https://github.com/matplotlib/matplotlib/issues/17849 for context
+        m = kws.get("marker", mpl.rcParams.get("marker", "o"))
+        if not isinstance(m, mpl.markers.MarkerStyle):
+            # TODO in more recent matplotlib (which?) can pass a MarkerStyle here
+            m = mpl.markers.MarkerStyle(m)
+        if m.is_filled():
+            kws.setdefault("edgecolor", "w")
+
+        # Draw the scatter plot
+        points = ax.scatter(x=x, y=y, **kws)
+
+        # Apply the mapping from semantic variables to artist attributes
+
+        if "hue" in self.variables:
+            points.set_facecolors(self._hue_map(data["hue"]))
+
+        if "size" in self.variables:
+            points.set_sizes(self._size_map(data["size"]))
+
+        if "style" in self.variables:
+            p = [self._style_map(val, "path") for val in data["style"]]
+            points.set_paths(p)
+
+        # Apply dependent default attributes
+
+        if "linewidth" not in kws:
+            sizes = points.get_sizes()
+            points.set_linewidths(.08 * np.sqrt(np.percentile(sizes, 10)))
+
+        # Finalize the axes details
+        self._add_axis_labels(ax)
+        if self.legend:
+            self.add_legend_data(ax)
+            handles, _ = ax.get_legend_handles_labels()
+            if handles:
+                legend = ax.legend(title=self.legend_title)
+                adjust_legend_subtitles(legend)
+
+
+def lineplot(
+    data=None, *,
+    x=None, y=None, hue=None, size=None, style=None, units=None,
+    palette=None, hue_order=None, hue_norm=None,
+    sizes=None, size_order=None, size_norm=None,
+    dashes=True, markers=None, style_order=None,
+    estimator="mean", errorbar=("ci", 95), n_boot=1000, seed=None,
+    orient="x", sort=True, err_style="band", err_kws=None,
+    legend="auto", ci="deprecated", ax=None, **kwargs
+):
+
+    # Handle deprecation of ci parameter
+    errorbar = _deprecate_ci(errorbar, ci)
+
+    variables = _LinePlotter.get_semantics(locals())
+    p = _LinePlotter(
+        data=data, variables=variables,
+        estimator=estimator, n_boot=n_boot, seed=seed, errorbar=errorbar,
+        sort=sort, orient=orient, err_style=err_style, err_kws=err_kws,
+        legend=legend,
+    )
+
+    p.map_hue(palette=palette, order=hue_order, norm=hue_norm)
+    p.map_size(sizes=sizes, order=size_order, norm=size_norm)
+    p.map_style(markers=markers, dashes=dashes, order=style_order)
+
+    if ax is None:
+        ax = plt.gca()
+
+    if style is None and not {"ls", "linestyle"} & set(kwargs):  # XXX
+        kwargs["dashes"] = "" if dashes is None or isinstance(dashes, bool) else dashes
+
+    if not p.has_xy_data:
+        return ax
+
+    p._attach(ax)
+
+    # Other functions have color as an explicit param,
+    # and we should probably do that here too
+    color = kwargs.pop("color", kwargs.pop("c", None))
+    kwargs["color"] = _default_color(ax.plot, hue, color, kwargs)
+
+    p.plot(ax, kwargs)
+    return ax
+
+
+lineplot.__doc__ = """\
+Draw a line plot with possibility of several semantic groupings.
+
+{narrative.main_api}
+
+{narrative.relational_semantic}
+
+By default, the plot aggregates over multiple `y` values at each value of
+`x` and shows an estimate of the central tendency and a confidence
+interval for that estimate.
+
+Parameters
+----------
+{params.core.data}
+{params.core.xy}
+hue : vector or key in `data`
+    Grouping variable that will produce lines with different colors.
+    Can be either categorical or numeric, although color mapping will
+    behave differently in latter case.
+size : vector or key in `data`
+    Grouping variable that will produce lines with different widths.
+    Can be either categorical or numeric, although size mapping will
+    behave differently in latter case.
+style : vector or key in `data`
+    Grouping variable that will produce lines with different dashes
+    and/or markers. Can have a numeric dtype but will always be treated
+    as categorical.
+{params.rel.units}
+{params.core.palette}
+{params.core.hue_order}
+{params.core.hue_norm}
+{params.rel.sizes}
+{params.rel.size_order}
+{params.rel.size_norm}
+{params.rel.dashes}
+{params.rel.markers}
+{params.rel.style_order}
+{params.rel.estimator}
+{params.stat.errorbar}
+{params.rel.n_boot}
+{params.rel.seed}
+orient : "x" or "y"
+    Dimension along which the data are sorted / aggregated. Equivalently,
+    the "independent variable" of the resulting function.
+sort : boolean
+    If True, the data will be sorted by the x and y variables, otherwise
+    lines will connect points in the order they appear in the dataset.
+err_style : "band" or "bars"
+    Whether to draw the confidence intervals with translucent error bands
+    or discrete error bars.
+err_kws : dict of keyword arguments
+    Additional parameters to control the aesthetics of the error bars. The
+    kwargs are passed either to :meth:`matplotlib.axes.Axes.fill_between`
+    or :meth:`matplotlib.axes.Axes.errorbar`, depending on `err_style`.
+{params.rel.legend}
+{params.rel.ci}
+{params.core.ax}
+kwargs : key, value mappings
+    Other keyword arguments are passed down to
+    :meth:`matplotlib.axes.Axes.plot`.
+
+Returns
+-------
+{returns.ax}
+
+See Also
+--------
+{seealso.scatterplot}
+{seealso.pointplot}
+
+Examples
+--------
+
+.. include:: ../docstrings/lineplot.rst
+
+""".format(
+    narrative=_relational_narrative,
+    params=_param_docs,
+    returns=_core_docs["returns"],
+    seealso=_core_docs["seealso"],
+)
+
+
+def scatterplot(
+    data=None, *,
+    x=None, y=None, hue=None, size=None, style=None,
+    palette=None, hue_order=None, hue_norm=None,
+    sizes=None, size_order=None, size_norm=None,
+    markers=True, style_order=None, legend="auto", ax=None,
+    **kwargs
+):
+
+    variables = _ScatterPlotter.get_semantics(locals())
+    p = _ScatterPlotter(data=data, variables=variables, legend=legend)
+
+    p.map_hue(palette=palette, order=hue_order, norm=hue_norm)
+    p.map_size(sizes=sizes, order=size_order, norm=size_norm)
+    p.map_style(markers=markers, order=style_order)
+
+    if ax is None:
+        ax = plt.gca()
+
+    if not p.has_xy_data:
+        return ax
+
+    p._attach(ax)
+
+    # Other functions have color as an explicit param,
+    # and we should probably do that here too
+    color = kwargs.pop("color", None)
+    kwargs["color"] = _default_color(ax.scatter, hue, color, kwargs)
+
+    p.plot(ax, kwargs)
+
+    return ax
+
+
+scatterplot.__doc__ = """\
+Draw a scatter plot with possibility of several semantic groupings.
+
+{narrative.main_api}
+
+{narrative.relational_semantic}
+
+Parameters
+----------
+{params.core.data}
+{params.core.xy}
+hue : vector or key in `data`
+    Grouping variable that will produce points with different colors.
+    Can be either categorical or numeric, although color mapping will
+    behave differently in latter case.
+size : vector or key in `data`
+    Grouping variable that will produce points with different sizes.
+    Can be either categorical or numeric, although size mapping will
+    behave differently in latter case.
+style : vector or key in `data`
+    Grouping variable that will produce points with different markers.
+    Can have a numeric dtype but will always be treated as categorical.
+{params.core.palette}
+{params.core.hue_order}
+{params.core.hue_norm}
+{params.rel.sizes}
+{params.rel.size_order}
+{params.rel.size_norm}
+{params.rel.markers}
+{params.rel.style_order}
+{params.rel.legend}
+{params.core.ax}
+kwargs : key, value mappings
+    Other keyword arguments are passed down to
+    :meth:`matplotlib.axes.Axes.scatter`.
+
+Returns
+-------
+{returns.ax}
+
+See Also
+--------
+{seealso.lineplot}
+{seealso.stripplot}
+{seealso.swarmplot}
+
+Examples
+--------
+
+.. include:: ../docstrings/scatterplot.rst
+
+""".format(
+    narrative=_relational_narrative,
+    params=_param_docs,
+    returns=_core_docs["returns"],
+    seealso=_core_docs["seealso"],
+)
+
+
+def relplot(
+    data=None, *,
+    x=None, y=None, hue=None, size=None, style=None, units=None,
+    row=None, col=None, col_wrap=None, row_order=None, col_order=None,
+    palette=None, hue_order=None, hue_norm=None,
+    sizes=None, size_order=None, size_norm=None,
+    markers=None, dashes=None, style_order=None,
+    legend="auto", kind="scatter", height=5, aspect=1, facet_kws=None,
+    **kwargs
+):
+
+    if kind == "scatter":
+
+        plotter = _ScatterPlotter
+        func = scatterplot
+        markers = True if markers is None else markers
+
+    elif kind == "line":
+
+        plotter = _LinePlotter
+        func = lineplot
+        dashes = True if dashes is None else dashes
+
+    else:
+        err = f"Plot kind {kind} not recognized"
+        raise ValueError(err)
+
+    # Check for attempt to plot onto specific axes and warn
+    if "ax" in kwargs:
+        msg = (
+            "relplot is a figure-level function and does not accept "
+            "the `ax` parameter. You may wish to try {}".format(kind + "plot")
+        )
+        warnings.warn(msg, UserWarning)
+        kwargs.pop("ax")
+
+    # Use the full dataset to map the semantics
+    p = plotter(
+        data=data,
+        variables=plotter.get_semantics(locals()),
+        legend=legend,
+    )
+    p.map_hue(palette=palette, order=hue_order, norm=hue_norm)
+    p.map_size(sizes=sizes, order=size_order, norm=size_norm)
+    p.map_style(markers=markers, dashes=dashes, order=style_order)
+
+    # Extract the semantic mappings
+    if "hue" in p.variables:
+        palette = p._hue_map.lookup_table
+        hue_order = p._hue_map.levels
+        hue_norm = p._hue_map.norm
+    else:
+        palette = hue_order = hue_norm = None
+
+    if "size" in p.variables:
+        sizes = p._size_map.lookup_table
+        size_order = p._size_map.levels
+        size_norm = p._size_map.norm
+
+    if "style" in p.variables:
+        style_order = p._style_map.levels
+        if markers:
+            markers = {k: p._style_map(k, "marker") for k in style_order}
+        else:
+            markers = None
+        if dashes:
+            dashes = {k: p._style_map(k, "dashes") for k in style_order}
+        else:
+            dashes = None
+    else:
+        markers = dashes = style_order = None
+
+    # Now extract the data that would be used to draw a single plot
+    variables = p.variables
+    plot_data = p.plot_data
+    plot_semantics = p.semantics
+
+    # Define the common plotting parameters
+    plot_kws = dict(
+        palette=palette, hue_order=hue_order, hue_norm=hue_norm,
+        sizes=sizes, size_order=size_order, size_norm=size_norm,
+        markers=markers, dashes=dashes, style_order=style_order,
+        legend=False,
+    )
+    plot_kws.update(kwargs)
+    if kind == "scatter":
+        plot_kws.pop("dashes")
+
+    # Add the grid semantics onto the plotter
+    grid_semantics = "row", "col"
+    p.semantics = plot_semantics + grid_semantics
+    p.assign_variables(
+        data=data,
+        variables=dict(
+            x=x, y=y,
+            hue=hue, size=size, style=style, units=units,
+            row=row, col=col,
+        ),
+    )
+
+    # Define the named variables for plotting on each facet
+    # Rename the variables with a leading underscore to avoid
+    # collisions with faceting variable names
+    plot_variables = {v: f"_{v}" for v in variables}
+    plot_kws.update(plot_variables)
+
+    # Pass the row/col variables to FacetGrid with their original
+    # names so that the axes titles render correctly
+    for var in ["row", "col"]:
+        # Handle faceting variables that lack name information
+        if var in p.variables and p.variables[var] is None:
+            p.variables[var] = f"_{var}_"
+    grid_kws = {v: p.variables.get(v) for v in grid_semantics}
+
+    # Rename the columns of the plot_data structure appropriately
+    new_cols = plot_variables.copy()
+    new_cols.update(grid_kws)
+    full_data = p.plot_data.rename(columns=new_cols)
+
+    # Set up the FacetGrid object
+    facet_kws = {} if facet_kws is None else facet_kws.copy()
+    g = FacetGrid(
+        data=full_data.dropna(axis=1, how="all"),
+        **grid_kws,
+        col_wrap=col_wrap, row_order=row_order, col_order=col_order,
+        height=height, aspect=aspect, dropna=False,
+        **facet_kws
+    )
+
+    # Draw the plot
+    g.map_dataframe(func, **plot_kws)
+
+    # Label the axes, using the original variables
+    # Pass "" when the variable name is None to overwrite internal variables
+    g.set_axis_labels(variables.get("x") or "", variables.get("y") or "")
+
+    # Show the legend
+    if legend:
+        # Replace the original plot data so the legend uses
+        # numeric data with the correct type
+        p.plot_data = plot_data
+        p.add_legend_data(g.axes.flat[0])
+        if p.legend_data:
+            g.add_legend(legend_data=p.legend_data,
+                         label_order=p.legend_order,
+                         title=p.legend_title,
+                         adjust_subtitles=True)
+
+    # Rename the columns of the FacetGrid's `data` attribute
+    # to match the original column names
+    orig_cols = {
+        f"_{k}": f"_{k}_" if v is None else v for k, v in variables.items()
+    }
+    grid_data = g.data.rename(columns=orig_cols)
+    if data is not None and (x is not None or y is not None):
+        if not isinstance(data, pd.DataFrame):
+            data = pd.DataFrame(data)
+        g.data = pd.merge(
+            data,
+            grid_data[grid_data.columns.difference(data.columns)],
+            left_index=True,
+            right_index=True,
+        )
+    else:
+        g.data = grid_data
+
+    return g
+
+
+relplot.__doc__ = """\
+Figure-level interface for drawing relational plots onto a FacetGrid.
+
+This function provides access to several different axes-level functions
+that show the relationship between two variables with semantic mappings
+of subsets. The `kind` parameter selects the underlying axes-level
+function to use:
+
+- :func:`scatterplot` (with `kind="scatter"`; the default)
+- :func:`lineplot` (with `kind="line"`)
+
+Extra keyword arguments are passed to the underlying function, so you
+should refer to the documentation for each to see kind-specific options.
+
+{narrative.main_api}
+
+{narrative.relational_semantic}
+
+After plotting, the :class:`FacetGrid` with the plot is returned and can
+be used directly to tweak supporting plot details or add other layers.
+
+Parameters
+----------
+{params.core.data}
+{params.core.xy}
+hue : vector or key in `data`
+    Grouping variable that will produce elements with different colors.
+    Can be either categorical or numeric, although color mapping will
+    behave differently in latter case.
+size : vector or key in `data`
+    Grouping variable that will produce elements with different sizes.
+    Can be either categorical or numeric, although size mapping will
+    behave differently in latter case.
+style : vector or key in `data`
+    Grouping variable that will produce elements with different styles.
+    Can have a numeric dtype but will always be treated as categorical.
+{params.rel.units}
+{params.facets.rowcol}
+{params.facets.col_wrap}
+row_order, col_order : lists of strings
+    Order to organize the rows and/or columns of the grid in, otherwise the
+    orders are inferred from the data objects.
+{params.core.palette}
+{params.core.hue_order}
+{params.core.hue_norm}
+{params.rel.sizes}
+{params.rel.size_order}
+{params.rel.size_norm}
+{params.rel.style_order}
+{params.rel.dashes}
+{params.rel.markers}
+{params.rel.legend}
+kind : string
+    Kind of plot to draw, corresponding to a seaborn relational plot.
+    Options are `"scatter"` or `"line"`.
+{params.facets.height}
+{params.facets.aspect}
+facet_kws : dict
+    Dictionary of other keyword arguments to pass to :class:`FacetGrid`.
+kwargs : key, value pairings
+    Other keyword arguments are passed through to the underlying plotting
+    function.
+
+Returns
+-------
+{returns.facetgrid}
+
+Examples
+--------
+
+.. include:: ../docstrings/relplot.rst
+
+""".format(
+    narrative=_relational_narrative,
+    params=_param_docs,
+    returns=_core_docs["returns"],
+    seealso=_core_docs["seealso"],
+)
diff --git a/testbed/mwaskom__seaborn/seaborn/utils.py b/testbed/mwaskom__seaborn/seaborn/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f8387769ce74667b95f6ef497e1e9c6ae60f721
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/utils.py
@@ -0,0 +1,869 @@
+"""Utility functions, mostly for internal use."""
+import os
+import re
+import inspect
+import warnings
+import colorsys
+from contextlib import contextmanager
+from urllib.request import urlopen, urlretrieve
+from types import ModuleType
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+from matplotlib.colors import to_rgb
+import matplotlib.pyplot as plt
+from matplotlib.cbook import normalize_kwargs
+
+from seaborn.external.version import Version
+from seaborn.external.appdirs import user_cache_dir
+
+__all__ = ["desaturate", "saturate", "set_hls_values", "move_legend",
+           "despine", "get_dataset_names", "get_data_home", "load_dataset"]
+
+
+def ci_to_errsize(cis, heights):
+    """Convert intervals to error arguments relative to plot heights.
+
+    Parameters
+    ----------
+    cis : 2 x n sequence
+        sequence of confidence interval limits
+    heights : n sequence
+        sequence of plot heights
+
+    Returns
+    -------
+    errsize : 2 x n array
+        sequence of error size relative to height values in correct
+        format as argument for plt.bar
+
+    """
+    cis = np.atleast_2d(cis).reshape(2, -1)
+    heights = np.atleast_1d(heights)
+    errsize = []
+    for i, (low, high) in enumerate(np.transpose(cis)):
+        h = heights[i]
+        elow = h - low
+        ehigh = high - h
+        errsize.append([elow, ehigh])
+
+    errsize = np.asarray(errsize).T
+    return errsize
+
+
+def _normal_quantile_func(q):
+    """
+    Compute the quantile function of the standard normal distribution.
+
+    This wrapper exists because we are dropping scipy as a mandatory dependency
+    but statistics.NormalDist was added to the standard library in 3.8.
+
+    """
+    try:
+        from statistics import NormalDist
+        qf = np.vectorize(NormalDist().inv_cdf)
+    except ImportError:
+        try:
+            from scipy.stats import norm
+            qf = norm.ppf
+        except ImportError:
+            msg = (
+                "Standard normal quantile functions require either Python>=3.8 or scipy"
+            )
+            raise RuntimeError(msg)
+    return qf(q)
+
+
+def _draw_figure(fig):
+    """Force draw of a matplotlib figure, accounting for back-compat."""
+    # See https://github.com/matplotlib/matplotlib/issues/19197 for context
+    fig.canvas.draw()
+    if fig.stale:
+        try:
+            fig.draw(fig.canvas.get_renderer())
+        except AttributeError:
+            pass
+
+
+def _default_color(method, hue, color, kws):
+    """If needed, get a default color by using the matplotlib property cycle."""
+
+    if hue is not None:
+        # This warning is probably user-friendly, but it's currently triggered
+        # in a FacetGrid context and I don't want to mess with that logic right now
+        #  if color is not None:
+        #      msg = "`color` is ignored when `hue` is assigned."
+        #      warnings.warn(msg)
+        return None
+
+    kws = kws.copy()
+    kws.pop("label", None)
+
+    if color is not None:
+        return color
+
+    elif method.__name__ == "plot":
+
+        color = _normalize_kwargs(kws, mpl.lines.Line2D).get("color")
+        scout, = method([], [], scalex=False, scaley=False, color=color)
+        color = scout.get_color()
+        scout.remove()
+
+    elif method.__name__ == "scatter":
+
+        # Matplotlib will raise if the size of x/y don't match s/c,
+        # and the latter might be in the kws dict
+        scout_size = max(
+            np.atleast_1d(kws.get(key, [])).shape[0]
+            for key in ["s", "c", "fc", "facecolor", "facecolors"]
+        )
+        scout_x = scout_y = np.full(scout_size, np.nan)
+
+        scout = method(scout_x, scout_y, **kws)
+        facecolors = scout.get_facecolors()
+
+        if not len(facecolors):
+            # Handle bug in matplotlib <= 3.2 (I think)
+            # This will limit the ability to use non color= kwargs to specify
+            # a color in versions of matplotlib with the bug, but trying to
+            # work out what the user wanted by re-implementing the broken logic
+            # of inspecting the kwargs is probably too brittle.
+            single_color = False
+        else:
+            single_color = np.unique(facecolors, axis=0).shape[0] == 1
+
+        # Allow the user to specify an array of colors through various kwargs
+        if "c" not in kws and single_color:
+            color = to_rgb(facecolors[0])
+
+        scout.remove()
+
+    elif method.__name__ == "bar":
+
+        # bar() needs masked, not empty data, to generate a patch
+        scout, = method([np.nan], [np.nan], **kws)
+        color = to_rgb(scout.get_facecolor())
+        scout.remove()
+
+    elif method.__name__ == "fill_between":
+
+        kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)
+        scout = method([], [], **kws)
+        facecolor = scout.get_facecolor()
+        color = to_rgb(facecolor[0])
+        scout.remove()
+
+    return color
+
+
+def desaturate(color, prop):
+    """Decrease the saturation channel of a color by some percent.
+
+    Parameters
+    ----------
+    color : matplotlib color
+        hex, rgb-tuple, or html color name
+    prop : float
+        saturation channel of color will be multiplied by this value
+
+    Returns
+    -------
+    new_color : rgb tuple
+        desaturated color code in RGB tuple representation
+
+    """
+    # Check inputs
+    if not 0 <= prop <= 1:
+        raise ValueError("prop must be between 0 and 1")
+
+    # Get rgb tuple rep
+    rgb = to_rgb(color)
+
+    # Convert to hls
+    h, l, s = colorsys.rgb_to_hls(*rgb)
+
+    # Desaturate the saturation channel
+    s *= prop
+
+    # Convert back to rgb
+    new_color = colorsys.hls_to_rgb(h, l, s)
+
+    return new_color
+
+
+def saturate(color):
+    """Return a fully saturated color with the same hue.
+
+    Parameters
+    ----------
+    color : matplotlib color
+        hex, rgb-tuple, or html color name
+
+    Returns
+    -------
+    new_color : rgb tuple
+        saturated color code in RGB tuple representation
+
+    """
+    return set_hls_values(color, s=1)
+
+
+def set_hls_values(color, h=None, l=None, s=None):  # noqa
+    """Independently manipulate the h, l, or s channels of a color.
+
+    Parameters
+    ----------
+    color : matplotlib color
+        hex, rgb-tuple, or html color name
+    h, l, s : floats between 0 and 1, or None
+        new values for each channel in hls space
+
+    Returns
+    -------
+    new_color : rgb tuple
+        new color code in RGB tuple representation
+
+    """
+    # Get an RGB tuple representation
+    rgb = to_rgb(color)
+    vals = list(colorsys.rgb_to_hls(*rgb))
+    for i, val in enumerate([h, l, s]):
+        if val is not None:
+            vals[i] = val
+
+    rgb = colorsys.hls_to_rgb(*vals)
+    return rgb
+
+
+def axlabel(xlabel, ylabel, **kwargs):
+    """Grab current axis and label it.
+
+    DEPRECATED: will be removed in a future version.
+
+    """
+    msg = "This function is deprecated and will be removed in a future version"
+    warnings.warn(msg, FutureWarning)
+    ax = plt.gca()
+    ax.set_xlabel(xlabel, **kwargs)
+    ax.set_ylabel(ylabel, **kwargs)
+
+
+def remove_na(vector):
+    """Helper method for removing null values from data vectors.
+
+    Parameters
+    ----------
+    vector : vector object
+        Must implement boolean masking with [] subscript syntax.
+
+    Returns
+    -------
+    clean_clean : same type as ``vector``
+        Vector of data with null values removed. May be a copy or a view.
+
+    """
+    return vector[pd.notnull(vector)]
+
+
+def get_color_cycle():
+    """Return the list of colors in the current matplotlib color cycle
+
+    Parameters
+    ----------
+    None
+
+    Returns
+    -------
+    colors : list
+        List of matplotlib colors in the current cycle, or dark gray if
+        the current color cycle is empty.
+    """
+    cycler = mpl.rcParams['axes.prop_cycle']
+    return cycler.by_key()['color'] if 'color' in cycler.keys else [".15"]
+
+
+def despine(fig=None, ax=None, top=True, right=True, left=False,
+            bottom=False, offset=None, trim=False):
+    """Remove the top and right spines from plot(s).
+
+    fig : matplotlib figure, optional
+        Figure to despine all axes of, defaults to the current figure.
+    ax : matplotlib axes, optional
+        Specific axes object to despine. Ignored if fig is provided.
+    top, right, left, bottom : boolean, optional
+        If True, remove that spine.
+    offset : int or dict, optional
+        Absolute distance, in points, spines should be moved away
+        from the axes (negative values move spines inward). A single value
+        applies to all spines; a dict can be used to set offset values per
+        side.
+    trim : bool, optional
+        If True, limit spines to the smallest and largest major tick
+        on each non-despined axis.
+
+    Returns
+    -------
+    None
+
+    """
+    # Get references to the axes we want
+    if fig is None and ax is None:
+        axes = plt.gcf().axes
+    elif fig is not None:
+        axes = fig.axes
+    elif ax is not None:
+        axes = [ax]
+
+    for ax_i in axes:
+        for side in ["top", "right", "left", "bottom"]:
+            # Toggle the spine objects
+            is_visible = not locals()[side]
+            ax_i.spines[side].set_visible(is_visible)
+            if offset is not None and is_visible:
+                try:
+                    val = offset.get(side, 0)
+                except AttributeError:
+                    val = offset
+                ax_i.spines[side].set_position(('outward', val))
+
+        # Potentially move the ticks
+        if left and not right:
+            maj_on = any(
+                t.tick1line.get_visible()
+                for t in ax_i.yaxis.majorTicks
+            )
+            min_on = any(
+                t.tick1line.get_visible()
+                for t in ax_i.yaxis.minorTicks
+            )
+            ax_i.yaxis.set_ticks_position("right")
+            for t in ax_i.yaxis.majorTicks:
+                t.tick2line.set_visible(maj_on)
+            for t in ax_i.yaxis.minorTicks:
+                t.tick2line.set_visible(min_on)
+
+        if bottom and not top:
+            maj_on = any(
+                t.tick1line.get_visible()
+                for t in ax_i.xaxis.majorTicks
+            )
+            min_on = any(
+                t.tick1line.get_visible()
+                for t in ax_i.xaxis.minorTicks
+            )
+            ax_i.xaxis.set_ticks_position("top")
+            for t in ax_i.xaxis.majorTicks:
+                t.tick2line.set_visible(maj_on)
+            for t in ax_i.xaxis.minorTicks:
+                t.tick2line.set_visible(min_on)
+
+        if trim:
+            # clip off the parts of the spines that extend past major ticks
+            xticks = np.asarray(ax_i.get_xticks())
+            if xticks.size:
+                firsttick = np.compress(xticks >= min(ax_i.get_xlim()),
+                                        xticks)[0]
+                lasttick = np.compress(xticks <= max(ax_i.get_xlim()),
+                                       xticks)[-1]
+                ax_i.spines['bottom'].set_bounds(firsttick, lasttick)
+                ax_i.spines['top'].set_bounds(firsttick, lasttick)
+                newticks = xticks.compress(xticks <= lasttick)
+                newticks = newticks.compress(newticks >= firsttick)
+                ax_i.set_xticks(newticks)
+
+            yticks = np.asarray(ax_i.get_yticks())
+            if yticks.size:
+                firsttick = np.compress(yticks >= min(ax_i.get_ylim()),
+                                        yticks)[0]
+                lasttick = np.compress(yticks <= max(ax_i.get_ylim()),
+                                       yticks)[-1]
+                ax_i.spines['left'].set_bounds(firsttick, lasttick)
+                ax_i.spines['right'].set_bounds(firsttick, lasttick)
+                newticks = yticks.compress(yticks <= lasttick)
+                newticks = newticks.compress(newticks >= firsttick)
+                ax_i.set_yticks(newticks)
+
+
+def move_legend(obj, loc, **kwargs):
+    """
+    Recreate a plot's legend at a new location.
+
+    The name is a slight misnomer. Matplotlib legends do not expose public
+    control over their position parameters. So this function creates a new legend,
+    copying over the data from the original object, which is then removed.
+
+    Parameters
+    ----------
+    obj : the object with the plot
+        This argument can be either a seaborn or matplotlib object:
+
+        - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`
+        - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`
+
+    loc : str or int
+        Location argument, as in :meth:`matplotlib.axes.Axes.legend`.
+
+    kwargs
+        Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.
+
+    Examples
+    --------
+
+    .. include:: ../docstrings/move_legend.rst
+
+    """
+    # This is a somewhat hackish solution that will hopefully be obviated by
+    # upstream improvements to matplotlib legends that make them easier to
+    # modify after creation.
+
+    from seaborn.axisgrid import Grid  # Avoid circular import
+
+    # Locate the legend object and a method to recreate the legend
+    if isinstance(obj, Grid):
+        old_legend = obj.legend
+        legend_func = obj.figure.legend
+    elif isinstance(obj, mpl.axes.Axes):
+        old_legend = obj.legend_
+        legend_func = obj.legend
+    elif isinstance(obj, mpl.figure.Figure):
+        if obj.legends:
+            old_legend = obj.legends[-1]
+        else:
+            old_legend = None
+        legend_func = obj.legend
+    else:
+        err = "`obj` must be a seaborn Grid or matplotlib Axes or Figure instance."
+        raise TypeError(err)
+
+    if old_legend is None:
+        err = f"{obj} has no legend attached."
+        raise ValueError(err)
+
+    # Extract the components of the legend we need to reuse
+    handles = old_legend.legendHandles
+    labels = [t.get_text() for t in old_legend.get_texts()]
+
+    # Extract legend properties that can be passed to the recreation method
+    # (Vexingly, these don't all round-trip)
+    legend_kws = inspect.signature(mpl.legend.Legend).parameters
+    props = {k: v for k, v in old_legend.properties().items() if k in legend_kws}
+
+    # Delegate default bbox_to_anchor rules to matplotlib
+    props.pop("bbox_to_anchor")
+
+    # Try to propagate the existing title and font properties; respect new ones too
+    title = props.pop("title")
+    if "title" in kwargs:
+        title.set_text(kwargs.pop("title"))
+    title_kwargs = {k: v for k, v in kwargs.items() if k.startswith("title_")}
+    for key, val in title_kwargs.items():
+        title.set(**{key[6:]: val})
+        kwargs.pop(key)
+
+    # Try to respect the frame visibility
+    kwargs.setdefault("frameon", old_legend.legendPatch.get_visible())
+
+    # Remove the old legend and create the new one
+    props.update(kwargs)
+    old_legend.remove()
+    new_legend = legend_func(handles, labels, loc=loc, **props)
+    new_legend.set_title(title.get_text(), title.get_fontproperties())
+
+    # Let the Grid object continue to track the correct legend object
+    if isinstance(obj, Grid):
+        obj._legend = new_legend
+
+
+def _kde_support(data, bw, gridsize, cut, clip):
+    """Establish support for a kernel density estimate."""
+    support_min = max(data.min() - bw * cut, clip[0])
+    support_max = min(data.max() + bw * cut, clip[1])
+    support = np.linspace(support_min, support_max, gridsize)
+
+    return support
+
+
+def ci(a, which=95, axis=None):
+    """Return a percentile range from an array of values."""
+    p = 50 - which / 2, 50 + which / 2
+    return np.nanpercentile(a, p, axis)
+
+
+def get_dataset_names():
+    """Report available example datasets, useful for reporting issues.
+
+    Requires an internet connection.
+
+    """
+    url = "https://github.com/mwaskom/seaborn-data"
+    with urlopen(url) as resp:
+        html = resp.read()
+
+    pat = r"/mwaskom/seaborn-data/blob/master/(\w*).csv"
+    datasets = re.findall(pat, html.decode())
+    return datasets
+
+
+def get_data_home(data_home=None):
+    """Return a path to the cache directory for example datasets.
+
+    This directory is used by :func:`load_dataset`.
+
+    If the ``data_home`` argument is not provided, it will use a directory
+    specified by the `SEABORN_DATA` environment variable (if it exists)
+    or otherwise default to an OS-appropriate user cache location.
+
+    """
+    if data_home is None:
+        data_home = os.environ.get("SEABORN_DATA", user_cache_dir("seaborn"))
+    data_home = os.path.expanduser(data_home)
+    if not os.path.exists(data_home):
+        os.makedirs(data_home)
+    return data_home
+
+
+def load_dataset(name, cache=True, data_home=None, **kws):
+    """Load an example dataset from the online repository (requires internet).
+
+    This function provides quick access to a small number of example datasets
+    that are useful for documenting seaborn or generating reproducible examples
+    for bug reports. It is not necessary for normal usage.
+
+    Note that some of the datasets have a small amount of preprocessing applied
+    to define a proper ordering for categorical variables.
+
+    Use :func:`get_dataset_names` to see a list of available datasets.
+
+    Parameters
+    ----------
+    name : str
+        Name of the dataset (``{name}.csv`` on
+        https://github.com/mwaskom/seaborn-data).
+    cache : boolean, optional
+        If True, try to load from the local cache first, and save to the cache
+        if a download is required.
+    data_home : string, optional
+        The directory in which to cache data; see :func:`get_data_home`.
+    kws : keys and values, optional
+        Additional keyword arguments are passed to passed through to
+        :func:`pandas.read_csv`.
+
+    Returns
+    -------
+    df : :class:`pandas.DataFrame`
+        Tabular data, possibly with some preprocessing applied.
+
+    """
+    # A common beginner mistake is to assume that one's personal data needs
+    # to be passed through this function to be usable with seaborn.
+    # Let's provide a more helpful error than you would otherwise get.
+    if isinstance(name, pd.DataFrame):
+        err = (
+            "This function accepts only strings (the name of an example dataset). "
+            "You passed a pandas DataFrame. If you have your own dataset, "
+            "it is not necessary to use this function before plotting."
+        )
+        raise TypeError(err)
+
+    url = f"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{name}.csv"
+
+    if cache:
+        cache_path = os.path.join(get_data_home(data_home), os.path.basename(url))
+        if not os.path.exists(cache_path):
+            if name not in get_dataset_names():
+                raise ValueError(f"'{name}' is not one of the example datasets.")
+            urlretrieve(url, cache_path)
+        full_path = cache_path
+    else:
+        full_path = url
+
+    df = pd.read_csv(full_path, **kws)
+
+    if df.iloc[-1].isnull().all():
+        df = df.iloc[:-1]
+
+    # Set some columns as a categorical type with ordered levels
+
+    if name == "tips":
+        df["day"] = pd.Categorical(df["day"], ["Thur", "Fri", "Sat", "Sun"])
+        df["sex"] = pd.Categorical(df["sex"], ["Male", "Female"])
+        df["time"] = pd.Categorical(df["time"], ["Lunch", "Dinner"])
+        df["smoker"] = pd.Categorical(df["smoker"], ["Yes", "No"])
+
+    elif name == "flights":
+        months = df["month"].str[:3]
+        df["month"] = pd.Categorical(months, months.unique())
+
+    elif name == "exercise":
+        df["time"] = pd.Categorical(df["time"], ["1 min", "15 min", "30 min"])
+        df["kind"] = pd.Categorical(df["kind"], ["rest", "walking", "running"])
+        df["diet"] = pd.Categorical(df["diet"], ["no fat", "low fat"])
+
+    elif name == "titanic":
+        df["class"] = pd.Categorical(df["class"], ["First", "Second", "Third"])
+        df["deck"] = pd.Categorical(df["deck"], list("ABCDEFG"))
+
+    elif name == "penguins":
+        df["sex"] = df["sex"].str.title()
+
+    elif name == "diamonds":
+        df["color"] = pd.Categorical(
+            df["color"], ["D", "E", "F", "G", "H", "I", "J"],
+        )
+        df["clarity"] = pd.Categorical(
+            df["clarity"], ["IF", "VVS1", "VVS2", "VS1", "VS2", "SI1", "SI2", "I1"],
+        )
+        df["cut"] = pd.Categorical(
+            df["cut"], ["Ideal", "Premium", "Very Good", "Good", "Fair"],
+        )
+
+    elif name == "taxis":
+        df["pickup"] = pd.to_datetime(df["pickup"])
+        df["dropoff"] = pd.to_datetime(df["dropoff"])
+
+    elif name == "seaice":
+        df["Date"] = pd.to_datetime(df["Date"])
+
+    elif name == "dowjones":
+        df["Date"] = pd.to_datetime(df["Date"])
+
+    return df
+
+
+def axis_ticklabels_overlap(labels):
+    """Return a boolean for whether the list of ticklabels have overlaps.
+
+    Parameters
+    ----------
+    labels : list of matplotlib ticklabels
+
+    Returns
+    -------
+    overlap : boolean
+        True if any of the labels overlap.
+
+    """
+    if not labels:
+        return False
+    try:
+        bboxes = [l.get_window_extent() for l in labels]
+        overlaps = [b.count_overlaps(bboxes) for b in bboxes]
+        return max(overlaps) > 1
+    except RuntimeError:
+        # Issue on macos backend raises an error in the above code
+        return False
+
+
+def axes_ticklabels_overlap(ax):
+    """Return booleans for whether the x and y ticklabels on an Axes overlap.
+
+    Parameters
+    ----------
+    ax : matplotlib Axes
+
+    Returns
+    -------
+    x_overlap, y_overlap : booleans
+        True when the labels on that axis overlap.
+
+    """
+    return (axis_ticklabels_overlap(ax.get_xticklabels()),
+            axis_ticklabels_overlap(ax.get_yticklabels()))
+
+
+def locator_to_legend_entries(locator, limits, dtype):
+    """Return levels and formatted levels for brief numeric legends."""
+    raw_levels = locator.tick_values(*limits).astype(dtype)
+
+    # The locator can return ticks outside the limits, clip them here
+    raw_levels = [l for l in raw_levels if l >= limits[0] and l <= limits[1]]
+
+    class dummy_axis:
+        def get_view_interval(self):
+            return limits
+
+    if isinstance(locator, mpl.ticker.LogLocator):
+        formatter = mpl.ticker.LogFormatter()
+    else:
+        formatter = mpl.ticker.ScalarFormatter()
+        # Avoid having an offset/scientific notation which we don't currently
+        # have any way of representing in the legend
+        formatter.set_useOffset(False)
+        formatter.set_scientific(False)
+    formatter.axis = dummy_axis()
+
+    # TODO: The following two lines should be replaced
+    # once pinned matplotlib>=3.1.0 with:
+    # formatted_levels = formatter.format_ticks(raw_levels)
+    formatter.set_locs(raw_levels)
+    formatted_levels = [formatter(x) for x in raw_levels]
+
+    return raw_levels, formatted_levels
+
+
+def relative_luminance(color):
+    """Calculate the relative luminance of a color according to W3C standards
+
+    Parameters
+    ----------
+    color : matplotlib color or sequence of matplotlib colors
+        Hex code, rgb-tuple, or html color name.
+
+    Returns
+    -------
+    luminance : float(s) between 0 and 1
+
+    """
+    rgb = mpl.colors.colorConverter.to_rgba_array(color)[:, :3]
+    rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)
+    lum = rgb.dot([.2126, .7152, .0722])
+    try:
+        return lum.item()
+    except ValueError:
+        return lum
+
+
+def to_utf8(obj):
+    """Return a string representing a Python object.
+
+    Strings (i.e. type ``str``) are returned unchanged.
+
+    Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.
+
+    For other objects, the method ``__str__()`` is called, and the result is
+    returned as a string.
+
+    Parameters
+    ----------
+    obj : object
+        Any Python object
+
+    Returns
+    -------
+    s : str
+        UTF-8-decoded string representation of ``obj``
+
+    """
+    if isinstance(obj, str):
+        return obj
+    try:
+        return obj.decode(encoding="utf-8")
+    except AttributeError:  # obj is not bytes-like
+        return str(obj)
+
+
+def _normalize_kwargs(kws, artist):
+    """Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1."""
+    _alias_map = {
+        'color': ['c'],
+        'linewidth': ['lw'],
+        'linestyle': ['ls'],
+        'facecolor': ['fc'],
+        'edgecolor': ['ec'],
+        'markerfacecolor': ['mfc'],
+        'markeredgecolor': ['mec'],
+        'markeredgewidth': ['mew'],
+        'markersize': ['ms']
+    }
+    try:
+        kws = normalize_kwargs(kws, artist)
+    except AttributeError:
+        kws = normalize_kwargs(kws, _alias_map)
+    return kws
+
+
+def _check_argument(param, options, value):
+    """Raise if value for param is not in options."""
+    if value not in options:
+        raise ValueError(
+            f"`{param}` must be one of {options}, but {repr(value)} was passed."
+        )
+
+
+def _assign_default_kwargs(kws, call_func, source_func):
+    """Assign default kwargs for call_func using values from source_func."""
+    # This exists so that axes-level functions and figure-level functions can
+    # both call a Plotter method while having the default kwargs be defined in
+    # the signature of the axes-level function.
+    # An alternative would be to have a decorator on the method that sets its
+    # defaults based on those defined in the axes-level function.
+    # Then the figure-level function would not need to worry about defaults.
+    # I am not sure which is better.
+    needed = inspect.signature(call_func).parameters
+    defaults = inspect.signature(source_func).parameters
+
+    for param in needed:
+        if param in defaults and param not in kws:
+            kws[param] = defaults[param].default
+
+    return kws
+
+
+def adjust_legend_subtitles(legend):
+    """
+    Make invisible-handle "subtitles" entries look more like titles.
+
+    Note: This function is not part of the public API and may be changed or removed.
+
+    """
+    # Legend title not in rcParams until 3.0
+    font_size = plt.rcParams.get("legend.title_fontsize", None)
+    hpackers = legend.findobj(mpl.offsetbox.VPacker)[0].get_children()
+    for hpack in hpackers:
+        draw_area, text_area = hpack.get_children()
+        handles = draw_area.get_children()
+        if not all(artist.get_visible() for artist in handles):
+            draw_area.set_width(0)
+            for text in text_area.get_children():
+                if font_size is not None:
+                    text.set_size(font_size)
+
+
+def _deprecate_ci(errorbar, ci):
+    """
+    Warn on usage of ci= and convert to appropriate errorbar= arg.
+
+    ci was deprecated when errorbar was added in 0.12. It should not be removed
+    completely for some time, but it can be moved out of function definitions
+    (and extracted from kwargs) after one cycle.
+
+    """
+    if ci != "deprecated":
+        if ci is None:
+            errorbar = None
+        elif ci == "sd":
+            errorbar = "sd"
+        else:
+            errorbar = ("ci", ci)
+        msg = (
+            "\n\nThe `ci` parameter is deprecated. "
+            f"Use `errorbar={repr(errorbar)}` for the same effect.\n"
+        )
+        warnings.warn(msg, FutureWarning, stacklevel=3)
+
+    return errorbar
+
+
+@contextmanager
+def _disable_autolayout():
+    """Context manager for preventing rc-controlled auto-layout behavior."""
+    # This is a workaround for an issue in matplotlib, for details see
+    # https://github.com/mwaskom/seaborn/issues/2914
+    # The only affect of this rcParam is to set the default value for
+    # layout= in plt.figure, so we could just do that instead.
+    # But then we would need to own the complexity of the transition
+    # from tight_layout=True -> layout="tight". This seems easier,
+    # but can be removed when (if) that is simpler on the matplotlib side,
+    # or if the layout algorithms are improved to handle figure legends.
+    orig_val = mpl.rcParams["figure.autolayout"]
+    try:
+        mpl.rcParams["figure.autolayout"] = False
+        yield
+    finally:
+        mpl.rcParams["figure.autolayout"] = orig_val
+
+
+def _version_predates(lib: ModuleType, version: str) -> bool:
+    """Helper function for checking version compatibility."""
+    return Version(lib.__version__) < Version(version)
diff --git a/testbed/mwaskom__seaborn/seaborn/widgets.py b/testbed/mwaskom__seaborn/seaborn/widgets.py
new file mode 100644
index 0000000000000000000000000000000000000000..502812af57f5fa2c7e8163c33f472b594f506c79
--- /dev/null
+++ b/testbed/mwaskom__seaborn/seaborn/widgets.py
@@ -0,0 +1,426 @@
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.colors import LinearSegmentedColormap
+
+try:
+    from ipywidgets import interact, FloatSlider, IntSlider
+except ImportError:
+    def interact(f):
+        msg = "Interactive palettes require `ipywidgets`, which is not installed."
+        raise ImportError(msg)
+
+from .miscplot import palplot
+from .palettes import (color_palette, dark_palette, light_palette,
+                       diverging_palette, cubehelix_palette)
+
+
+__all__ = ["choose_colorbrewer_palette", "choose_cubehelix_palette",
+           "choose_dark_palette", "choose_light_palette",
+           "choose_diverging_palette"]
+
+
+def _init_mutable_colormap():
+    """Create a matplotlib colormap that will be updated by the widgets."""
+    greys = color_palette("Greys", 256)
+    cmap = LinearSegmentedColormap.from_list("interactive", greys)
+    cmap._init()
+    cmap._set_extremes()
+    return cmap
+
+
+def _update_lut(cmap, colors):
+    """Change the LUT values in a matplotlib colormap in-place."""
+    cmap._lut[:256] = colors
+    cmap._set_extremes()
+
+
+def _show_cmap(cmap):
+    """Show a continuous matplotlib colormap."""
+    from .rcmod import axes_style  # Avoid circular import
+    with axes_style("white"):
+        f, ax = plt.subplots(figsize=(8.25, .75))
+    ax.set(xticks=[], yticks=[])
+    x = np.linspace(0, 1, 256)[np.newaxis, :]
+    ax.pcolormesh(x, cmap=cmap)
+
+
+def choose_colorbrewer_palette(data_type, as_cmap=False):
+    """Select a palette from the ColorBrewer set.
+
+    These palettes are built into matplotlib and can be used by name in
+    many seaborn functions, or by passing the object returned by this function.
+
+    Parameters
+    ----------
+    data_type : {'sequential', 'diverging', 'qualitative'}
+        This describes the kind of data you want to visualize. See the seaborn
+        color palette docs for more information about how to choose this value.
+        Note that you can pass substrings (e.g. 'q' for 'qualitative.
+
+    as_cmap : bool
+        If True, the return value is a matplotlib colormap rather than a
+        list of discrete colors.
+
+    Returns
+    -------
+    pal or cmap : list of colors or matplotlib colormap
+        Object that can be passed to plotting functions.
+
+    See Also
+    --------
+    dark_palette : Create a sequential palette with dark low values.
+    light_palette : Create a sequential palette with bright low values.
+    diverging_palette : Create a diverging palette from selected colors.
+    cubehelix_palette : Create a sequential palette or colormap using the
+                        cubehelix system.
+
+
+    """
+    if data_type.startswith("q") and as_cmap:
+        raise ValueError("Qualitative palettes cannot be colormaps.")
+
+    pal = []
+    if as_cmap:
+        cmap = _init_mutable_colormap()
+
+    if data_type.startswith("s"):
+        opts = ["Greys", "Reds", "Greens", "Blues", "Oranges", "Purples",
+                "BuGn", "BuPu", "GnBu", "OrRd", "PuBu", "PuRd", "RdPu", "YlGn",
+                "PuBuGn", "YlGnBu", "YlOrBr", "YlOrRd"]
+        variants = ["regular", "reverse", "dark"]
+
+        @interact
+        def choose_sequential(name=opts, n=(2, 18),
+                              desat=FloatSlider(min=0, max=1, value=1),
+                              variant=variants):
+            if variant == "reverse":
+                name += "_r"
+            elif variant == "dark":
+                name += "_d"
+
+            if as_cmap:
+                colors = color_palette(name, 256, desat)
+                _update_lut(cmap, np.c_[colors, np.ones(256)])
+                _show_cmap(cmap)
+            else:
+                pal[:] = color_palette(name, n, desat)
+                palplot(pal)
+
+    elif data_type.startswith("d"):
+        opts = ["RdBu", "RdGy", "PRGn", "PiYG", "BrBG",
+                "RdYlBu", "RdYlGn", "Spectral"]
+        variants = ["regular", "reverse"]
+
+        @interact
+        def choose_diverging(name=opts, n=(2, 16),
+                             desat=FloatSlider(min=0, max=1, value=1),
+                             variant=variants):
+            if variant == "reverse":
+                name += "_r"
+            if as_cmap:
+                colors = color_palette(name, 256, desat)
+                _update_lut(cmap, np.c_[colors, np.ones(256)])
+                _show_cmap(cmap)
+            else:
+                pal[:] = color_palette(name, n, desat)
+                palplot(pal)
+
+    elif data_type.startswith("q"):
+        opts = ["Set1", "Set2", "Set3", "Paired", "Accent",
+                "Pastel1", "Pastel2", "Dark2"]
+
+        @interact
+        def choose_qualitative(name=opts, n=(2, 16),
+                               desat=FloatSlider(min=0, max=1, value=1)):
+            pal[:] = color_palette(name, n, desat)
+            palplot(pal)
+
+    if as_cmap:
+        return cmap
+    return pal
+
+
+def choose_dark_palette(input="husl", as_cmap=False):
+    """Launch an interactive widget to create a dark sequential palette.
+
+    This corresponds with the :func:`dark_palette` function. This kind
+    of palette is good for data that range between relatively uninteresting
+    low values and interesting high values.
+
+    Requires IPython 2+ and must be used in the notebook.
+
+    Parameters
+    ----------
+    input : {'husl', 'hls', 'rgb'}
+        Color space for defining the seed value. Note that the default is
+        different than the default input for :func:`dark_palette`.
+    as_cmap : bool
+        If True, the return value is a matplotlib colormap rather than a
+        list of discrete colors.
+
+    Returns
+    -------
+    pal or cmap : list of colors or matplotlib colormap
+        Object that can be passed to plotting functions.
+
+    See Also
+    --------
+    dark_palette : Create a sequential palette with dark low values.
+    light_palette : Create a sequential palette with bright low values.
+    cubehelix_palette : Create a sequential palette or colormap using the
+                        cubehelix system.
+
+    """
+    pal = []
+    if as_cmap:
+        cmap = _init_mutable_colormap()
+
+    if input == "rgb":
+        @interact
+        def choose_dark_palette_rgb(r=(0., 1.),
+                                    g=(0., 1.),
+                                    b=(0., 1.),
+                                    n=(3, 17)):
+            color = r, g, b
+            if as_cmap:
+                colors = dark_palette(color, 256, input="rgb")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = dark_palette(color, n, input="rgb")
+                palplot(pal)
+
+    elif input == "hls":
+        @interact
+        def choose_dark_palette_hls(h=(0., 1.),
+                                    l=(0., 1.),  # noqa: E741
+                                    s=(0., 1.),
+                                    n=(3, 17)):
+            color = h, l, s
+            if as_cmap:
+                colors = dark_palette(color, 256, input="hls")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = dark_palette(color, n, input="hls")
+                palplot(pal)
+
+    elif input == "husl":
+        @interact
+        def choose_dark_palette_husl(h=(0, 359),
+                                     s=(0, 99),
+                                     l=(0, 99),  # noqa: E741
+                                     n=(3, 17)):
+            color = h, s, l
+            if as_cmap:
+                colors = dark_palette(color, 256, input="husl")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = dark_palette(color, n, input="husl")
+                palplot(pal)
+
+    if as_cmap:
+        return cmap
+    return pal
+
+
+def choose_light_palette(input="husl", as_cmap=False):
+    """Launch an interactive widget to create a light sequential palette.
+
+    This corresponds with the :func:`light_palette` function. This kind
+    of palette is good for data that range between relatively uninteresting
+    low values and interesting high values.
+
+    Requires IPython 2+ and must be used in the notebook.
+
+    Parameters
+    ----------
+    input : {'husl', 'hls', 'rgb'}
+        Color space for defining the seed value. Note that the default is
+        different than the default input for :func:`light_palette`.
+    as_cmap : bool
+        If True, the return value is a matplotlib colormap rather than a
+        list of discrete colors.
+
+    Returns
+    -------
+    pal or cmap : list of colors or matplotlib colormap
+        Object that can be passed to plotting functions.
+
+    See Also
+    --------
+    light_palette : Create a sequential palette with bright low values.
+    dark_palette : Create a sequential palette with dark low values.
+    cubehelix_palette : Create a sequential palette or colormap using the
+                        cubehelix system.
+
+    """
+    pal = []
+    if as_cmap:
+        cmap = _init_mutable_colormap()
+
+    if input == "rgb":
+        @interact
+        def choose_light_palette_rgb(r=(0., 1.),
+                                     g=(0., 1.),
+                                     b=(0., 1.),
+                                     n=(3, 17)):
+            color = r, g, b
+            if as_cmap:
+                colors = light_palette(color, 256, input="rgb")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = light_palette(color, n, input="rgb")
+                palplot(pal)
+
+    elif input == "hls":
+        @interact
+        def choose_light_palette_hls(h=(0., 1.),
+                                     l=(0., 1.),  # noqa: E741
+                                     s=(0., 1.),
+                                     n=(3, 17)):
+            color = h, l, s
+            if as_cmap:
+                colors = light_palette(color, 256, input="hls")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = light_palette(color, n, input="hls")
+                palplot(pal)
+
+    elif input == "husl":
+        @interact
+        def choose_light_palette_husl(h=(0, 359),
+                                      s=(0, 99),
+                                      l=(0, 99),  # noqa: E741
+                                      n=(3, 17)):
+            color = h, s, l
+            if as_cmap:
+                colors = light_palette(color, 256, input="husl")
+                _update_lut(cmap, colors)
+                _show_cmap(cmap)
+            else:
+                pal[:] = light_palette(color, n, input="husl")
+                palplot(pal)
+
+    if as_cmap:
+        return cmap
+    return pal
+
+
+def choose_diverging_palette(as_cmap=False):
+    """Launch an interactive widget to choose a diverging color palette.
+
+    This corresponds with the :func:`diverging_palette` function. This kind
+    of palette is good for data that range between interesting low values
+    and interesting high values with a meaningful midpoint. (For example,
+    change scores relative to some baseline value).
+
+    Requires IPython 2+ and must be used in the notebook.
+
+    Parameters
+    ----------
+    as_cmap : bool
+        If True, the return value is a matplotlib colormap rather than a
+        list of discrete colors.
+
+    Returns
+    -------
+    pal or cmap : list of colors or matplotlib colormap
+        Object that can be passed to plotting functions.
+
+    See Also
+    --------
+    diverging_palette : Create a diverging color palette or colormap.
+    choose_colorbrewer_palette : Interactively choose palettes from the
+                                 colorbrewer set, including diverging palettes.
+
+    """
+    pal = []
+    if as_cmap:
+        cmap = _init_mutable_colormap()
+
+    @interact
+    def choose_diverging_palette(
+        h_neg=IntSlider(min=0,
+                        max=359,
+                        value=220),
+        h_pos=IntSlider(min=0,
+                        max=359,
+                        value=10),
+        s=IntSlider(min=0, max=99, value=74),
+        l=IntSlider(min=0, max=99, value=50),  # noqa: E741
+        sep=IntSlider(min=1, max=50, value=10),
+        n=(2, 16),
+        center=["light", "dark"]
+    ):
+        if as_cmap:
+            colors = diverging_palette(h_neg, h_pos, s, l, sep, 256, center)
+            _update_lut(cmap, colors)
+            _show_cmap(cmap)
+        else:
+            pal[:] = diverging_palette(h_neg, h_pos, s, l, sep, n, center)
+            palplot(pal)
+
+    if as_cmap:
+        return cmap
+    return pal
+
+
+def choose_cubehelix_palette(as_cmap=False):
+    """Launch an interactive widget to create a sequential cubehelix palette.
+
+    This corresponds with the :func:`cubehelix_palette` function. This kind
+    of palette is good for data that range between relatively uninteresting
+    low values and interesting high values. The cubehelix system allows the
+    palette to have more hue variance across the range, which can be helpful
+    for distinguishing a wider range of values.
+
+    Requires IPython 2+ and must be used in the notebook.
+
+    Parameters
+    ----------
+    as_cmap : bool
+        If True, the return value is a matplotlib colormap rather than a
+        list of discrete colors.
+
+    Returns
+    -------
+    pal or cmap : list of colors or matplotlib colormap
+        Object that can be passed to plotting functions.
+
+    See Also
+    --------
+    cubehelix_palette : Create a sequential palette or colormap using the
+                        cubehelix system.
+
+    """
+    pal = []
+    if as_cmap:
+        cmap = _init_mutable_colormap()
+
+    @interact
+    def choose_cubehelix(n_colors=IntSlider(min=2, max=16, value=9),
+                         start=FloatSlider(min=0, max=3, value=0),
+                         rot=FloatSlider(min=-1, max=1, value=.4),
+                         gamma=FloatSlider(min=0, max=5, value=1),
+                         hue=FloatSlider(min=0, max=1, value=.8),
+                         light=FloatSlider(min=0, max=1, value=.85),
+                         dark=FloatSlider(min=0, max=1, value=.15),
+                         reverse=False):
+
+        if as_cmap:
+            colors = cubehelix_palette(256, start, rot, gamma,
+                                       hue, light, dark, reverse)
+            _update_lut(cmap, np.c_[colors, np.ones(256)])
+            _show_cmap(cmap)
+        else:
+            pal[:] = cubehelix_palette(n_colors, start, rot, gamma,
+                                       hue, light, dark, reverse)
+            palplot(pal)
+
+    if as_cmap:
+        return cmap
+    return pal
diff --git a/testbed/mwaskom__seaborn/setup.cfg b/testbed/mwaskom__seaborn/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..3b14c1997d9d9eeef15ed07d8e51966fea2171e4
--- /dev/null
+++ b/testbed/mwaskom__seaborn/setup.cfg
@@ -0,0 +1,25 @@
+[flake8]
+max-line-length = 88
+exclude = seaborn/cm.py,seaborn/external
+ignore = E741,F522,W503
+
+[mypy]
+# Currently this ignores pandas and matplotlib
+# We may want to make custom stub files for the parts we use
+# I have found the available third party stubs to be less
+# complete than they would need to be useful
+ignore_missing_imports = True
+
+[coverage:run]
+omit =
+    seaborn/widgets.py
+    seaborn/external/*
+    seaborn/colors/*
+    seaborn/cm.py
+    seaborn/conftest.py
+
+[coverage:report]
+exclude_lines =
+    pragma: no cover
+    if TYPE_CHECKING:
+    raise NotImplementedError
diff --git a/testbed/mwaskom__seaborn/tests/__init__.py b/testbed/mwaskom__seaborn/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/mwaskom__seaborn/tests/_core/__init__.py b/testbed/mwaskom__seaborn/tests/_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_data.py b/testbed/mwaskom__seaborn/tests/_core/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e0026c19f3976f2d0b8c4cd3d040ad09195be8
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_data.py
@@ -0,0 +1,398 @@
+import functools
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal
+from pandas.testing import assert_series_equal
+
+from seaborn._core.data import PlotData
+
+
+assert_vector_equal = functools.partial(assert_series_equal, check_names=False)
+
+
+class TestPlotData:
+
+    @pytest.fixture
+    def long_variables(self):
+        variables = dict(x="x", y="y", color="a", size="z", style="s_cat")
+        return variables
+
+    def test_named_vectors(self, long_df, long_variables):
+
+        p = PlotData(long_df, long_variables)
+        assert p.source_data is long_df
+        assert p.source_vars is long_variables
+        for key, val in long_variables.items():
+            assert p.names[key] == val
+            assert_vector_equal(p.frame[key], long_df[val])
+
+    def test_named_and_given_vectors(self, long_df, long_variables):
+
+        long_variables["y"] = long_df["b"]
+        long_variables["size"] = long_df["z"].to_numpy()
+
+        p = PlotData(long_df, long_variables)
+
+        assert_vector_equal(p.frame["color"], long_df[long_variables["color"]])
+        assert_vector_equal(p.frame["y"], long_df["b"])
+        assert_vector_equal(p.frame["size"], long_df["z"])
+
+        assert p.names["color"] == long_variables["color"]
+        assert p.names["y"] == "b"
+        assert p.names["size"] is None
+
+        assert p.ids["color"] == long_variables["color"]
+        assert p.ids["y"] == "b"
+        assert p.ids["size"] == id(long_variables["size"])
+
+    def test_index_as_variable(self, long_df, long_variables):
+
+        index = pd.Index(np.arange(len(long_df)) * 2 + 10, name="i", dtype=int)
+        long_variables["x"] = "i"
+        p = PlotData(long_df.set_index(index), long_variables)
+
+        assert p.names["x"] == p.ids["x"] == "i"
+        assert_vector_equal(p.frame["x"], pd.Series(index, index))
+
+    def test_multiindex_as_variables(self, long_df, long_variables):
+
+        index_i = pd.Index(np.arange(len(long_df)) * 2 + 10, name="i", dtype=int)
+        index_j = pd.Index(np.arange(len(long_df)) * 3 + 5, name="j", dtype=int)
+        index = pd.MultiIndex.from_arrays([index_i, index_j])
+        long_variables.update({"x": "i", "y": "j"})
+
+        p = PlotData(long_df.set_index(index), long_variables)
+        assert_vector_equal(p.frame["x"], pd.Series(index_i, index))
+        assert_vector_equal(p.frame["y"], pd.Series(index_j, index))
+
+    def test_int_as_variable_key(self, rng):
+
+        df = pd.DataFrame(rng.uniform(size=(10, 3)))
+
+        var = "x"
+        key = 2
+
+        p = PlotData(df, {var: key})
+        assert_vector_equal(p.frame[var], df[key])
+        assert p.names[var] == p.ids[var] == str(key)
+
+    def test_int_as_variable_value(self, long_df):
+
+        p = PlotData(long_df, {"x": 0, "y": "y"})
+        assert (p.frame["x"] == 0).all()
+        assert p.names["x"] is None
+        assert p.ids["x"] == id(0)
+
+    def test_tuple_as_variable_key(self, rng):
+
+        cols = pd.MultiIndex.from_product([("a", "b", "c"), ("x", "y")])
+        df = pd.DataFrame(rng.uniform(size=(10, 6)), columns=cols)
+
+        var = "color"
+        key = ("b", "y")
+        p = PlotData(df, {var: key})
+        assert_vector_equal(p.frame[var], df[key])
+        assert p.names[var] == p.ids[var] == str(key)
+
+    def test_dict_as_data(self, long_dict, long_variables):
+
+        p = PlotData(long_dict, long_variables)
+        assert p.source_data is long_dict
+        for key, val in long_variables.items():
+            assert_vector_equal(p.frame[key], pd.Series(long_dict[val]))
+
+    @pytest.mark.parametrize(
+        "vector_type",
+        ["series", "numpy", "list"],
+    )
+    def test_vectors_various_types(self, long_df, long_variables, vector_type):
+
+        variables = {key: long_df[val] for key, val in long_variables.items()}
+        if vector_type == "numpy":
+            variables = {key: val.to_numpy() for key, val in variables.items()}
+        elif vector_type == "list":
+            variables = {key: val.to_list() for key, val in variables.items()}
+
+        p = PlotData(None, variables)
+
+        assert list(p.names) == list(long_variables)
+        if vector_type == "series":
+            assert p.source_vars is variables
+            assert p.names == p.ids == {key: val.name for key, val in variables.items()}
+        else:
+            assert p.names == {key: None for key in variables}
+            assert p.ids == {key: id(val) for key, val in variables.items()}
+
+        for key, val in long_variables.items():
+            if vector_type == "series":
+                assert_vector_equal(p.frame[key], long_df[val])
+            else:
+                assert_array_equal(p.frame[key], long_df[val])
+
+    def test_none_as_variable_value(self, long_df):
+
+        p = PlotData(long_df, {"x": "z", "y": None})
+        assert list(p.frame.columns) == ["x"]
+        assert p.names == p.ids == {"x": "z"}
+
+    def test_frame_and_vector_mismatched_lengths(self, long_df):
+
+        vector = np.arange(len(long_df) * 2)
+        with pytest.raises(ValueError):
+            PlotData(long_df, {"x": "x", "y": vector})
+
+    @pytest.mark.parametrize(
+        "arg", [[], np.array([]), pd.DataFrame()],
+    )
+    def test_empty_data_input(self, arg):
+
+        p = PlotData(arg, {})
+        assert p.frame.empty
+        assert not p.names
+
+        if not isinstance(arg, pd.DataFrame):
+            p = PlotData(None, dict(x=arg, y=arg))
+            assert p.frame.empty
+            assert not p.names
+
+    def test_index_alignment_series_to_dataframe(self):
+
+        x = [1, 2, 3]
+        x_index = pd.Index(x, dtype=int)
+
+        y_values = [3, 4, 5]
+        y_index = pd.Index(y_values, dtype=int)
+        y = pd.Series(y_values, y_index, name="y")
+
+        data = pd.DataFrame(dict(x=x), index=x_index)
+
+        p = PlotData(data, {"x": "x", "y": y})
+
+        x_col_expected = pd.Series([1, 2, 3, np.nan, np.nan], np.arange(1, 6))
+        y_col_expected = pd.Series([np.nan, np.nan, 3, 4, 5], np.arange(1, 6))
+        assert_vector_equal(p.frame["x"], x_col_expected)
+        assert_vector_equal(p.frame["y"], y_col_expected)
+
+    def test_index_alignment_between_series(self):
+
+        x_index = [1, 2, 3]
+        x_values = [10, 20, 30]
+        x = pd.Series(x_values, x_index, name="x")
+
+        y_index = [3, 4, 5]
+        y_values = [300, 400, 500]
+        y = pd.Series(y_values, y_index, name="y")
+
+        p = PlotData(None, {"x": x, "y": y})
+
+        x_col_expected = pd.Series([10, 20, 30, np.nan, np.nan], np.arange(1, 6))
+        y_col_expected = pd.Series([np.nan, np.nan, 300, 400, 500], np.arange(1, 6))
+        assert_vector_equal(p.frame["x"], x_col_expected)
+        assert_vector_equal(p.frame["y"], y_col_expected)
+
+    def test_key_not_in_data_raises(self, long_df):
+
+        var = "x"
+        key = "what"
+        msg = f"Could not interpret value `{key}` for `{var}`. An entry with this name"
+        with pytest.raises(ValueError, match=msg):
+            PlotData(long_df, {var: key})
+
+    def test_key_with_no_data_raises(self):
+
+        var = "x"
+        key = "what"
+        msg = f"Could not interpret value `{key}` for `{var}`. Value is a string,"
+        with pytest.raises(ValueError, match=msg):
+            PlotData(None, {var: key})
+
+    def test_data_vector_different_lengths_raises(self, long_df):
+
+        vector = np.arange(len(long_df) - 5)
+        msg = "Length of ndarray vectors must match length of `data`"
+        with pytest.raises(ValueError, match=msg):
+            PlotData(long_df, {"y": vector})
+
+    def test_undefined_variables_raise(self, long_df):
+
+        with pytest.raises(ValueError):
+            PlotData(long_df, dict(x="not_in_df"))
+
+        with pytest.raises(ValueError):
+            PlotData(long_df, dict(x="x", y="not_in_df"))
+
+        with pytest.raises(ValueError):
+            PlotData(long_df, dict(x="x", y="y", color="not_in_df"))
+
+    def test_contains_operation(self, long_df):
+
+        p = PlotData(long_df, {"x": "y", "color": long_df["a"]})
+        assert "x" in p
+        assert "y" not in p
+        assert "color" in p
+
+    def test_join_add_variable(self, long_df):
+
+        v1 = {"x": "x", "y": "f"}
+        v2 = {"color": "a"}
+
+        p1 = PlotData(long_df, v1)
+        p2 = p1.join(None, v2)
+
+        for var, key in dict(**v1, **v2).items():
+            assert var in p2
+            assert p2.names[var] == key
+            assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_replace_variable(self, long_df):
+
+        v1 = {"x": "x", "y": "y"}
+        v2 = {"y": "s"}
+
+        p1 = PlotData(long_df, v1)
+        p2 = p1.join(None, v2)
+
+        variables = v1.copy()
+        variables.update(v2)
+
+        for var, key in variables.items():
+            assert var in p2
+            assert p2.names[var] == key
+            assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_remove_variable(self, long_df):
+
+        variables = {"x": "x", "y": "f"}
+        drop_var = "y"
+
+        p1 = PlotData(long_df, variables)
+        p2 = p1.join(None, {drop_var: None})
+
+        assert drop_var in p1
+        assert drop_var not in p2
+        assert drop_var not in p2.frame
+        assert drop_var not in p2.names
+
+    def test_join_all_operations(self, long_df):
+
+        v1 = {"x": "x", "y": "y", "color": "a"}
+        v2 = {"y": "s", "size": "s", "color": None}
+
+        p1 = PlotData(long_df, v1)
+        p2 = p1.join(None, v2)
+
+        for var, key in v2.items():
+            if key is None:
+                assert var not in p2
+            else:
+                assert p2.names[var] == key
+                assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_all_operations_same_data(self, long_df):
+
+        v1 = {"x": "x", "y": "y", "color": "a"}
+        v2 = {"y": "s", "size": "s", "color": None}
+
+        p1 = PlotData(long_df, v1)
+        p2 = p1.join(long_df, v2)
+
+        for var, key in v2.items():
+            if key is None:
+                assert var not in p2
+            else:
+                assert p2.names[var] == key
+                assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_add_variable_new_data(self, long_df):
+
+        d1 = long_df[["x", "y"]]
+        d2 = long_df[["a", "s"]]
+
+        v1 = {"x": "x", "y": "y"}
+        v2 = {"color": "a"}
+
+        p1 = PlotData(d1, v1)
+        p2 = p1.join(d2, v2)
+
+        for var, key in dict(**v1, **v2).items():
+            assert p2.names[var] == key
+            assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_replace_variable_new_data(self, long_df):
+
+        d1 = long_df[["x", "y"]]
+        d2 = long_df[["a", "s"]]
+
+        v1 = {"x": "x", "y": "y"}
+        v2 = {"x": "a"}
+
+        p1 = PlotData(d1, v1)
+        p2 = p1.join(d2, v2)
+
+        variables = v1.copy()
+        variables.update(v2)
+
+        for var, key in variables.items():
+            assert p2.names[var] == key
+            assert_vector_equal(p2.frame[var], long_df[key])
+
+    def test_join_add_variable_different_index(self, long_df):
+
+        d1 = long_df.iloc[:70]
+        d2 = long_df.iloc[30:]
+
+        v1 = {"x": "a"}
+        v2 = {"y": "z"}
+
+        p1 = PlotData(d1, v1)
+        p2 = p1.join(d2, v2)
+
+        (var1, key1), = v1.items()
+        (var2, key2), = v2.items()
+
+        assert_vector_equal(p2.frame.loc[d1.index, var1], d1[key1])
+        assert_vector_equal(p2.frame.loc[d2.index, var2], d2[key2])
+
+        assert p2.frame.loc[d2.index.difference(d1.index), var1].isna().all()
+        assert p2.frame.loc[d1.index.difference(d2.index), var2].isna().all()
+
+    def test_join_replace_variable_different_index(self, long_df):
+
+        d1 = long_df.iloc[:70]
+        d2 = long_df.iloc[30:]
+
+        var = "x"
+        k1, k2 = "a", "z"
+        v1 = {var: k1}
+        v2 = {var: k2}
+
+        p1 = PlotData(d1, v1)
+        p2 = p1.join(d2, v2)
+
+        (var1, key1), = v1.items()
+        (var2, key2), = v2.items()
+
+        assert_vector_equal(p2.frame.loc[d2.index, var], d2[k2])
+        assert p2.frame.loc[d1.index.difference(d2.index), var].isna().all()
+
+    def test_join_subset_data_inherit_variables(self, long_df):
+
+        sub_df = long_df[long_df["a"] == "b"]
+
+        var = "y"
+        p1 = PlotData(long_df, {var: var})
+        p2 = p1.join(sub_df, None)
+
+        assert_vector_equal(p2.frame.loc[sub_df.index, var], sub_df[var])
+        assert p2.frame.loc[long_df.index.difference(sub_df.index), var].isna().all()
+
+    def test_join_multiple_inherits_from_orig(self, rng):
+
+        d1 = pd.DataFrame(dict(a=rng.normal(0, 1, 100), b=rng.normal(0, 1, 100)))
+        d2 = pd.DataFrame(dict(a=rng.normal(0, 1, 100)))
+
+        p = PlotData(d1, {"x": "a"}).join(d2, {"y": "a"}).join(None, {"y": "a"})
+        assert_vector_equal(p.frame["x"], d1["a"])
+        assert_vector_equal(p.frame["y"], d1["a"])
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_groupby.py b/testbed/mwaskom__seaborn/tests/_core/test_groupby.py
new file mode 100644
index 0000000000000000000000000000000000000000..46888db577ebbc37da47153b47349c3beddc7c6a
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_groupby.py
@@ -0,0 +1,134 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn._core.groupby import GroupBy
+
+
+@pytest.fixture
+def df():
+
+    return pd.DataFrame(
+        columns=["a", "b", "x", "y"],
+        data=[
+            ["a", "g", 1, .2],
+            ["b", "h", 3, .5],
+            ["a", "f", 2, .8],
+            ["a", "h", 1, .3],
+            ["b", "f", 2, .4],
+        ]
+    )
+
+
+def test_init_from_list():
+    g = GroupBy(["a", "c", "b"])
+    assert g.order == {"a": None, "c": None, "b": None}
+
+
+def test_init_from_dict():
+    order = {"a": [3, 2, 1], "c": None, "b": ["x", "y", "z"]}
+    g = GroupBy(order)
+    assert g.order == order
+
+
+def test_init_requires_order():
+
+    with pytest.raises(ValueError, match="GroupBy requires at least one"):
+        GroupBy([])
+
+
+def test_at_least_one_grouping_variable_required(df):
+
+    with pytest.raises(ValueError, match="No grouping variables are present"):
+        GroupBy(["z"]).agg(df, x="mean")
+
+
+def test_agg_one_grouper(df):
+
+    res = GroupBy(["a"]).agg(df, {"y": "max"})
+    assert_array_equal(res.index, [0, 1])
+    assert_array_equal(res.columns, ["a", "y"])
+    assert_array_equal(res["a"], ["a", "b"])
+    assert_array_equal(res["y"], [.8, .5])
+
+
+def test_agg_two_groupers(df):
+
+    res = GroupBy(["a", "x"]).agg(df, {"y": "min"})
+    assert_array_equal(res.index, [0, 1, 2, 3, 4, 5])
+    assert_array_equal(res.columns, ["a", "x", "y"])
+    assert_array_equal(res["a"], ["a", "a", "a", "b", "b", "b"])
+    assert_array_equal(res["x"], [1, 2, 3, 1, 2, 3])
+    assert_array_equal(res["y"], [.2, .8, np.nan, np.nan, .4, .5])
+
+
+def test_agg_two_groupers_ordered(df):
+
+    order = {"b": ["h", "g", "f"], "x": [3, 2, 1]}
+    res = GroupBy(order).agg(df, {"a": "min", "y": lambda x: x.iloc[0]})
+    assert_array_equal(res.index, [0, 1, 2, 3, 4, 5, 6, 7, 8])
+    assert_array_equal(res.columns, ["a", "b", "x", "y"])
+    assert_array_equal(res["b"], ["h", "h", "h", "g", "g", "g", "f", "f", "f"])
+    assert_array_equal(res["x"], [3, 2, 1, 3, 2, 1, 3, 2, 1])
+
+    T, F = True, False
+    assert_array_equal(res["a"].isna(), [F, T, F, T, T, F, T, F, T])
+    assert_array_equal(res["a"].dropna(), ["b", "a", "a", "a"])
+    assert_array_equal(res["y"].dropna(), [.5, .3, .2, .8])
+
+
+def test_apply_no_grouper(df):
+
+    df = df[["x", "y"]]
+    res = GroupBy(["a"]).apply(df, lambda x: x.sort_values("x"))
+    assert_array_equal(res.columns, ["x", "y"])
+    assert_array_equal(res["x"], df["x"].sort_values())
+    assert_array_equal(res["y"], df.loc[np.argsort(df["x"]), "y"])
+
+
+def test_apply_one_grouper(df):
+
+    res = GroupBy(["a"]).apply(df, lambda x: x.sort_values("x"))
+    assert_array_equal(res.index, [0, 1, 2, 3, 4])
+    assert_array_equal(res.columns, ["a", "b", "x", "y"])
+    assert_array_equal(res["a"], ["a", "a", "a", "b", "b"])
+    assert_array_equal(res["b"], ["g", "h", "f", "f", "h"])
+    assert_array_equal(res["x"], [1, 1, 2, 2, 3])
+
+
+def test_apply_mutate_columns(df):
+
+    xx = np.arange(0, 5)
+    hats = []
+
+    def polyfit(df):
+        fit = np.polyfit(df["x"], df["y"], 1)
+        hat = np.polyval(fit, xx)
+        hats.append(hat)
+        return pd.DataFrame(dict(x=xx, y=hat))
+
+    res = GroupBy(["a"]).apply(df, polyfit)
+    assert_array_equal(res.index, np.arange(xx.size * 2))
+    assert_array_equal(res.columns, ["a", "x", "y"])
+    assert_array_equal(res["a"], ["a"] * xx.size + ["b"] * xx.size)
+    assert_array_equal(res["x"], xx.tolist() + xx.tolist())
+    assert_array_equal(res["y"], np.concatenate(hats))
+
+
+def test_apply_replace_columns(df):
+
+    def add_sorted_cumsum(df):
+
+        x = df["x"].sort_values()
+        z = df.loc[x.index, "y"].cumsum()
+        return pd.DataFrame(dict(x=x.values, z=z.values))
+
+    res = GroupBy(["a"]).apply(df, add_sorted_cumsum)
+    assert_array_equal(res.index, df.index)
+    assert_array_equal(res.columns, ["a", "x", "z"])
+    assert_array_equal(res["a"], ["a", "a", "a", "b", "b"])
+    assert_array_equal(res["x"], [1, 1, 2, 2, 3])
+    assert_array_equal(res["z"], [.2, .5, 1.3, .4, .9])
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_moves.py b/testbed/mwaskom__seaborn/tests/_core/test_moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fd88bb5fca1e625fbb682ebcd7c169a58f6fda6
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_moves.py
@@ -0,0 +1,367 @@
+
+from itertools import product
+
+import numpy as np
+import pandas as pd
+from pandas.testing import assert_series_equal
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn._core.moves import Dodge, Jitter, Shift, Stack, Norm
+from seaborn._core.rules import categorical_order
+from seaborn._core.groupby import GroupBy
+
+import pytest
+
+
+class MoveFixtures:
+
+    @pytest.fixture
+    def df(self, rng):
+
+        n = 50
+        data = {
+            "x": rng.choice([0., 1., 2., 3.], n),
+            "y": rng.normal(0, 1, n),
+            "grp2": rng.choice(["a", "b"], n),
+            "grp3": rng.choice(["x", "y", "z"], n),
+            "width": 0.8,
+            "baseline": 0,
+        }
+        return pd.DataFrame(data)
+
+    @pytest.fixture
+    def toy_df(self):
+
+        data = {
+            "x": [0, 0, 1],
+            "y": [1, 2, 3],
+            "grp": ["a", "b", "b"],
+            "width": .8,
+            "baseline": 0,
+        }
+        return pd.DataFrame(data)
+
+    @pytest.fixture
+    def toy_df_widths(self, toy_df):
+
+        toy_df["width"] = [.8, .2, .4]
+        return toy_df
+
+    @pytest.fixture
+    def toy_df_facets(self):
+
+        data = {
+            "x": [0, 0, 1, 0, 1, 2],
+            "y": [1, 2, 3, 1, 2, 3],
+            "grp": ["a", "b", "a", "b", "a", "b"],
+            "col": ["x", "x", "x", "y", "y", "y"],
+            "width": .8,
+            "baseline": 0,
+        }
+        return pd.DataFrame(data)
+
+
+class TestJitter(MoveFixtures):
+
+    def get_groupby(self, data, orient):
+        other = {"x": "y", "y": "x"}[orient]
+        variables = [v for v in data if v not in [other, "width"]]
+        return GroupBy(variables)
+
+    def check_same(self, res, df, *cols):
+        for col in cols:
+            assert_series_equal(res[col], df[col])
+
+    def check_pos(self, res, df, var, limit):
+
+        assert (res[var] != df[var]).all()
+        assert (res[var] < df[var] + limit / 2).all()
+        assert (res[var] > df[var] - limit / 2).all()
+
+    def test_default(self, df):
+
+        orient = "x"
+        groupby = self.get_groupby(df, orient)
+        res = Jitter()(df, groupby, orient, {})
+        self.check_same(res, df, "y", "grp2", "width")
+        self.check_pos(res, df, "x", 0.2 * df["width"])
+        assert (res["x"] - df["x"]).abs().min() > 0
+
+    def test_width(self, df):
+
+        width = .4
+        orient = "x"
+        groupby = self.get_groupby(df, orient)
+        res = Jitter(width=width)(df, groupby, orient, {})
+        self.check_same(res, df, "y", "grp2", "width")
+        self.check_pos(res, df, "x", width * df["width"])
+
+    def test_x(self, df):
+
+        val = .2
+        orient = "x"
+        groupby = self.get_groupby(df, orient)
+        res = Jitter(x=val)(df, groupby, orient, {})
+        self.check_same(res, df, "y", "grp2", "width")
+        self.check_pos(res, df, "x", val)
+
+    def test_y(self, df):
+
+        val = .2
+        orient = "x"
+        groupby = self.get_groupby(df, orient)
+        res = Jitter(y=val)(df, groupby, orient, {})
+        self.check_same(res, df, "x", "grp2", "width")
+        self.check_pos(res, df, "y", val)
+
+    def test_seed(self, df):
+
+        kws = dict(width=.2, y=.1, seed=0)
+        orient = "x"
+        groupby = self.get_groupby(df, orient)
+        res1 = Jitter(**kws)(df, groupby, orient, {})
+        res2 = Jitter(**kws)(df, groupby, orient, {})
+        for var in "xy":
+            assert_series_equal(res1[var], res2[var])
+
+
+class TestDodge(MoveFixtures):
+
+    # First some very simple toy examples
+
+    def test_default(self, toy_df):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge()(toy_df, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3]),
+        assert_array_almost_equal(res["x"], [-.2, .2, 1.2])
+        assert_array_almost_equal(res["width"], [.4, .4, .4])
+
+    def test_fill(self, toy_df):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge(empty="fill")(toy_df, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3]),
+        assert_array_almost_equal(res["x"], [-.2, .2, 1])
+        assert_array_almost_equal(res["width"], [.4, .4, .8])
+
+    def test_drop(self, toy_df):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge("drop")(toy_df, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.2, .2, 1])
+        assert_array_almost_equal(res["width"], [.4, .4, .4])
+
+    def test_gap(self, toy_df):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge(gap=.25)(toy_df, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.2, .2, 1.2])
+        assert_array_almost_equal(res["width"], [.3, .3, .3])
+
+    def test_widths_default(self, toy_df_widths):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge()(toy_df_widths, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.08, .32, 1.1])
+        assert_array_almost_equal(res["width"], [.64, .16, .2])
+
+    def test_widths_fill(self, toy_df_widths):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge(empty="fill")(toy_df_widths, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.08, .32, 1])
+        assert_array_almost_equal(res["width"], [.64, .16, .4])
+
+    def test_widths_drop(self, toy_df_widths):
+
+        groupby = GroupBy(["x", "grp"])
+        res = Dodge(empty="drop")(toy_df_widths, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.08, .32, 1])
+        assert_array_almost_equal(res["width"], [.64, .16, .2])
+
+    def test_faceted_default(self, toy_df_facets):
+
+        groupby = GroupBy(["x", "grp", "col"])
+        res = Dodge()(toy_df_facets, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3, 1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.2, .2, .8, .2, .8, 2.2])
+        assert_array_almost_equal(res["width"], [.4] * 6)
+
+    def test_faceted_fill(self, toy_df_facets):
+
+        groupby = GroupBy(["x", "grp", "col"])
+        res = Dodge(empty="fill")(toy_df_facets, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3, 1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.2, .2, 1, 0, 1, 2])
+        assert_array_almost_equal(res["width"], [.4, .4, .8, .8, .8, .8])
+
+    def test_faceted_drop(self, toy_df_facets):
+
+        groupby = GroupBy(["x", "grp", "col"])
+        res = Dodge(empty="drop")(toy_df_facets, groupby, "x", {})
+
+        assert_array_equal(res["y"], [1, 2, 3, 1, 2, 3])
+        assert_array_almost_equal(res["x"], [-.2, .2, 1, 0, 1, 2])
+        assert_array_almost_equal(res["width"], [.4] * 6)
+
+    def test_orient(self, toy_df):
+
+        df = toy_df.assign(x=toy_df["y"], y=toy_df["x"])
+
+        groupby = GroupBy(["y", "grp"])
+        res = Dodge("drop")(df, groupby, "y", {})
+
+        assert_array_equal(res["x"], [1, 2, 3])
+        assert_array_almost_equal(res["y"], [-.2, .2, 1])
+        assert_array_almost_equal(res["width"], [.4, .4, .4])
+
+    # Now tests with slightly more complicated data
+
+    @pytest.mark.parametrize("grp", ["grp2", "grp3"])
+    def test_single_semantic(self, df, grp):
+
+        groupby = GroupBy(["x", grp])
+        res = Dodge()(df, groupby, "x", {})
+
+        levels = categorical_order(df[grp])
+        w, n = 0.8, len(levels)
+
+        shifts = np.linspace(0, w - w / n, n)
+        shifts -= shifts.mean()
+
+        assert_series_equal(res["y"], df["y"])
+        assert_series_equal(res["width"], df["width"] / n)
+
+        for val, shift in zip(levels, shifts):
+            rows = df[grp] == val
+            assert_series_equal(res.loc[rows, "x"], df.loc[rows, "x"] + shift)
+
+    def test_two_semantics(self, df):
+
+        groupby = GroupBy(["x", "grp2", "grp3"])
+        res = Dodge()(df, groupby, "x", {})
+
+        levels = categorical_order(df["grp2"]), categorical_order(df["grp3"])
+        w, n = 0.8, len(levels[0]) * len(levels[1])
+
+        shifts = np.linspace(0, w - w / n, n)
+        shifts -= shifts.mean()
+
+        assert_series_equal(res["y"], df["y"])
+        assert_series_equal(res["width"], df["width"] / n)
+
+        for (v2, v3), shift in zip(product(*levels), shifts):
+            rows = (df["grp2"] == v2) & (df["grp3"] == v3)
+            assert_series_equal(res.loc[rows, "x"], df.loc[rows, "x"] + shift)
+
+
+class TestStack(MoveFixtures):
+
+    def test_basic(self, toy_df):
+
+        groupby = GroupBy(["color", "group"])
+        res = Stack()(toy_df, groupby, "x", {})
+
+        assert_array_equal(res["x"], [0, 0, 1])
+        assert_array_equal(res["y"], [1, 3, 3])
+        assert_array_equal(res["baseline"], [0, 1, 0])
+
+    def test_faceted(self, toy_df_facets):
+
+        groupby = GroupBy(["color", "group"])
+        res = Stack()(toy_df_facets, groupby, "x", {})
+
+        assert_array_equal(res["x"], [0, 0, 1, 0, 1, 2])
+        assert_array_equal(res["y"], [1, 3, 3, 1, 2, 3])
+        assert_array_equal(res["baseline"], [0, 1, 0, 0, 0, 0])
+
+    def test_misssing_data(self, toy_df):
+
+        df = pd.DataFrame({
+            "x": [0, 0, 0],
+            "y": [2, np.nan, 1],
+            "baseline": [0, 0, 0],
+        })
+        res = Stack()(df, None, "x", {})
+        assert_array_equal(res["y"], [2, np.nan, 3])
+        assert_array_equal(res["baseline"], [0, np.nan, 2])
+
+    def test_baseline_homogeneity_check(self, toy_df):
+
+        toy_df["baseline"] = [0, 1, 2]
+        groupby = GroupBy(["color", "group"])
+        move = Stack()
+        err = "Stack move cannot be used when baselines"
+        with pytest.raises(RuntimeError, match=err):
+            move(toy_df, groupby, "x", {})
+
+
+class TestShift(MoveFixtures):
+
+    def test_default(self, toy_df):
+
+        gb = GroupBy(["color", "group"])
+        res = Shift()(toy_df, gb, "x", {})
+        for col in toy_df:
+            assert_series_equal(toy_df[col], res[col])
+
+    @pytest.mark.parametrize("x,y", [(.3, 0), (0, .2), (.1, .3)])
+    def test_moves(self, toy_df, x, y):
+
+        gb = GroupBy(["color", "group"])
+        res = Shift(x=x, y=y)(toy_df, gb, "x", {})
+        assert_array_equal(res["x"], toy_df["x"] + x)
+        assert_array_equal(res["y"], toy_df["y"] + y)
+
+
+class TestNorm(MoveFixtures):
+
+    @pytest.mark.parametrize("orient", ["x", "y"])
+    def test_default_no_groups(self, df, orient):
+
+        other = {"x": "y", "y": "x"}[orient]
+        gb = GroupBy(["null"])
+        res = Norm()(df, gb, orient, {})
+        assert res[other].max() == pytest.approx(1)
+
+    @pytest.mark.parametrize("orient", ["x", "y"])
+    def test_default_groups(self, df, orient):
+
+        other = {"x": "y", "y": "x"}[orient]
+        gb = GroupBy(["grp2"])
+        res = Norm()(df, gb, orient, {})
+        for _, grp in res.groupby("grp2"):
+            assert grp[other].max() == pytest.approx(1)
+
+    def test_sum(self, df):
+
+        gb = GroupBy(["null"])
+        res = Norm("sum")(df, gb, "x", {})
+        assert res["y"].sum() == pytest.approx(1)
+
+    def test_where(self, df):
+
+        gb = GroupBy(["null"])
+        res = Norm(where="x == 2")(df, gb, "x", {})
+        assert res.loc[res["x"] == 2, "y"].max() == pytest.approx(1)
+
+    def test_percent(self, df):
+
+        gb = GroupBy(["null"])
+        res = Norm(percent=True)(df, gb, "x", {})
+        assert res["y"].max() == pytest.approx(100)
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_plot.py b/testbed/mwaskom__seaborn/tests/_core/test_plot.py
new file mode 100644
index 0000000000000000000000000000000000000000..af81685e58e6956f78c805442140de4e7272f79a
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_plot.py
@@ -0,0 +1,2195 @@
+import io
+import xml
+import functools
+import itertools
+import warnings
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from PIL import Image
+
+import pytest
+from pandas.testing import assert_frame_equal, assert_series_equal
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn._core.plot import Plot, Default
+from seaborn._core.scales import Continuous, Nominal, Temporal
+from seaborn._core.moves import Move, Shift, Dodge
+from seaborn._core.rules import categorical_order
+from seaborn._core.exceptions import PlotSpecError
+from seaborn._marks.base import Mark
+from seaborn._stats.base import Stat
+from seaborn._marks.dot import Dot
+from seaborn._stats.aggregation import Agg
+from seaborn.utils import _version_predates
+
+assert_vector_equal = functools.partial(
+    # TODO do we care about int/float dtype consistency?
+    # Eventually most variables become floats ... but does it matter when?
+    # (Or rather, does it matter if it happens too early?)
+    assert_series_equal, check_names=False, check_dtype=False,
+)
+
+
+def assert_gridspec_shape(ax, nrows=1, ncols=1):
+
+    gs = ax.get_gridspec()
+    assert gs.nrows == nrows
+    assert gs.ncols == ncols
+
+
+class MockMark(Mark):
+
+    _grouping_props = ["color"]
+
+    def __init__(self, *args, **kwargs):
+
+        super().__init__(*args, **kwargs)
+        self.passed_keys = []
+        self.passed_data = []
+        self.passed_axes = []
+        self.passed_scales = None
+        self.passed_orient = None
+        self.n_splits = 0
+
+    def _plot(self, split_gen, scales, orient):
+
+        for keys, data, ax in split_gen():
+            self.n_splits += 1
+            self.passed_keys.append(keys)
+            self.passed_data.append(data)
+            self.passed_axes.append(ax)
+
+        self.passed_scales = scales
+        self.passed_orient = orient
+
+    def _legend_artist(self, variables, value, scales):
+
+        a = mpl.lines.Line2D([], [])
+        a.variables = variables
+        a.value = value
+        return a
+
+
+class TestInit:
+
+    def test_empty(self):
+
+        p = Plot()
+        assert p._data.source_data is None
+        assert p._data.source_vars == {}
+
+    def test_data_only(self, long_df):
+
+        p = Plot(long_df)
+        assert p._data.source_data is long_df
+        assert p._data.source_vars == {}
+
+    def test_df_and_named_variables(self, long_df):
+
+        variables = {"x": "a", "y": "z"}
+        p = Plot(long_df, **variables)
+        for var, col in variables.items():
+            assert_vector_equal(p._data.frame[var], long_df[col])
+        assert p._data.source_data is long_df
+        assert p._data.source_vars.keys() == variables.keys()
+
+    def test_df_and_mixed_variables(self, long_df):
+
+        variables = {"x": "a", "y": long_df["z"]}
+        p = Plot(long_df, **variables)
+        for var, col in variables.items():
+            if isinstance(col, str):
+                assert_vector_equal(p._data.frame[var], long_df[col])
+            else:
+                assert_vector_equal(p._data.frame[var], col)
+        assert p._data.source_data is long_df
+        assert p._data.source_vars.keys() == variables.keys()
+
+    def test_vector_variables_only(self, long_df):
+
+        variables = {"x": long_df["a"], "y": long_df["z"]}
+        p = Plot(**variables)
+        for var, col in variables.items():
+            assert_vector_equal(p._data.frame[var], col)
+        assert p._data.source_data is None
+        assert p._data.source_vars.keys() == variables.keys()
+
+    def test_vector_variables_no_index(self, long_df):
+
+        variables = {"x": long_df["a"].to_numpy(), "y": long_df["z"].to_list()}
+        p = Plot(**variables)
+        for var, col in variables.items():
+            assert_vector_equal(p._data.frame[var], pd.Series(col))
+            assert p._data.names[var] is None
+        assert p._data.source_data is None
+        assert p._data.source_vars.keys() == variables.keys()
+
+    def test_data_only_named(self, long_df):
+
+        p = Plot(data=long_df)
+        assert p._data.source_data is long_df
+        assert p._data.source_vars == {}
+
+    def test_positional_and_named_data(self, long_df):
+
+        err = "`data` given by both name and position"
+        with pytest.raises(TypeError, match=err):
+            Plot(long_df, data=long_df)
+
+    @pytest.mark.parametrize("var", ["x", "y"])
+    def test_positional_and_named_xy(self, long_df, var):
+
+        err = f"`{var}` given by both name and position"
+        with pytest.raises(TypeError, match=err):
+            Plot(long_df, "a", "b", **{var: "c"})
+
+    def test_positional_data_x_y(self, long_df):
+
+        p = Plot(long_df, "a", "b")
+        assert p._data.source_data is long_df
+        assert list(p._data.source_vars) == ["x", "y"]
+
+    def test_positional_x_y(self, long_df):
+
+        p = Plot(long_df["a"], long_df["b"])
+        assert p._data.source_data is None
+        assert list(p._data.source_vars) == ["x", "y"]
+
+    def test_positional_data_x(self, long_df):
+
+        p = Plot(long_df, "a")
+        assert p._data.source_data is long_df
+        assert list(p._data.source_vars) == ["x"]
+
+    def test_positional_x(self, long_df):
+
+        p = Plot(long_df["a"])
+        assert p._data.source_data is None
+        assert list(p._data.source_vars) == ["x"]
+
+    def test_positional_too_many(self, long_df):
+
+        err = r"Plot\(\) accepts no more than 3 positional arguments \(data, x, y\)"
+        with pytest.raises(TypeError, match=err):
+            Plot(long_df, "x", "y", "z")
+
+    def test_unknown_keywords(self, long_df):
+
+        err = r"Plot\(\) got unexpected keyword argument\(s\): bad"
+        with pytest.raises(TypeError, match=err):
+            Plot(long_df, bad="x")
+
+
+class TestLayerAddition:
+
+    def test_without_data(self, long_df):
+
+        p = Plot(long_df, x="x", y="y").add(MockMark()).plot()
+        layer, = p._layers
+        assert_frame_equal(p._data.frame, layer["data"].frame, check_dtype=False)
+
+    def test_with_new_variable_by_name(self, long_df):
+
+        p = Plot(long_df, x="x").add(MockMark(), y="y").plot()
+        layer, = p._layers
+        assert layer["data"].frame.columns.to_list() == ["x", "y"]
+        for var in "xy":
+            assert_vector_equal(layer["data"].frame[var], long_df[var])
+
+    def test_with_new_variable_by_vector(self, long_df):
+
+        p = Plot(long_df, x="x").add(MockMark(), y=long_df["y"]).plot()
+        layer, = p._layers
+        assert layer["data"].frame.columns.to_list() == ["x", "y"]
+        for var in "xy":
+            assert_vector_equal(layer["data"].frame[var], long_df[var])
+
+    def test_with_late_data_definition(self, long_df):
+
+        p = Plot().add(MockMark(), data=long_df, x="x", y="y").plot()
+        layer, = p._layers
+        assert layer["data"].frame.columns.to_list() == ["x", "y"]
+        for var in "xy":
+            assert_vector_equal(layer["data"].frame[var], long_df[var])
+
+    def test_with_new_data_definition(self, long_df):
+
+        long_df_sub = long_df.sample(frac=.5)
+
+        p = Plot(long_df, x="x", y="y").add(MockMark(), data=long_df_sub).plot()
+        layer, = p._layers
+        assert layer["data"].frame.columns.to_list() == ["x", "y"]
+        for var in "xy":
+            assert_vector_equal(
+                layer["data"].frame[var], long_df_sub[var].reindex(long_df.index)
+            )
+
+    def test_drop_variable(self, long_df):
+
+        p = Plot(long_df, x="x", y="y").add(MockMark(), y=None).plot()
+        layer, = p._layers
+        assert layer["data"].frame.columns.to_list() == ["x"]
+        assert_vector_equal(layer["data"].frame["x"], long_df["x"], check_dtype=False)
+
+    @pytest.mark.xfail(reason="Need decision on default stat")
+    def test_stat_default(self):
+
+        class MarkWithDefaultStat(Mark):
+            default_stat = Stat
+
+        p = Plot().add(MarkWithDefaultStat())
+        layer, = p._layers
+        assert layer["stat"].__class__ is Stat
+
+    def test_stat_nondefault(self):
+
+        class MarkWithDefaultStat(Mark):
+            default_stat = Stat
+
+        class OtherMockStat(Stat):
+            pass
+
+        p = Plot().add(MarkWithDefaultStat(), OtherMockStat())
+        layer, = p._layers
+        assert layer["stat"].__class__ is OtherMockStat
+
+    @pytest.mark.parametrize(
+        "arg,expected",
+        [("x", "x"), ("y", "y"), ("v", "x"), ("h", "y")],
+    )
+    def test_orient(self, arg, expected):
+
+        class MockStatTrackOrient(Stat):
+            def __call__(self, data, groupby, orient, scales):
+                self.orient_at_call = orient
+                return data
+
+        class MockMoveTrackOrient(Move):
+            def __call__(self, data, groupby, orient, scales):
+                self.orient_at_call = orient
+                return data
+
+        s = MockStatTrackOrient()
+        m = MockMoveTrackOrient()
+        Plot(x=[1, 2, 3], y=[1, 2, 3]).add(MockMark(), s, m, orient=arg).plot()
+
+        assert s.orient_at_call == expected
+        assert m.orient_at_call == expected
+
+    def test_variable_list(self, long_df):
+
+        p = Plot(long_df, x="x", y="y")
+        assert p._variables == ["x", "y"]
+
+        p = Plot(long_df).add(MockMark(), x="x", y="y")
+        assert p._variables == ["x", "y"]
+
+        p = Plot(long_df, y="x", color="a").add(MockMark(), x="y")
+        assert p._variables == ["y", "color", "x"]
+
+        p = Plot(long_df, x="x", y="y", color="a").add(MockMark(), color=None)
+        assert p._variables == ["x", "y", "color"]
+
+        p = (
+            Plot(long_df, x="x", y="y")
+            .add(MockMark(), color="a")
+            .add(MockMark(), alpha="s")
+        )
+        assert p._variables == ["x", "y", "color", "alpha"]
+
+        p = Plot(long_df, y="x").pair(x=["a", "b"])
+        assert p._variables == ["y", "x0", "x1"]
+
+    def test_type_checks(self):
+
+        p = Plot()
+        with pytest.raises(TypeError, match="mark must be a Mark instance"):
+            p.add(MockMark)
+
+        class MockStat(Stat):
+            pass
+
+        class MockMove(Move):
+            pass
+
+        err = "Transforms must have at most one Stat type"
+
+        with pytest.raises(TypeError, match=err):
+            p.add(MockMark(), MockStat)
+
+        with pytest.raises(TypeError, match=err):
+            p.add(MockMark(), MockMove(), MockStat())
+
+        with pytest.raises(TypeError, match=err):
+            p.add(MockMark(), MockMark(), MockStat())
+
+
+class TestScaling:
+
+    def test_inference(self, long_df):
+
+        for col, scale_type in zip("zat", ["Continuous", "Nominal", "Temporal"]):
+            p = Plot(long_df, x=col, y=col).add(MockMark()).plot()
+            for var in "xy":
+                assert p._scales[var].__class__.__name__ == scale_type
+
+    def test_inference_from_layer_data(self):
+
+        p = Plot().add(MockMark(), x=["a", "b", "c"]).plot()
+        assert p._scales["x"]("b") == 1
+
+    def test_inference_joins(self):
+
+        p = (
+            Plot(y=pd.Series([1, 2, 3, 4]))
+            .add(MockMark(), x=pd.Series([1, 2]))
+            .add(MockMark(), x=pd.Series(["a", "b"], index=[2, 3]))
+            .plot()
+        )
+        assert p._scales["x"]("a") == 2
+
+    def test_inferred_categorical_converter(self):
+
+        p = Plot(x=["b", "c", "a"]).add(MockMark()).plot()
+        ax = p._figure.axes[0]
+        assert ax.xaxis.convert_units("c") == 1
+
+    def test_explicit_categorical_converter(self):
+
+        p = Plot(y=[2, 1, 3]).scale(y=Nominal()).add(MockMark()).plot()
+        ax = p._figure.axes[0]
+        assert ax.yaxis.convert_units("3") == 2
+
+    @pytest.mark.xfail(reason="Temporal auto-conversion not implemented")
+    def test_categorical_as_datetime(self):
+
+        dates = ["1970-01-03", "1970-01-02", "1970-01-04"]
+        p = Plot(x=dates).scale(...).add(MockMark()).plot()
+        p  # TODO
+        ...
+
+    def test_faceted_log_scale(self):
+
+        p = Plot(y=[1, 10]).facet(col=["a", "b"]).scale(y="log").plot()
+        for ax in p._figure.axes:
+            xfm = ax.yaxis.get_transform().transform
+            assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])
+
+    def test_paired_single_log_scale(self):
+
+        x0, x1 = [1, 2, 3], [1, 10, 100]
+        p = Plot().pair(x=[x0, x1]).scale(x1="log").plot()
+        ax_lin, ax_log = p._figure.axes
+        xfm_lin = ax_lin.xaxis.get_transform().transform
+        assert_array_equal(xfm_lin([1, 10, 100]), [1, 10, 100])
+        xfm_log = ax_log.xaxis.get_transform().transform
+        assert_array_equal(xfm_log([1, 10, 100]), [0, 1, 2])
+
+    @pytest.mark.xfail(reason="Custom log scale needs log name for consistency")
+    def test_log_scale_name(self):
+
+        p = Plot().scale(x="log").plot()
+        ax = p._figure.axes[0]
+        assert ax.get_xscale() == "log"
+        assert ax.get_yscale() == "linear"
+
+    def test_mark_data_log_transform_is_inverted(self, long_df):
+
+        col = "z"
+        m = MockMark()
+        Plot(long_df, x=col).scale(x="log").add(m).plot()
+        assert_vector_equal(m.passed_data[0]["x"], long_df[col])
+
+    def test_mark_data_log_transfrom_with_stat(self, long_df):
+
+        class Mean(Stat):
+            group_by_orient = True
+
+            def __call__(self, data, groupby, orient, scales):
+                other = {"x": "y", "y": "x"}[orient]
+                return groupby.agg(data, {other: "mean"})
+
+        col = "z"
+        grouper = "a"
+        m = MockMark()
+        s = Mean()
+
+        Plot(long_df, x=grouper, y=col).scale(y="log").add(m, s).plot()
+
+        expected = (
+            long_df[col]
+            .pipe(np.log)
+            .groupby(long_df[grouper], sort=False)
+            .mean()
+            .pipe(np.exp)
+            .reset_index(drop=True)
+        )
+        assert_vector_equal(m.passed_data[0]["y"], expected)
+
+    def test_mark_data_from_categorical(self, long_df):
+
+        col = "a"
+        m = MockMark()
+        Plot(long_df, x=col).add(m).plot()
+
+        levels = categorical_order(long_df[col])
+        level_map = {x: float(i) for i, x in enumerate(levels)}
+        assert_vector_equal(m.passed_data[0]["x"], long_df[col].map(level_map))
+
+    def test_mark_data_from_datetime(self, long_df):
+
+        col = "t"
+        m = MockMark()
+        Plot(long_df, x=col).add(m).plot()
+
+        expected = long_df[col].map(mpl.dates.date2num)
+        assert_vector_equal(m.passed_data[0]["x"], expected)
+
+    def test_computed_var_ticks(self, long_df):
+
+        class Identity(Stat):
+            def __call__(self, df, groupby, orient, scales):
+                other = {"x": "y", "y": "x"}[orient]
+                return df.assign(**{other: df[orient]})
+
+        tick_locs = [1, 2, 5]
+        scale = Continuous().tick(at=tick_locs)
+        p = Plot(long_df, "x").add(MockMark(), Identity()).scale(y=scale).plot()
+        ax = p._figure.axes[0]
+        assert_array_equal(ax.get_yticks(), tick_locs)
+
+    def test_computed_var_transform(self, long_df):
+
+        class Identity(Stat):
+            def __call__(self, df, groupby, orient, scales):
+                other = {"x": "y", "y": "x"}[orient]
+                return df.assign(**{other: df[orient]})
+
+        p = Plot(long_df, "x").add(MockMark(), Identity()).scale(y="log").plot()
+        ax = p._figure.axes[0]
+        xfm = ax.yaxis.get_transform().transform
+        assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])
+
+    def test_explicit_range_with_axis_scaling(self):
+
+        x = [1, 2, 3]
+        ymin = [10, 100, 1000]
+        ymax = [20, 200, 2000]
+        m = MockMark()
+        Plot(x=x, ymin=ymin, ymax=ymax).add(m).scale(y="log").plot()
+        assert_vector_equal(m.passed_data[0]["ymax"], pd.Series(ymax, dtype=float))
+
+    def test_derived_range_with_axis_scaling(self):
+
+        class AddOne(Stat):
+            def __call__(self, df, *args):
+                return df.assign(ymax=df["y"] + 1)
+
+        x = y = [1, 10, 100]
+
+        m = MockMark()
+        Plot(x, y).add(m, AddOne()).scale(y="log").plot()
+        assert_vector_equal(m.passed_data[0]["ymax"], pd.Series([10., 100., 1000.]))
+
+    def test_facet_categories(self):
+
+        m = MockMark()
+        p = Plot(x=["a", "b", "a", "c"]).facet(col=["x", "x", "y", "y"]).add(m).plot()
+        ax1, ax2 = p._figure.axes
+        assert len(ax1.get_xticks()) == 3
+        assert len(ax2.get_xticks()) == 3
+        assert_vector_equal(m.passed_data[0]["x"], pd.Series([0., 1.], [0, 1]))
+        assert_vector_equal(m.passed_data[1]["x"], pd.Series([0., 2.], [2, 3]))
+
+    def test_facet_categories_unshared(self):
+
+        m = MockMark()
+        p = (
+            Plot(x=["a", "b", "a", "c"])
+            .facet(col=["x", "x", "y", "y"])
+            .share(x=False)
+            .add(m)
+            .plot()
+        )
+        ax1, ax2 = p._figure.axes
+        assert len(ax1.get_xticks()) == 2
+        assert len(ax2.get_xticks()) == 2
+        assert_vector_equal(m.passed_data[0]["x"], pd.Series([0., 1.], [0, 1]))
+        assert_vector_equal(m.passed_data[1]["x"], pd.Series([0., 1.], [2, 3]))
+
+    def test_facet_categories_single_dim_shared(self):
+
+        data = [
+            ("a", 1, 1), ("b", 1, 1),
+            ("a", 1, 2), ("c", 1, 2),
+            ("b", 2, 1), ("d", 2, 1),
+            ("e", 2, 2), ("e", 2, 1),
+        ]
+        df = pd.DataFrame(data, columns=["x", "row", "col"]).assign(y=1)
+        m = MockMark()
+        p = (
+            Plot(df, x="x")
+            .facet(row="row", col="col")
+            .add(m)
+            .share(x="row")
+            .plot()
+        )
+
+        axs = p._figure.axes
+        for ax in axs:
+            assert ax.get_xticks() == [0, 1, 2]
+
+        assert_vector_equal(m.passed_data[0]["x"], pd.Series([0., 1.], [0, 1]))
+        assert_vector_equal(m.passed_data[1]["x"], pd.Series([0., 2.], [2, 3]))
+        assert_vector_equal(m.passed_data[2]["x"], pd.Series([0., 1., 2.], [4, 5, 7]))
+        assert_vector_equal(m.passed_data[3]["x"], pd.Series([2.], [6]))
+
+    def test_pair_categories(self):
+
+        data = [("a", "a"), ("b", "c")]
+        df = pd.DataFrame(data, columns=["x1", "x2"]).assign(y=1)
+        m = MockMark()
+        p = Plot(df, y="y").pair(x=["x1", "x2"]).add(m).plot()
+
+        ax1, ax2 = p._figure.axes
+        assert ax1.get_xticks() == [0, 1]
+        assert ax2.get_xticks() == [0, 1]
+        assert_vector_equal(m.passed_data[0]["x"], pd.Series([0., 1.], [0, 1]))
+        assert_vector_equal(m.passed_data[1]["x"], pd.Series([0., 1.], [0, 1]))
+
+    @pytest.mark.xfail(
+        _version_predates(mpl, "3.4.0"),
+        reason="Sharing paired categorical axes requires matplotlib>3.4.0"
+    )
+    def test_pair_categories_shared(self):
+
+        data = [("a", "a"), ("b", "c")]
+        df = pd.DataFrame(data, columns=["x1", "x2"]).assign(y=1)
+        m = MockMark()
+        p = Plot(df, y="y").pair(x=["x1", "x2"]).add(m).share(x=True).plot()
+
+        for ax in p._figure.axes:
+            assert ax.get_xticks() == [0, 1, 2]
+        print(m.passed_data)
+        assert_vector_equal(m.passed_data[0]["x"], pd.Series([0., 1.], [0, 1]))
+        assert_vector_equal(m.passed_data[1]["x"], pd.Series([0., 2.], [0, 1]))
+
+    def test_identity_mapping_linewidth(self):
+
+        m = MockMark()
+        x = y = [1, 2, 3, 4, 5]
+        lw = pd.Series([.5, .1, .1, .9, 3])
+        Plot(x=x, y=y, linewidth=lw).scale(linewidth=None).add(m).plot()
+        assert_vector_equal(m.passed_scales["linewidth"](lw), lw)
+
+    def test_pair_single_coordinate_stat_orient(self, long_df):
+
+        class MockStat(Stat):
+            def __call__(self, data, groupby, orient, scales):
+                self.orient = orient
+                return data
+
+        s = MockStat()
+        Plot(long_df).pair(x=["x", "y"]).add(MockMark(), s).plot()
+        assert s.orient == "x"
+
+    def test_inferred_nominal_passed_to_stat(self):
+
+        class MockStat(Stat):
+            def __call__(self, data, groupby, orient, scales):
+                self.scales = scales
+                return data
+
+        s = MockStat()
+        y = ["a", "a", "b", "c"]
+        Plot(y=y).add(MockMark(), s).plot()
+        assert s.scales["y"].__class__.__name__ == "Nominal"
+
+    # TODO where should RGB consistency be enforced?
+    @pytest.mark.xfail(
+        reason="Correct output representation for color with identity scale undefined"
+    )
+    def test_identity_mapping_color_strings(self):
+
+        m = MockMark()
+        x = y = [1, 2, 3]
+        c = ["C0", "C2", "C1"]
+        Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()
+        expected = mpl.colors.to_rgba_array(c)[:, :3]
+        assert_array_equal(m.passed_scales["color"](c), expected)
+
+    def test_identity_mapping_color_tuples(self):
+
+        m = MockMark()
+        x = y = [1, 2, 3]
+        c = [(1, 0, 0), (0, 1, 0), (1, 0, 0)]
+        Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()
+        expected = mpl.colors.to_rgba_array(c)[:, :3]
+        assert_array_equal(m.passed_scales["color"](c), expected)
+
+    @pytest.mark.xfail(
+        reason="Need decision on what to do with scale defined for unused variable"
+    )
+    def test_undefined_variable_raises(self):
+
+        p = Plot(x=[1, 2, 3], color=["a", "b", "c"]).scale(y=Continuous())
+        err = r"No data found for variable\(s\) with explicit scale: {'y'}"
+        with pytest.raises(RuntimeError, match=err):
+            p.plot()
+
+    def test_nominal_x_axis_tweaks(self):
+
+        p = Plot(x=["a", "b", "c"], y=[1, 2, 3])
+        ax1 = p.plot()._figure.axes[0]
+        assert ax1.get_xlim() == (-.5, 2.5)
+        assert not any(x.get_visible() for x in ax1.xaxis.get_gridlines())
+
+        lim = (-1, 2.1)
+        ax2 = p.limit(x=lim).plot()._figure.axes[0]
+        assert ax2.get_xlim() == lim
+
+    def test_nominal_y_axis_tweaks(self):
+
+        p = Plot(x=[1, 2, 3], y=["a", "b", "c"])
+        ax1 = p.plot()._figure.axes[0]
+        assert ax1.get_ylim() == (2.5, -.5)
+        assert not any(y.get_visible() for y in ax1.yaxis.get_gridlines())
+
+        lim = (-1, 2.1)
+        ax2 = p.limit(y=lim).plot()._figure.axes[0]
+        assert ax2.get_ylim() == lim
+
+
+class TestPlotting:
+
+    def test_matplotlib_object_creation(self):
+
+        p = Plot().plot()
+        assert isinstance(p._figure, mpl.figure.Figure)
+        for sub in p._subplots:
+            assert isinstance(sub["ax"], mpl.axes.Axes)
+
+    def test_empty(self):
+
+        m = MockMark()
+        Plot().add(m).plot()
+        assert m.n_splits == 0
+        assert not m.passed_data
+
+    def test_no_orient_variance(self):
+
+        x, y = [0, 0], [1, 2]
+        m = MockMark()
+        Plot(x, y).add(m).plot()
+        assert_array_equal(m.passed_data[0]["x"], x)
+        assert_array_equal(m.passed_data[0]["y"], y)
+
+    def test_single_split_single_layer(self, long_df):
+
+        m = MockMark()
+        p = Plot(long_df, x="f", y="z").add(m).plot()
+        assert m.n_splits == 1
+
+        assert m.passed_keys[0] == {}
+        assert m.passed_axes == [sub["ax"] for sub in p._subplots]
+        for col in p._data.frame:
+            assert_series_equal(m.passed_data[0][col], p._data.frame[col])
+
+    def test_single_split_multi_layer(self, long_df):
+
+        vs = [{"color": "a", "linewidth": "z"}, {"color": "b", "pattern": "c"}]
+
+        class NoGroupingMark(MockMark):
+            _grouping_props = []
+
+        ms = [NoGroupingMark(), NoGroupingMark()]
+        Plot(long_df).add(ms[0], **vs[0]).add(ms[1], **vs[1]).plot()
+
+        for m, v in zip(ms, vs):
+            for var, col in v.items():
+                assert_vector_equal(m.passed_data[0][var], long_df[col])
+
+    def check_splits_single_var(
+        self, data, mark, data_vars, split_var, split_col, split_keys
+    ):
+
+        assert mark.n_splits == len(split_keys)
+        assert mark.passed_keys == [{split_var: key} for key in split_keys]
+
+        for i, key in enumerate(split_keys):
+
+            split_data = data[data[split_col] == key]
+            for var, col in data_vars.items():
+                assert_array_equal(mark.passed_data[i][var], split_data[col])
+
+    def check_splits_multi_vars(
+        self, data, mark, data_vars, split_vars, split_cols, split_keys
+    ):
+
+        assert mark.n_splits == np.prod([len(ks) for ks in split_keys])
+
+        expected_keys = [
+            dict(zip(split_vars, level_keys))
+            for level_keys in itertools.product(*split_keys)
+        ]
+        assert mark.passed_keys == expected_keys
+
+        for i, keys in enumerate(itertools.product(*split_keys)):
+
+            use_rows = pd.Series(True, data.index)
+            for var, col, key in zip(split_vars, split_cols, keys):
+                use_rows &= data[col] == key
+            split_data = data[use_rows]
+            for var, col in data_vars.items():
+                assert_array_equal(mark.passed_data[i][var], split_data[col])
+
+    @pytest.mark.parametrize(
+        "split_var", [
+            "color",  # explicitly declared on the Mark
+            "group",  # implicitly used for all Mark classes
+        ])
+    def test_one_grouping_variable(self, long_df, split_var):
+
+        split_col = "a"
+        data_vars = {"x": "f", "y": "z", split_var: split_col}
+
+        m = MockMark()
+        p = Plot(long_df, **data_vars).add(m).plot()
+
+        split_keys = categorical_order(long_df[split_col])
+        sub, *_ = p._subplots
+        assert m.passed_axes == [sub["ax"] for _ in split_keys]
+        self.check_splits_single_var(
+            long_df, m, data_vars, split_var, split_col, split_keys
+        )
+
+    def test_two_grouping_variables(self, long_df):
+
+        split_vars = ["color", "group"]
+        split_cols = ["a", "b"]
+        data_vars = {"y": "z", **{var: col for var, col in zip(split_vars, split_cols)}}
+
+        m = MockMark()
+        p = Plot(long_df, **data_vars).add(m).plot()
+
+        split_keys = [categorical_order(long_df[col]) for col in split_cols]
+        sub, *_ = p._subplots
+        assert m.passed_axes == [
+            sub["ax"] for _ in itertools.product(*split_keys)
+        ]
+        self.check_splits_multi_vars(
+            long_df, m, data_vars, split_vars, split_cols, split_keys
+        )
+
+    def test_specified_width(self, long_df):
+
+        m = MockMark()
+        Plot(long_df, x="x", y="y").add(m, width="z").plot()
+        assert_array_almost_equal(m.passed_data[0]["width"], long_df["z"])
+
+    def test_facets_no_subgroups(self, long_df):
+
+        split_var = "col"
+        split_col = "b"
+        data_vars = {"x": "f", "y": "z"}
+
+        m = MockMark()
+        p = Plot(long_df, **data_vars).facet(**{split_var: split_col}).add(m).plot()
+
+        split_keys = categorical_order(long_df[split_col])
+        assert m.passed_axes == list(p._figure.axes)
+        self.check_splits_single_var(
+            long_df, m, data_vars, split_var, split_col, split_keys
+        )
+
+    def test_facets_one_subgroup(self, long_df):
+
+        facet_var, facet_col = fx = "col", "a"
+        group_var, group_col = gx = "group", "b"
+        split_vars, split_cols = zip(*[fx, gx])
+        data_vars = {"x": "f", "y": "z", group_var: group_col}
+
+        m = MockMark()
+        p = (
+            Plot(long_df, **data_vars)
+            .facet(**{facet_var: facet_col})
+            .add(m)
+            .plot()
+        )
+
+        split_keys = [categorical_order(long_df[col]) for col in [facet_col, group_col]]
+        assert m.passed_axes == [
+            ax
+            for ax in list(p._figure.axes)
+            for _ in categorical_order(long_df[group_col])
+        ]
+        self.check_splits_multi_vars(
+            long_df, m, data_vars, split_vars, split_cols, split_keys
+        )
+
+    def test_layer_specific_facet_disabling(self, long_df):
+
+        axis_vars = {"x": "y", "y": "z"}
+        row_var = "a"
+
+        m = MockMark()
+        p = Plot(long_df, **axis_vars).facet(row=row_var).add(m, row=None).plot()
+
+        col_levels = categorical_order(long_df[row_var])
+        assert len(p._figure.axes) == len(col_levels)
+
+        for data in m.passed_data:
+            for var, col in axis_vars.items():
+                assert_vector_equal(data[var], long_df[col])
+
+    def test_paired_variables(self, long_df):
+
+        x = ["x", "y"]
+        y = ["f", "z"]
+
+        m = MockMark()
+        Plot(long_df).pair(x, y).add(m).plot()
+
+        var_product = itertools.product(x, y)
+
+        for data, (x_i, y_i) in zip(m.passed_data, var_product):
+            assert_vector_equal(data["x"], long_df[x_i].astype(float))
+            assert_vector_equal(data["y"], long_df[y_i].astype(float))
+
+    def test_paired_one_dimension(self, long_df):
+
+        x = ["y", "z"]
+
+        m = MockMark()
+        Plot(long_df).pair(x).add(m).plot()
+
+        for data, x_i in zip(m.passed_data, x):
+            assert_vector_equal(data["x"], long_df[x_i].astype(float))
+
+    def test_paired_variables_one_subset(self, long_df):
+
+        x = ["x", "y"]
+        y = ["f", "z"]
+        group = "a"
+
+        long_df["x"] = long_df["x"].astype(float)  # simplify vector comparison
+
+        m = MockMark()
+        Plot(long_df, group=group).pair(x, y).add(m).plot()
+
+        groups = categorical_order(long_df[group])
+        var_product = itertools.product(x, y, groups)
+
+        for data, (x_i, y_i, g_i) in zip(m.passed_data, var_product):
+            rows = long_df[group] == g_i
+            assert_vector_equal(data["x"], long_df.loc[rows, x_i])
+            assert_vector_equal(data["y"], long_df.loc[rows, y_i])
+
+    def test_paired_and_faceted(self, long_df):
+
+        x = ["y", "z"]
+        y = "f"
+        row = "c"
+
+        m = MockMark()
+        Plot(long_df, y=y).facet(row=row).pair(x).add(m).plot()
+
+        facets = categorical_order(long_df[row])
+        var_product = itertools.product(x, facets)
+
+        for data, (x_i, f_i) in zip(m.passed_data, var_product):
+            rows = long_df[row] == f_i
+            assert_vector_equal(data["x"], long_df.loc[rows, x_i])
+            assert_vector_equal(data["y"], long_df.loc[rows, y])
+
+    def test_theme_default(self):
+
+        p = Plot().plot()
+        assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), "#EAEAF2")
+
+    def test_theme_params(self):
+
+        color = ".888"
+        p = Plot().theme({"axes.facecolor": color}).plot()
+        assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), color)
+
+    def test_theme_error(self):
+
+        p = Plot()
+        with pytest.raises(TypeError, match=r"theme\(\) takes 1 positional"):
+            p.theme("arg1", "arg2")
+
+    def test_theme_validation(self):
+
+        p = Plot()
+        # You'd think matplotlib would raise a TypeError here, but it doesn't
+        with pytest.raises(ValueError, match="Key axes.linewidth:"):
+            p.theme({"axes.linewidth": "thick"})
+
+        with pytest.raises(KeyError, match="not.a.key is not a valid rc"):
+            p.theme({"not.a.key": True})
+
+    def test_stat(self, long_df):
+
+        orig_df = long_df.copy(deep=True)
+
+        m = MockMark()
+        Plot(long_df, x="a", y="z").add(m, Agg()).plot()
+
+        expected = long_df.groupby("a", sort=False)["z"].mean().reset_index(drop=True)
+        assert_vector_equal(m.passed_data[0]["y"], expected)
+
+        assert_frame_equal(long_df, orig_df)   # Test data was not mutated
+
+    def test_move(self, long_df):
+
+        orig_df = long_df.copy(deep=True)
+
+        m = MockMark()
+        Plot(long_df, x="z", y="z").add(m, Shift(x=1)).plot()
+        assert_vector_equal(m.passed_data[0]["x"], long_df["z"] + 1)
+        assert_vector_equal(m.passed_data[0]["y"], long_df["z"])
+
+        assert_frame_equal(long_df, orig_df)   # Test data was not mutated
+
+    def test_stat_and_move(self, long_df):
+
+        m = MockMark()
+        Plot(long_df, x="a", y="z").add(m, Agg(), Shift(y=1)).plot()
+
+        expected = long_df.groupby("a", sort=False)["z"].mean().reset_index(drop=True)
+        assert_vector_equal(m.passed_data[0]["y"], expected + 1)
+
+    def test_stat_log_scale(self, long_df):
+
+        orig_df = long_df.copy(deep=True)
+
+        m = MockMark()
+        Plot(long_df, x="a", y="z").add(m, Agg()).scale(y="log").plot()
+
+        x = long_df["a"]
+        y = np.log10(long_df["z"])
+        expected = y.groupby(x, sort=False).mean().reset_index(drop=True)
+        assert_vector_equal(m.passed_data[0]["y"], 10 ** expected)
+
+        assert_frame_equal(long_df, orig_df)   # Test data was not mutated
+
+    def test_move_log_scale(self, long_df):
+
+        m = MockMark()
+        Plot(
+            long_df, x="z", y="z"
+        ).scale(x="log").add(m, Shift(x=-1)).plot()
+        assert_vector_equal(m.passed_data[0]["x"], long_df["z"] / 10)
+
+    def test_multi_move(self, long_df):
+
+        m = MockMark()
+        move_stack = [Shift(1), Shift(2)]
+        Plot(long_df, x="x", y="y").add(m, *move_stack).plot()
+        assert_vector_equal(m.passed_data[0]["x"], long_df["x"] + 3)
+
+    def test_multi_move_with_pairing(self, long_df):
+        m = MockMark()
+        move_stack = [Shift(1), Shift(2)]
+        Plot(long_df, x="x").pair(y=["y", "z"]).add(m, *move_stack).plot()
+        for frame in m.passed_data:
+            assert_vector_equal(frame["x"], long_df["x"] + 3)
+
+    def test_move_with_range(self, long_df):
+
+        x = [0, 0, 1, 1, 2, 2]
+        group = [0, 1, 0, 1, 0, 1]
+        ymin = np.arange(6)
+        ymax = np.arange(6) * 2
+
+        m = MockMark()
+        Plot(x=x, group=group, ymin=ymin, ymax=ymax).add(m, Dodge()).plot()
+
+        signs = [-1, +1]
+        for i, df in m.passed_data[0].groupby("group"):
+            assert_array_equal(df["x"], np.arange(3) + signs[i] * 0.2)
+
+    def test_methods_clone(self, long_df):
+
+        p1 = Plot(long_df, "x", "y")
+        p2 = p1.add(MockMark()).facet("a")
+
+        assert p1 is not p2
+        assert not p1._layers
+        assert not p1._facet_spec
+
+    def test_default_is_no_pyplot(self):
+
+        p = Plot().plot()
+
+        assert not plt.get_fignums()
+        assert isinstance(p._figure, mpl.figure.Figure)
+
+    def test_with_pyplot(self):
+
+        p = Plot().plot(pyplot=True)
+
+        assert len(plt.get_fignums()) == 1
+        fig = plt.gcf()
+        assert p._figure is fig
+
+    def test_show(self):
+
+        p = Plot()
+
+        with warnings.catch_warnings(record=True) as msg:
+            out = p.show(block=False)
+        assert out is None
+        assert not hasattr(p, "_figure")
+
+        assert len(plt.get_fignums()) == 1
+        fig = plt.gcf()
+
+        gui_backend = (
+            # From https://github.com/matplotlib/matplotlib/issues/20281
+            fig.canvas.manager.show != mpl.backend_bases.FigureManagerBase.show
+        )
+        if not gui_backend:
+            assert msg
+
+    def test_png_repr(self):
+
+        p = Plot()
+        data, metadata = p._repr_png_()
+        img = Image.open(io.BytesIO(data))
+
+        assert not hasattr(p, "_figure")
+        assert isinstance(data, bytes)
+        assert img.format == "PNG"
+        assert sorted(metadata) == ["height", "width"]
+        # TODO test retina scaling
+
+    def test_save(self):
+
+        buf = io.BytesIO()
+
+        p = Plot().save(buf)
+        assert isinstance(p, Plot)
+        img = Image.open(buf)
+        assert img.format == "PNG"
+
+        buf = io.StringIO()
+        Plot().save(buf, format="svg")
+        tag = xml.etree.ElementTree.fromstring(buf.getvalue()).tag
+        assert tag == "{http://www.w3.org/2000/svg}svg"
+
+    def test_layout_size(self):
+
+        size = (4, 2)
+        p = Plot().layout(size=size).plot()
+        assert tuple(p._figure.get_size_inches()) == size
+
+    def test_on_axes(self):
+
+        ax = mpl.figure.Figure().subplots()
+        m = MockMark()
+        p = Plot([1], [2]).on(ax).add(m).plot()
+        assert m.passed_axes == [ax]
+        assert p._figure is ax.figure
+
+    @pytest.mark.parametrize("facet", [True, False])
+    def test_on_figure(self, facet):
+
+        f = mpl.figure.Figure()
+        m = MockMark()
+        p = Plot([1, 2], [3, 4]).on(f).add(m)
+        if facet:
+            p = p.facet(["a", "b"])
+        p = p.plot()
+        assert m.passed_axes == f.axes
+        assert p._figure is f
+
+    @pytest.mark.skipif(
+        _version_predates(mpl, "3.4"),
+        reason="mpl<3.4 does not have SubFigure",
+    )
+    @pytest.mark.parametrize("facet", [True, False])
+    def test_on_subfigure(self, facet):
+
+        sf1, sf2 = mpl.figure.Figure().subfigures(2)
+        sf1.subplots()
+        m = MockMark()
+        p = Plot([1, 2], [3, 4]).on(sf2).add(m)
+        if facet:
+            p = p.facet(["a", "b"])
+        p = p.plot()
+        assert m.passed_axes == sf2.figure.axes[1:]
+        assert p._figure is sf2.figure
+
+    def test_on_type_check(self):
+
+        p = Plot()
+        with pytest.raises(TypeError, match="The `Plot.on`.+"):
+            p.on([])
+
+    def test_on_axes_with_subplots_error(self):
+
+        ax = mpl.figure.Figure().subplots()
+
+        p1 = Plot().facet(["a", "b"]).on(ax)
+        with pytest.raises(RuntimeError, match="Cannot create multiple subplots"):
+            p1.plot()
+
+        p2 = Plot().pair([["a", "b"], ["x", "y"]]).on(ax)
+        with pytest.raises(RuntimeError, match="Cannot create multiple subplots"):
+            p2.plot()
+
+    @pytest.mark.skipif(
+        _version_predates(mpl, "3.6"),
+        reason="Requires newer matplotlib layout engine API"
+    )
+    def test_on_layout_algo_default(self):
+
+        class MockEngine(mpl.layout_engine.ConstrainedLayoutEngine):
+            ...
+
+        f = mpl.figure.Figure(layout=MockEngine())
+        p = Plot().on(f).plot()
+        layout_engine = p._figure.get_layout_engine()
+        assert layout_engine.__class__.__name__ == "MockEngine"
+
+    @pytest.mark.skipif(
+        _version_predates(mpl, "3.6"),
+        reason="Requires newer matplotlib layout engine API"
+    )
+    def test_on_layout_algo_spec(self):
+
+        f = mpl.figure.Figure(layout="constrained")
+        p = Plot().on(f).layout(engine="tight").plot()
+        layout_engine = p._figure.get_layout_engine()
+        assert layout_engine.__class__.__name__ == "TightLayoutEngine"
+
+    def test_axis_labels_from_constructor(self, long_df):
+
+        ax, = Plot(long_df, x="a", y="b").plot()._figure.axes
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == "b"
+
+        ax, = Plot(x=long_df["a"], y=long_df["b"].to_numpy()).plot()._figure.axes
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == ""
+
+    def test_axis_labels_from_layer(self, long_df):
+
+        m = MockMark()
+
+        ax, = Plot(long_df).add(m, x="a", y="b").plot()._figure.axes
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == "b"
+
+        p = Plot().add(m, x=long_df["a"], y=long_df["b"].to_list())
+        ax, = p.plot()._figure.axes
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == ""
+
+    def test_axis_labels_are_first_name(self, long_df):
+
+        m = MockMark()
+        p = (
+            Plot(long_df, x=long_df["z"].to_list(), y="b")
+            .add(m, x="a")
+            .add(m, x="x", y="y")
+        )
+        ax, = p.plot()._figure.axes
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == "b"
+
+    def test_limits(self, long_df):
+
+        limit = (-2, 24)
+        p = Plot(long_df, x="x", y="y").limit(x=limit).plot()
+        ax = p._figure.axes[0]
+        assert ax.get_xlim() == limit
+
+        limit = (np.datetime64("2005-01-01"), np.datetime64("2008-01-01"))
+        p = Plot(long_df, x="d", y="y").limit(x=limit).plot()
+        ax = p._figure.axes[0]
+        assert ax.get_xlim() == tuple(mpl.dates.date2num(limit))
+
+        limit = ("b", "c")
+        p = Plot(x=["a", "b", "c", "d"], y=[1, 2, 3, 4]).limit(x=limit).plot()
+        ax = p._figure.axes[0]
+        assert ax.get_xlim() == (0.5, 2.5)
+
+    def test_labels_axis(self, long_df):
+
+        label = "Y axis"
+        p = Plot(long_df, x="x", y="y").label(y=label).plot()
+        ax = p._figure.axes[0]
+        assert ax.get_ylabel() == label
+
+        label = str.capitalize
+        p = Plot(long_df, x="x", y="y").label(y=label).plot()
+        ax = p._figure.axes[0]
+        assert ax.get_ylabel() == "Y"
+
+    def test_labels_legend(self, long_df):
+
+        m = MockMark()
+
+        label = "A"
+        p = Plot(long_df, x="x", y="y", color="a").add(m).label(color=label).plot()
+        assert p._figure.legends[0].get_title().get_text() == label
+
+        func = str.capitalize
+        p = Plot(long_df, x="x", y="y", color="a").add(m).label(color=func).plot()
+        assert p._figure.legends[0].get_title().get_text() == label
+
+    def test_labels_facets(self):
+
+        data = {"a": ["b", "c"], "x": ["y", "z"]}
+        p = Plot(data).facet("a", "x").label(col=str.capitalize, row="$x$").plot()
+        axs = np.reshape(p._figure.axes, (2, 2))
+        for (i, j), ax in np.ndenumerate(axs):
+            expected = f"A {data['a'][j]} | $x$ {data['x'][i]}"
+            assert ax.get_title() == expected
+
+    def test_title_single(self):
+
+        label = "A"
+        p = Plot().label(title=label).plot()
+        assert p._figure.axes[0].get_title() == label
+
+    def test_title_facet_function(self):
+
+        titles = ["a", "b"]
+        p = Plot().facet(titles).label(title=str.capitalize).plot()
+        for i, ax in enumerate(p._figure.axes):
+            assert ax.get_title() == titles[i].upper()
+
+        cols, rows = ["a", "b"], ["x", "y"]
+        p = Plot().facet(cols, rows).label(title=str.capitalize).plot()
+        for i, ax in enumerate(p._figure.axes):
+            expected = " | ".join([cols[i % 2].upper(), rows[i // 2].upper()])
+            assert ax.get_title() == expected
+
+
+class TestExceptions:
+
+    def test_scale_setup(self):
+
+        x = y = color = ["a", "b"]
+        bad_palette = "not_a_palette"
+        p = Plot(x, y, color=color).add(MockMark()).scale(color=bad_palette)
+
+        msg = "Scale setup failed for the `color` variable."
+        with pytest.raises(PlotSpecError, match=msg) as err:
+            p.plot()
+        assert isinstance(err.value.__cause__, ValueError)
+        assert bad_palette in str(err.value.__cause__)
+
+    def test_coordinate_scaling(self):
+
+        x = ["a", "b"]
+        y = [1, 2]
+        p = Plot(x, y).add(MockMark()).scale(x=Temporal())
+
+        msg = "Scaling operation failed for the `x` variable."
+        with pytest.raises(PlotSpecError, match=msg) as err:
+            p.plot()
+        # Don't test the cause contents b/c matplotlib owns them here.
+        assert hasattr(err.value, "__cause__")
+
+    def test_semantic_scaling(self):
+
+        class ErrorRaising(Continuous):
+
+            def _setup(self, data, prop, axis=None):
+
+                def f(x):
+                    raise ValueError("This is a test")
+
+                new = super()._setup(data, prop, axis)
+                new._pipeline = [f]
+                return new
+
+        x = y = color = [1, 2]
+        p = Plot(x, y, color=color).add(Dot()).scale(color=ErrorRaising())
+        msg = "Scaling operation failed for the `color` variable."
+        with pytest.raises(PlotSpecError, match=msg) as err:
+            p.plot()
+        assert isinstance(err.value.__cause__, ValueError)
+        assert str(err.value.__cause__) == "This is a test"
+
+
+class TestFacetInterface:
+
+    @pytest.fixture(scope="class", params=["row", "col"])
+    def dim(self, request):
+        return request.param
+
+    @pytest.fixture(scope="class", params=["reverse", "subset", "expand"])
+    def reorder(self, request):
+        return {
+            "reverse": lambda x: x[::-1],
+            "subset": lambda x: x[:-1],
+            "expand": lambda x: x + ["z"],
+        }[request.param]
+
+    def check_facet_results_1d(self, p, df, dim, key, order=None):
+
+        p = p.plot()
+
+        order = categorical_order(df[key], order)
+        assert len(p._figure.axes) == len(order)
+
+        other_dim = {"row": "col", "col": "row"}[dim]
+
+        for subplot, level in zip(p._subplots, order):
+            assert subplot[dim] == level
+            assert subplot[other_dim] is None
+            assert subplot["ax"].get_title() == f"{level}"
+            assert_gridspec_shape(subplot["ax"], **{f"n{dim}s": len(order)})
+
+    def test_1d(self, long_df, dim):
+
+        key = "a"
+        p = Plot(long_df).facet(**{dim: key})
+        self.check_facet_results_1d(p, long_df, dim, key)
+
+    def test_1d_as_vector(self, long_df, dim):
+
+        key = "a"
+        p = Plot(long_df).facet(**{dim: long_df[key]})
+        self.check_facet_results_1d(p, long_df, dim, key)
+
+    def test_1d_with_order(self, long_df, dim, reorder):
+
+        key = "a"
+        order = reorder(categorical_order(long_df[key]))
+        p = Plot(long_df).facet(**{dim: key, "order": order})
+        self.check_facet_results_1d(p, long_df, dim, key, order)
+
+    def check_facet_results_2d(self, p, df, variables, order=None):
+
+        p = p.plot()
+
+        if order is None:
+            order = {dim: categorical_order(df[key]) for dim, key in variables.items()}
+
+        levels = itertools.product(*[order[dim] for dim in ["row", "col"]])
+        assert len(p._subplots) == len(list(levels))
+
+        for subplot, (row_level, col_level) in zip(p._subplots, levels):
+            assert subplot["row"] == row_level
+            assert subplot["col"] == col_level
+            assert subplot["axes"].get_title() == (
+                f"{col_level} | {row_level}"
+            )
+            assert_gridspec_shape(
+                subplot["axes"], len(levels["row"]), len(levels["col"])
+            )
+
+    def test_2d(self, long_df):
+
+        variables = {"row": "a", "col": "c"}
+        p = Plot(long_df).facet(**variables)
+        self.check_facet_results_2d(p, long_df, variables)
+
+    def test_2d_with_order(self, long_df, reorder):
+
+        variables = {"row": "a", "col": "c"}
+        order = {
+            dim: reorder(categorical_order(long_df[key]))
+            for dim, key in variables.items()
+        }
+
+        p = Plot(long_df).facet(**variables, order=order)
+        self.check_facet_results_2d(p, long_df, variables, order)
+
+    @pytest.mark.parametrize("algo", ["tight", "constrained"])
+    def test_layout_algo(self, algo):
+
+        p = Plot().facet(["a", "b"]).limit(x=(.1, .9))
+
+        p1 = p.layout(engine=algo).plot()
+        p2 = p.layout(engine="none").plot()
+
+        # Force a draw (we probably need a method for this)
+        p1.save(io.BytesIO())
+        p2.save(io.BytesIO())
+
+        bb11, bb12 = [ax.get_position() for ax in p1._figure.axes]
+        bb21, bb22 = [ax.get_position() for ax in p2._figure.axes]
+
+        sep1 = bb12.corners()[0, 0] - bb11.corners()[2, 0]
+        sep2 = bb22.corners()[0, 0] - bb21.corners()[2, 0]
+        assert sep1 <= sep2
+
+    def test_axis_sharing(self, long_df):
+
+        variables = {"row": "a", "col": "c"}
+
+        p = Plot(long_df).facet(**variables)
+
+        p1 = p.plot()
+        root, *other = p1._figure.axes
+        for axis in "xy":
+            shareset = getattr(root, f"get_shared_{axis}_axes")()
+            assert all(shareset.joined(root, ax) for ax in other)
+
+        p2 = p.share(x=False, y=False).plot()
+        root, *other = p2._figure.axes
+        for axis in "xy":
+            shareset = getattr(root, f"get_shared_{axis}_axes")()
+            assert not any(shareset.joined(root, ax) for ax in other)
+
+        p3 = p.share(x="col", y="row").plot()
+        shape = (
+            len(categorical_order(long_df[variables["row"]])),
+            len(categorical_order(long_df[variables["col"]])),
+        )
+        axes_matrix = np.reshape(p3._figure.axes, shape)
+
+        for (shared, unshared), vectors in zip(
+            ["yx", "xy"], [axes_matrix, axes_matrix.T]
+        ):
+            for root, *other in vectors:
+                shareset = {
+                    axis: getattr(root, f"get_shared_{axis}_axes")() for axis in "xy"
+                }
+                assert all(shareset[shared].joined(root, ax) for ax in other)
+                assert not any(shareset[unshared].joined(root, ax) for ax in other)
+
+    def test_unshared_spacing(self):
+
+        x = [1, 2, 10, 20]
+        y = [1, 2, 3, 4]
+        col = [1, 1, 2, 2]
+
+        m = MockMark()
+        Plot(x, y).facet(col).add(m).share(x=False).plot()
+        assert_array_almost_equal(m.passed_data[0]["width"], [0.8, 0.8])
+        assert_array_equal(m.passed_data[1]["width"], [8, 8])
+
+    def test_col_wrapping(self):
+
+        cols = list("abcd")
+        wrap = 3
+        p = Plot().facet(col=cols, wrap=wrap).plot()
+
+        assert len(p._figure.axes) == 4
+        assert_gridspec_shape(p._figure.axes[0], len(cols) // wrap + 1, wrap)
+
+        # TODO test axis labels and titles
+
+    def test_row_wrapping(self):
+
+        rows = list("abcd")
+        wrap = 3
+        p = Plot().facet(row=rows, wrap=wrap).plot()
+
+        assert_gridspec_shape(p._figure.axes[0], wrap, len(rows) // wrap + 1)
+        assert len(p._figure.axes) == 4
+
+        # TODO test axis labels and titles
+
+
+class TestPairInterface:
+
+    def check_pair_grid(self, p, x, y):
+
+        xys = itertools.product(y, x)
+
+        for (y_i, x_j), subplot in zip(xys, p._subplots):
+
+            ax = subplot["ax"]
+            assert ax.get_xlabel() == "" if x_j is None else x_j
+            assert ax.get_ylabel() == "" if y_i is None else y_i
+            assert_gridspec_shape(subplot["ax"], len(y), len(x))
+
+    @pytest.mark.parametrize("vector_type", [list, pd.Index])
+    def test_all_numeric(self, long_df, vector_type):
+
+        x, y = ["x", "y", "z"], ["s", "f"]
+        p = Plot(long_df).pair(vector_type(x), vector_type(y)).plot()
+        self.check_pair_grid(p, x, y)
+
+    def test_single_variable_key_raises(self, long_df):
+
+        p = Plot(long_df)
+        err = "You must pass a sequence of variable keys to `y`"
+        with pytest.raises(TypeError, match=err):
+            p.pair(x=["x", "y"], y="z")
+
+    @pytest.mark.parametrize("dim", ["x", "y"])
+    def test_single_dimension(self, long_df, dim):
+
+        variables = {"x": None, "y": None}
+        variables[dim] = ["x", "y", "z"]
+        p = Plot(long_df).pair(**variables).plot()
+        variables = {k: [v] if v is None else v for k, v in variables.items()}
+        self.check_pair_grid(p, **variables)
+
+    def test_non_cross(self, long_df):
+
+        x = ["x", "y"]
+        y = ["f", "z"]
+
+        p = Plot(long_df).pair(x, y, cross=False).plot()
+
+        for i, subplot in enumerate(p._subplots):
+            ax = subplot["ax"]
+            assert ax.get_xlabel() == x[i]
+            assert ax.get_ylabel() == y[i]
+            assert_gridspec_shape(ax, 1, len(x))
+
+        root, *other = p._figure.axes
+        for axis in "xy":
+            shareset = getattr(root, f"get_shared_{axis}_axes")()
+            assert not any(shareset.joined(root, ax) for ax in other)
+
+    def test_list_of_vectors(self, long_df):
+
+        x_vars = ["x", "z"]
+        p = Plot(long_df, y="y").pair(x=[long_df[x] for x in x_vars]).plot()
+        assert len(p._figure.axes) == len(x_vars)
+        for ax, x_i in zip(p._figure.axes, x_vars):
+            assert ax.get_xlabel() == x_i
+
+    def test_with_no_variables(self, long_df):
+
+        p = Plot(long_df).pair().plot()
+        assert len(p._figure.axes) == 1
+
+    def test_with_facets(self, long_df):
+
+        x = "x"
+        y = ["y", "z"]
+        col = "a"
+
+        p = Plot(long_df, x=x).facet(col).pair(y=y).plot()
+
+        facet_levels = categorical_order(long_df[col])
+        dims = itertools.product(y, facet_levels)
+
+        for (y_i, col_i), subplot in zip(dims, p._subplots):
+
+            ax = subplot["ax"]
+            assert ax.get_xlabel() == x
+            assert ax.get_ylabel() == y_i
+            assert ax.get_title() == f"{col_i}"
+            assert_gridspec_shape(ax, len(y), len(facet_levels))
+
+    @pytest.mark.parametrize("variables", [("rows", "y"), ("columns", "x")])
+    def test_error_on_facet_overlap(self, long_df, variables):
+
+        facet_dim, pair_axis = variables
+        p = Plot(long_df).facet(**{facet_dim[:3]: "a"}).pair(**{pair_axis: ["x", "y"]})
+        expected = f"Cannot facet the {facet_dim} while pairing on `{pair_axis}`."
+        with pytest.raises(RuntimeError, match=expected):
+            p.plot()
+
+    @pytest.mark.parametrize("variables", [("columns", "y"), ("rows", "x")])
+    def test_error_on_wrap_overlap(self, long_df, variables):
+
+        facet_dim, pair_axis = variables
+        p = (
+            Plot(long_df)
+            .facet(wrap=2, **{facet_dim[:3]: "a"})
+            .pair(**{pair_axis: ["x", "y"]})
+        )
+        expected = f"Cannot wrap the {facet_dim} while pairing on `{pair_axis}``."
+        with pytest.raises(RuntimeError, match=expected):
+            p.plot()
+
+    def test_axis_sharing(self, long_df):
+
+        p = Plot(long_df).pair(x=["a", "b"], y=["y", "z"])
+        shape = 2, 2
+
+        p1 = p.plot()
+        axes_matrix = np.reshape(p1._figure.axes, shape)
+
+        for root, *other in axes_matrix:  # Test row-wise sharing
+            x_shareset = getattr(root, "get_shared_x_axes")()
+            assert not any(x_shareset.joined(root, ax) for ax in other)
+            y_shareset = getattr(root, "get_shared_y_axes")()
+            assert all(y_shareset.joined(root, ax) for ax in other)
+
+        for root, *other in axes_matrix.T:  # Test col-wise sharing
+            x_shareset = getattr(root, "get_shared_x_axes")()
+            assert all(x_shareset.joined(root, ax) for ax in other)
+            y_shareset = getattr(root, "get_shared_y_axes")()
+            assert not any(y_shareset.joined(root, ax) for ax in other)
+
+        p2 = p.share(x=False, y=False).plot()
+        root, *other = p2._figure.axes
+        for axis in "xy":
+            shareset = getattr(root, f"get_shared_{axis}_axes")()
+            assert not any(shareset.joined(root, ax) for ax in other)
+
+    def test_axis_sharing_with_facets(self, long_df):
+
+        p = Plot(long_df, y="y").pair(x=["a", "b"]).facet(row="c").plot()
+        shape = 2, 2
+
+        axes_matrix = np.reshape(p._figure.axes, shape)
+
+        for root, *other in axes_matrix:  # Test row-wise sharing
+            x_shareset = getattr(root, "get_shared_x_axes")()
+            assert not any(x_shareset.joined(root, ax) for ax in other)
+            y_shareset = getattr(root, "get_shared_y_axes")()
+            assert all(y_shareset.joined(root, ax) for ax in other)
+
+        for root, *other in axes_matrix.T:  # Test col-wise sharing
+            x_shareset = getattr(root, "get_shared_x_axes")()
+            assert all(x_shareset.joined(root, ax) for ax in other)
+            y_shareset = getattr(root, "get_shared_y_axes")()
+            assert all(y_shareset.joined(root, ax) for ax in other)
+
+    def test_x_wrapping(self, long_df):
+
+        x_vars = ["f", "x", "y", "z"]
+        wrap = 3
+        p = Plot(long_df, y="y").pair(x=x_vars, wrap=wrap).plot()
+
+        assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)
+        assert len(p._figure.axes) == len(x_vars)
+        for ax, var in zip(p._figure.axes, x_vars):
+            label = ax.xaxis.get_label()
+            assert label.get_visible()
+            assert label.get_text() == var
+
+    def test_y_wrapping(self, long_df):
+
+        y_vars = ["f", "x", "y", "z"]
+        wrap = 3
+        p = Plot(long_df, x="x").pair(y=y_vars, wrap=wrap).plot()
+
+        n_row, n_col = wrap, len(y_vars) // wrap + 1
+        assert_gridspec_shape(p._figure.axes[0], n_row, n_col)
+        assert len(p._figure.axes) == len(y_vars)
+        label_array = np.empty(n_row * n_col, object)
+        label_array[:len(y_vars)] = y_vars
+        label_array = label_array.reshape((n_row, n_col), order="F")
+        label_array = [y for y in label_array.flat if y is not None]
+        for i, ax in enumerate(p._figure.axes):
+            label = ax.yaxis.get_label()
+            assert label.get_visible()
+            assert label.get_text() == label_array[i]
+
+    def test_non_cross_wrapping(self, long_df):
+
+        x_vars = ["a", "b", "c", "t"]
+        y_vars = ["f", "x", "y", "z"]
+        wrap = 3
+
+        p = (
+            Plot(long_df, x="x")
+            .pair(x=x_vars, y=y_vars, wrap=wrap, cross=False)
+            .plot()
+        )
+
+        assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)
+        assert len(p._figure.axes) == len(x_vars)
+
+    def test_cross_mismatched_lengths(self, long_df):
+
+        p = Plot(long_df)
+        with pytest.raises(ValueError, match="Lengths of the `x` and `y`"):
+            p.pair(x=["a", "b"], y=["x", "y", "z"], cross=False)
+
+    def test_orient_inference(self, long_df):
+
+        orient_list = []
+
+        class CaptureOrientMove(Move):
+            def __call__(self, data, groupby, orient, scales):
+                orient_list.append(orient)
+                return data
+
+        (
+            Plot(long_df, x="x")
+            .pair(y=["b", "z"])
+            .add(MockMark(), CaptureOrientMove())
+            .plot()
+        )
+
+        assert orient_list == ["y", "x"]
+
+    def test_computed_coordinate_orient_inference(self, long_df):
+
+        class MockComputeStat(Stat):
+            def __call__(self, df, groupby, orient, scales):
+                other = {"x": "y", "y": "x"}[orient]
+                return df.assign(**{other: df[orient] * 2})
+
+        m = MockMark()
+        Plot(long_df, y="y").add(m, MockComputeStat()).plot()
+        assert m.passed_orient == "y"
+
+    def test_two_variables_single_order_error(self, long_df):
+
+        p = Plot(long_df)
+        err = "When faceting on both col= and row=, passing `order`"
+        with pytest.raises(RuntimeError, match=err):
+            p.facet(col="a", row="b", order=["a", "b", "c"])
+
+    def test_limits(self, long_df):
+
+        limit = (-2, 24)
+        p = Plot(long_df, y="y").pair(x=["x", "z"]).limit(x1=limit).plot()
+        ax1 = p._figure.axes[1]
+        assert ax1.get_xlim() == limit
+
+    def test_labels(self, long_df):
+
+        label = "Z"
+        p = Plot(long_df, y="y").pair(x=["x", "z"]).label(x1=label).plot()
+        ax1 = p._figure.axes[1]
+        assert ax1.get_xlabel() == label
+
+
+class TestLabelVisibility:
+
+    def test_single_subplot(self, long_df):
+
+        x, y = "a", "z"
+        p = Plot(long_df, x=x, y=y).plot()
+        subplot, *_ = p._subplots
+        ax = subplot["ax"]
+        assert ax.xaxis.get_label().get_visible()
+        assert ax.yaxis.get_label().get_visible()
+        assert all(t.get_visible() for t in ax.get_xticklabels())
+        assert all(t.get_visible() for t in ax.get_yticklabels())
+
+    @pytest.mark.parametrize(
+        "facet_kws,pair_kws", [({"col": "b"}, {}), ({}, {"x": ["x", "y", "f"]})]
+    )
+    def test_1d_column(self, long_df, facet_kws, pair_kws):
+
+        x = None if "x" in pair_kws else "a"
+        y = "z"
+        p = Plot(long_df, x=x, y=y).plot()
+        first, *other = p._subplots
+
+        ax = first["ax"]
+        assert ax.xaxis.get_label().get_visible()
+        assert ax.yaxis.get_label().get_visible()
+        assert all(t.get_visible() for t in ax.get_xticklabels())
+        assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in other:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert not ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+            assert not any(t.get_visible() for t in ax.get_yticklabels())
+
+    @pytest.mark.parametrize(
+        "facet_kws,pair_kws", [({"row": "b"}, {}), ({}, {"y": ["x", "y", "f"]})]
+    )
+    def test_1d_row(self, long_df, facet_kws, pair_kws):
+
+        x = "z"
+        y = None if "y" in pair_kws else "z"
+        p = Plot(long_df, x=x, y=y).plot()
+        first, *other = p._subplots
+
+        ax = first["ax"]
+        assert ax.xaxis.get_label().get_visible()
+        assert all(t.get_visible() for t in ax.get_xticklabels())
+        assert ax.yaxis.get_label().get_visible()
+        assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in other:
+            ax = s["ax"]
+            assert not ax.xaxis.get_label().get_visible()
+            assert ax.yaxis.get_label().get_visible()
+            assert not any(t.get_visible() for t in ax.get_xticklabels())
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+    def test_1d_column_wrapped(self):
+
+        p = Plot().facet(col=["a", "b", "c", "d"], wrap=3).plot()
+        subplots = list(p._subplots)
+
+        for s in [subplots[0], subplots[-1]]:
+            ax = s["ax"]
+            assert ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in subplots[1:]:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in subplots[1:-1]:
+            ax = s["ax"]
+            assert not ax.yaxis.get_label().get_visible()
+            assert not any(t.get_visible() for t in ax.get_yticklabels())
+
+        ax = subplots[0]["ax"]
+        assert not ax.xaxis.get_label().get_visible()
+        assert not any(t.get_visible() for t in ax.get_xticklabels())
+
+    def test_1d_row_wrapped(self):
+
+        p = Plot().facet(row=["a", "b", "c", "d"], wrap=3).plot()
+        subplots = list(p._subplots)
+
+        for s in subplots[:-1]:
+            ax = s["ax"]
+            assert ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in subplots[-2:]:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in subplots[:-2]:
+            ax = s["ax"]
+            assert not ax.xaxis.get_label().get_visible()
+            assert not any(t.get_visible() for t in ax.get_xticklabels())
+
+        ax = subplots[-1]["ax"]
+        assert not ax.yaxis.get_label().get_visible()
+        assert not any(t.get_visible() for t in ax.get_yticklabels())
+
+    def test_1d_column_wrapped_non_cross(self, long_df):
+
+        p = (
+            Plot(long_df)
+            .pair(x=["a", "b", "c"], y=["x", "y", "z"], wrap=2, cross=False)
+            .plot()
+        )
+        for s in p._subplots:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+            assert ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+    def test_2d(self):
+
+        p = Plot().facet(col=["a", "b"], row=["x", "y"]).plot()
+        subplots = list(p._subplots)
+
+        for s in subplots[:2]:
+            ax = s["ax"]
+            assert not ax.xaxis.get_label().get_visible()
+            assert not any(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in subplots[2:]:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in [subplots[0], subplots[2]]:
+            ax = s["ax"]
+            assert ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in [subplots[1], subplots[3]]:
+            ax = s["ax"]
+            assert not ax.yaxis.get_label().get_visible()
+            assert not any(t.get_visible() for t in ax.get_yticklabels())
+
+    def test_2d_unshared(self):
+
+        p = (
+            Plot()
+            .facet(col=["a", "b"], row=["x", "y"])
+            .share(x=False, y=False)
+            .plot()
+        )
+        subplots = list(p._subplots)
+
+        for s in subplots[:2]:
+            ax = s["ax"]
+            assert not ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in subplots[2:]:
+            ax = s["ax"]
+            assert ax.xaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_xticklabels())
+
+        for s in [subplots[0], subplots[2]]:
+            ax = s["ax"]
+            assert ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+        for s in [subplots[1], subplots[3]]:
+            ax = s["ax"]
+            assert not ax.yaxis.get_label().get_visible()
+            assert all(t.get_visible() for t in ax.get_yticklabels())
+
+
+class TestLegend:
+
+    @pytest.fixture
+    def xy(self):
+        return dict(x=[1, 2, 3, 4], y=[1, 2, 3, 4])
+
+    def test_single_layer_single_variable(self, xy):
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        p = Plot(**xy).add(MockMark(), color=s).plot()
+        e, = p._legend_contents
+
+        labels = categorical_order(s)
+
+        assert e[0] == (s.name, s.name)
+        assert e[-1] == labels
+
+        artists = e[1]
+        assert len(artists) == len(labels)
+        for a, label in zip(artists, labels):
+            assert isinstance(a, mpl.artist.Artist)
+            assert a.value == label
+            assert a.variables == ["color"]
+
+    def test_single_layer_common_variable(self, xy):
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        sem = dict(color=s, marker=s)
+        p = Plot(**xy).add(MockMark(), **sem).plot()
+        e, = p._legend_contents
+
+        labels = categorical_order(s)
+
+        assert e[0] == (s.name, s.name)
+        assert e[-1] == labels
+
+        artists = e[1]
+        assert len(artists) == len(labels)
+        for a, label in zip(artists, labels):
+            assert isinstance(a, mpl.artist.Artist)
+            assert a.value == label
+            assert a.variables == list(sem)
+
+    def test_single_layer_common_unnamed_variable(self, xy):
+
+        s = np.array(["a", "b", "a", "c"])
+        sem = dict(color=s, marker=s)
+        p = Plot(**xy).add(MockMark(), **sem).plot()
+
+        e, = p._legend_contents
+
+        labels = list(np.unique(s))  # assumes sorted order
+
+        assert e[0] == ("", id(s))
+        assert e[-1] == labels
+
+        artists = e[1]
+        assert len(artists) == len(labels)
+        for a, label in zip(artists, labels):
+            assert isinstance(a, mpl.artist.Artist)
+            assert a.value == label
+            assert a.variables == list(sem)
+
+    def test_single_layer_multi_variable(self, xy):
+
+        s1 = pd.Series(["a", "b", "a", "c"], name="s1")
+        s2 = pd.Series(["m", "m", "p", "m"], name="s2")
+        sem = dict(color=s1, marker=s2)
+        p = Plot(**xy).add(MockMark(), **sem).plot()
+        e1, e2 = p._legend_contents
+
+        variables = {v.name: k for k, v in sem.items()}
+
+        for e, s in zip([e1, e2], [s1, s2]):
+            assert e[0] == (s.name, s.name)
+
+            labels = categorical_order(s)
+            assert e[-1] == labels
+
+            artists = e[1]
+            assert len(artists) == len(labels)
+            for a, label in zip(artists, labels):
+                assert isinstance(a, mpl.artist.Artist)
+                assert a.value == label
+                assert a.variables == [variables[s.name]]
+
+    def test_multi_layer_single_variable(self, xy):
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        p = Plot(**xy, color=s).add(MockMark()).add(MockMark()).plot()
+        e1, e2 = p._legend_contents
+
+        labels = categorical_order(s)
+
+        for e in [e1, e2]:
+            assert e[0] == (s.name, s.name)
+
+            labels = categorical_order(s)
+            assert e[-1] == labels
+
+            artists = e[1]
+            assert len(artists) == len(labels)
+            for a, label in zip(artists, labels):
+                assert isinstance(a, mpl.artist.Artist)
+                assert a.value == label
+                assert a.variables == ["color"]
+
+    def test_multi_layer_multi_variable(self, xy):
+
+        s1 = pd.Series(["a", "b", "a", "c"], name="s1")
+        s2 = pd.Series(["m", "m", "p", "m"], name="s2")
+        sem = dict(color=s1), dict(marker=s2)
+        variables = {"s1": "color", "s2": "marker"}
+        p = Plot(**xy).add(MockMark(), **sem[0]).add(MockMark(), **sem[1]).plot()
+        e1, e2 = p._legend_contents
+
+        for e, s in zip([e1, e2], [s1, s2]):
+            assert e[0] == (s.name, s.name)
+
+            labels = categorical_order(s)
+            assert e[-1] == labels
+
+            artists = e[1]
+            assert len(artists) == len(labels)
+            for a, label in zip(artists, labels):
+                assert isinstance(a, mpl.artist.Artist)
+                assert a.value == label
+                assert a.variables == [variables[s.name]]
+
+    def test_multi_layer_different_artists(self, xy):
+
+        class MockMark1(MockMark):
+            def _legend_artist(self, variables, value, scales):
+                return mpl.lines.Line2D([], [])
+
+        class MockMark2(MockMark):
+            def _legend_artist(self, variables, value, scales):
+                return mpl.patches.Patch()
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        p = Plot(**xy, color=s).add(MockMark1()).add(MockMark2()).plot()
+
+        legend, = p._figure.legends
+
+        names = categorical_order(s)
+        labels = [t.get_text() for t in legend.get_texts()]
+        assert labels == names
+
+        if not _version_predates(mpl, "3.4"):
+            contents = legend.get_children()[0]
+            assert len(contents.findobj(mpl.lines.Line2D)) == len(names)
+            assert len(contents.findobj(mpl.patches.Patch)) == len(names)
+
+    def test_three_layers(self, xy):
+
+        class MockMarkLine(MockMark):
+            def _legend_artist(self, variables, value, scales):
+                return mpl.lines.Line2D([], [])
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        p = Plot(**xy, color=s)
+        for _ in range(3):
+            p = p.add(MockMarkLine())
+        p = p.plot()
+        texts = p._figure.legends[0].get_texts()
+        assert len(texts) == len(s.unique())
+
+    def test_identity_scale_ignored(self, xy):
+
+        s = pd.Series(["r", "g", "b", "g"])
+        p = Plot(**xy).add(MockMark(), color=s).scale(color=None).plot()
+        assert not p._legend_contents
+
+    def test_suppression_in_add_method(self, xy):
+
+        s = pd.Series(["a", "b", "a", "c"], name="s")
+        p = Plot(**xy).add(MockMark(), color=s, legend=False).plot()
+        assert not p._legend_contents
+
+    def test_anonymous_title(self, xy):
+
+        p = Plot(**xy, color=["a", "b", "c", "d"]).add(MockMark()).plot()
+        legend, = p._figure.legends
+        assert legend.get_title().get_text() == ""
+
+    def test_legendless_mark(self, xy):
+
+        class NoLegendMark(MockMark):
+            def _legend_artist(self, variables, value, scales):
+                return None
+
+        p = Plot(**xy, color=["a", "b", "c", "d"]).add(NoLegendMark()).plot()
+        assert not p._figure.legends
+
+    def test_legend_has_no_offset(self, xy):
+
+        color = np.add(xy["x"], 1e8)
+        p = Plot(**xy, color=color).add(MockMark()).plot()
+        legend = p._figure.legends[0]
+        assert legend.texts
+        for text in legend.texts:
+            assert float(text.get_text()) > 1e7
+
+
+class TestDefaultObject:
+
+    def test_default_repr(self):
+
+        assert repr(Default()) == ""
+
+
+class TestThemeConfig:
+
+    @pytest.fixture(autouse=True)
+    def reset_config(self):
+        yield
+        Plot.config.theme.reset()
+
+    def test_default(self):
+
+        p = Plot().plot()
+        ax = p._figure.axes[0]
+        expected = Plot.config.theme["axes.facecolor"]
+        assert mpl.colors.same_color(ax.get_facecolor(), expected)
+
+    def test_setitem(self):
+
+        color = "#CCC"
+        Plot.config.theme["axes.facecolor"] = color
+        p = Plot().plot()
+        ax = p._figure.axes[0]
+        assert mpl.colors.same_color(ax.get_facecolor(), color)
+
+    def test_update(self):
+
+        color = "#DDD"
+        Plot.config.theme.update({"axes.facecolor": color})
+        p = Plot().plot()
+        ax = p._figure.axes[0]
+        assert mpl.colors.same_color(ax.get_facecolor(), color)
+
+    def test_reset(self):
+
+        orig = Plot.config.theme["axes.facecolor"]
+        Plot.config.theme.update({"axes.facecolor": "#EEE"})
+        Plot.config.theme.reset()
+        p = Plot().plot()
+        ax = p._figure.axes[0]
+        assert mpl.colors.same_color(ax.get_facecolor(), orig)
+
+    def test_copy(self):
+
+        key, val = "axes.facecolor", ".95"
+        orig = Plot.config.theme[key]
+        theme = Plot.config.theme.copy()
+        theme.update({key: val})
+        assert Plot.config.theme[key] == orig
+
+    def test_html_repr(self):
+
+        res = Plot.config.theme._repr_html_()
+        for tag in ["div", "table", "tr", "td"]:
+            assert res.count(f"<{tag}") == res.count(f"{key}:" in res
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_properties.py b/testbed/mwaskom__seaborn/tests/_core/test_properties.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4764762eb3a534559baf3ad733510642209e798
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_properties.py
@@ -0,0 +1,584 @@
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+from matplotlib.colors import same_color, to_rgb, to_rgba
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn.utils import _version_predates
+from seaborn._core.rules import categorical_order
+from seaborn._core.scales import Nominal, Continuous, Boolean
+from seaborn._core.properties import (
+    Alpha,
+    Color,
+    Coordinate,
+    EdgeWidth,
+    Fill,
+    LineStyle,
+    LineWidth,
+    Marker,
+    PointSize,
+)
+from seaborn._compat import MarkerStyle, get_colormap
+from seaborn.palettes import color_palette
+
+
+class DataFixtures:
+
+    @pytest.fixture
+    def num_vector(self, long_df):
+        return long_df["s"]
+
+    @pytest.fixture
+    def num_order(self, num_vector):
+        return categorical_order(num_vector)
+
+    @pytest.fixture
+    def cat_vector(self, long_df):
+        return long_df["a"]
+
+    @pytest.fixture
+    def cat_order(self, cat_vector):
+        return categorical_order(cat_vector)
+
+    @pytest.fixture
+    def dt_num_vector(self, long_df):
+        return long_df["t"]
+
+    @pytest.fixture
+    def dt_cat_vector(self, long_df):
+        return long_df["d"]
+
+    @pytest.fixture
+    def bool_vector(self, long_df):
+        return long_df["x"] > 10
+
+    @pytest.fixture
+    def vectors(self, num_vector, cat_vector, bool_vector):
+        return {"num": num_vector, "cat": cat_vector, "bool": bool_vector}
+
+
+class TestCoordinate(DataFixtures):
+
+    def test_bad_scale_arg_str(self, num_vector):
+
+        err = "Unknown magic arg for x scale: 'xxx'."
+        with pytest.raises(ValueError, match=err):
+            Coordinate("x").infer_scale("xxx", num_vector)
+
+    def test_bad_scale_arg_type(self, cat_vector):
+
+        err = "Magic arg for x scale must be str, not list."
+        with pytest.raises(TypeError, match=err):
+            Coordinate("x").infer_scale([1, 2, 3], cat_vector)
+
+
+class TestColor(DataFixtures):
+
+    def assert_same_rgb(self, a, b):
+        assert_array_equal(a[:, :3], b[:, :3])
+
+    def test_nominal_default_palette(self, cat_vector, cat_order):
+
+        m = Color().get_mapping(Nominal(), cat_vector)
+        n = len(cat_order)
+        actual = m(np.arange(n))
+        expected = color_palette(None, n)
+        for have, want in zip(actual, expected):
+            assert same_color(have, want)
+
+    def test_nominal_default_palette_large(self):
+
+        vector = pd.Series(list("abcdefghijklmnopqrstuvwxyz"))
+        m = Color().get_mapping(Nominal(), vector)
+        actual = m(np.arange(26))
+        expected = color_palette("husl", 26)
+        for have, want in zip(actual, expected):
+            assert same_color(have, want)
+
+    def test_nominal_named_palette(self, cat_vector, cat_order):
+
+        palette = "Blues"
+        m = Color().get_mapping(Nominal(palette), cat_vector)
+        n = len(cat_order)
+        actual = m(np.arange(n))
+        expected = color_palette(palette, n)
+        for have, want in zip(actual, expected):
+            assert same_color(have, want)
+
+    def test_nominal_list_palette(self, cat_vector, cat_order):
+
+        palette = color_palette("Reds", len(cat_order))
+        m = Color().get_mapping(Nominal(palette), cat_vector)
+        actual = m(np.arange(len(palette)))
+        expected = palette
+        for have, want in zip(actual, expected):
+            assert same_color(have, want)
+
+    def test_nominal_dict_palette(self, cat_vector, cat_order):
+
+        colors = color_palette("Greens")
+        palette = dict(zip(cat_order, colors))
+        m = Color().get_mapping(Nominal(palette), cat_vector)
+        n = len(cat_order)
+        actual = m(np.arange(n))
+        expected = colors
+        for have, want in zip(actual, expected):
+            assert same_color(have, want)
+
+    def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order):
+
+        palette = dict(zip(cat_order[1:], color_palette("Purples")))
+        with pytest.raises(ValueError, match="No entry in color dict"):
+            Color("color").get_mapping(Nominal(palette), cat_vector)
+
+    def test_nominal_list_too_short(self, cat_vector, cat_order):
+
+        n = len(cat_order) - 1
+        palette = color_palette("Oranges", n)
+        msg = rf"The edgecolor list has fewer values \({n}\) than needed \({n + 1}\)"
+        with pytest.warns(UserWarning, match=msg):
+            Color("edgecolor").get_mapping(Nominal(palette), cat_vector)
+
+    def test_nominal_list_too_long(self, cat_vector, cat_order):
+
+        n = len(cat_order) + 1
+        palette = color_palette("Oranges", n)
+        msg = rf"The edgecolor list has more values \({n}\) than needed \({n - 1}\)"
+        with pytest.warns(UserWarning, match=msg):
+            Color("edgecolor").get_mapping(Nominal(palette), cat_vector)
+
+    def test_continuous_default_palette(self, num_vector):
+
+        cmap = color_palette("ch:", as_cmap=True)
+        m = Color().get_mapping(Continuous(), num_vector)
+        self.assert_same_rgb(m(num_vector), cmap(num_vector))
+
+    def test_continuous_named_palette(self, num_vector):
+
+        pal = "flare"
+        cmap = color_palette(pal, as_cmap=True)
+        m = Color().get_mapping(Continuous(pal), num_vector)
+        self.assert_same_rgb(m(num_vector), cmap(num_vector))
+
+    def test_continuous_tuple_palette(self, num_vector):
+
+        vals = ("blue", "red")
+        cmap = color_palette("blend:" + ",".join(vals), as_cmap=True)
+        m = Color().get_mapping(Continuous(vals), num_vector)
+        self.assert_same_rgb(m(num_vector), cmap(num_vector))
+
+    def test_continuous_callable_palette(self, num_vector):
+
+        cmap = get_colormap("viridis")
+        m = Color().get_mapping(Continuous(cmap), num_vector)
+        self.assert_same_rgb(m(num_vector), cmap(num_vector))
+
+    def test_continuous_missing(self):
+
+        x = pd.Series([1, 2, np.nan, 4])
+        m = Color().get_mapping(Continuous(), x)
+        assert np.isnan(m(x)[2]).all()
+
+    def test_bad_scale_values_continuous(self, num_vector):
+
+        with pytest.raises(TypeError, match="Scale values for color with a Continuous"):
+            Color().get_mapping(Continuous(["r", "g", "b"]), num_vector)
+
+    def test_bad_scale_values_nominal(self, cat_vector):
+
+        with pytest.raises(TypeError, match="Scale values for color with a Nominal"):
+            Color().get_mapping(Nominal(get_colormap("viridis")), cat_vector)
+
+    def test_bad_inference_arg(self, cat_vector):
+
+        with pytest.raises(TypeError, match="A single scale argument for color"):
+            Color().infer_scale(123, cat_vector)
+
+    @pytest.mark.parametrize(
+        "data_type,scale_class",
+        [("cat", Nominal), ("num", Continuous), ("bool", Boolean)]
+    )
+    def test_default(self, data_type, scale_class, vectors):
+
+        scale = Color().default_scale(vectors[data_type])
+        assert isinstance(scale, scale_class)
+
+    def test_default_numeric_data_category_dtype(self, num_vector):
+
+        scale = Color().default_scale(num_vector.astype("category"))
+        assert isinstance(scale, Nominal)
+
+    def test_default_binary_data(self):
+
+        x = pd.Series([0, 0, 1, 0, 1], dtype=int)
+        scale = Color().default_scale(x)
+        assert isinstance(scale, Continuous)
+
+    @pytest.mark.parametrize(
+        "values,data_type,scale_class",
+        [
+            ("viridis", "cat", Nominal),  # Based on variable type
+            ("viridis", "num", Continuous),  # Based on variable type
+            ("viridis", "bool", Boolean),  # Based on variable type
+            ("muted", "num", Nominal),  # Based on qualitative palette
+            (["r", "g", "b"], "num", Nominal),  # Based on list palette
+            ({2: "r", 4: "g", 8: "b"}, "num", Nominal),  # Based on dict palette
+            (("r", "b"), "num", Continuous),  # Based on tuple / variable type
+            (("g", "m"), "cat", Nominal),  # Based on tuple / variable type
+            (("c", "y"), "bool", Boolean),  # Based on tuple / variable type
+            (get_colormap("inferno"), "num", Continuous),  # Based on callable
+        ]
+    )
+    def test_inference(self, values, data_type, scale_class, vectors):
+
+        scale = Color().infer_scale(values, vectors[data_type])
+        assert isinstance(scale, scale_class)
+        assert scale.values == values
+
+    def test_standardization(self):
+
+        f = Color().standardize
+        assert f("C3") == to_rgb("C3")
+        assert f("dodgerblue") == to_rgb("dodgerblue")
+
+        assert f((.1, .2, .3)) == (.1, .2, .3)
+        assert f((.1, .2, .3, .4)) == (.1, .2, .3, .4)
+
+        assert f("#123456") == to_rgb("#123456")
+        assert f("#12345678") == to_rgba("#12345678")
+
+        if not _version_predates(mpl, "3.4.0"):
+            assert f("#123") == to_rgb("#123")
+            assert f("#1234") == to_rgba("#1234")
+
+
+class ObjectPropertyBase(DataFixtures):
+
+    def assert_equal(self, a, b):
+
+        assert self.unpack(a) == self.unpack(b)
+
+    def unpack(self, x):
+        return x
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_default(self, data_type, vectors):
+
+        scale = self.prop().default_scale(vectors[data_type])
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_inference_list(self, data_type, vectors):
+
+        scale = self.prop().infer_scale(self.values, vectors[data_type])
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+        assert scale.values == self.values
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_inference_dict(self, data_type, vectors):
+
+        x = vectors[data_type]
+        values = dict(zip(categorical_order(x), self.values))
+        scale = self.prop().infer_scale(values, x)
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+        assert scale.values == values
+
+    def test_dict_missing(self, cat_vector):
+
+        levels = categorical_order(cat_vector)
+        values = dict(zip(levels, self.values[:-1]))
+        scale = Nominal(values)
+        name = self.prop.__name__.lower()
+        msg = f"No entry in {name} dictionary for {repr(levels[-1])}"
+        with pytest.raises(ValueError, match=msg):
+            self.prop().get_mapping(scale, cat_vector)
+
+    @pytest.mark.parametrize("data_type", ["cat", "num"])
+    def test_mapping_default(self, data_type, vectors):
+
+        x = vectors[data_type]
+        mapping = self.prop().get_mapping(Nominal(), x)
+        n = x.nunique()
+        for i, expected in enumerate(self.prop()._default_values(n)):
+            actual, = mapping([i])
+            self.assert_equal(actual, expected)
+
+    @pytest.mark.parametrize("data_type", ["cat", "num"])
+    def test_mapping_from_list(self, data_type, vectors):
+
+        x = vectors[data_type]
+        scale = Nominal(self.values)
+        mapping = self.prop().get_mapping(scale, x)
+        for i, expected in enumerate(self.standardized_values):
+            actual, = mapping([i])
+            self.assert_equal(actual, expected)
+
+    @pytest.mark.parametrize("data_type", ["cat", "num"])
+    def test_mapping_from_dict(self, data_type, vectors):
+
+        x = vectors[data_type]
+        levels = categorical_order(x)
+        values = dict(zip(levels, self.values[::-1]))
+        standardized_values = dict(zip(levels, self.standardized_values[::-1]))
+
+        scale = Nominal(values)
+        mapping = self.prop().get_mapping(scale, x)
+        for i, level in enumerate(levels):
+            actual, = mapping([i])
+            expected = standardized_values[level]
+            self.assert_equal(actual, expected)
+
+    def test_mapping_with_null_value(self, cat_vector):
+
+        mapping = self.prop().get_mapping(Nominal(self.values), cat_vector)
+        actual = mapping(np.array([0, np.nan, 2]))
+        v0, _, v2 = self.standardized_values
+        expected = [v0, self.prop.null_value, v2]
+        for a, b in zip(actual, expected):
+            self.assert_equal(a, b)
+
+    def test_unique_default_large_n(self):
+
+        n = 24
+        x = pd.Series(np.arange(n))
+        mapping = self.prop().get_mapping(Nominal(), x)
+        assert len({self.unpack(x_i) for x_i in mapping(x)}) == n
+
+    def test_bad_scale_values(self, cat_vector):
+
+        var_name = self.prop.__name__.lower()
+        with pytest.raises(TypeError, match=f"Scale values for a {var_name} variable"):
+            self.prop().get_mapping(Nominal(("o", "s")), cat_vector)
+
+
+class TestMarker(ObjectPropertyBase):
+
+    prop = Marker
+    values = ["o", (5, 2, 0), MarkerStyle("^")]
+    standardized_values = [MarkerStyle(x) for x in values]
+
+    def unpack(self, x):
+        return (
+            x.get_path(),
+            x.get_joinstyle(),
+            x.get_transform().to_values(),
+            x.get_fillstyle(),
+        )
+
+
+class TestLineStyle(ObjectPropertyBase):
+
+    prop = LineStyle
+    values = ["solid", "--", (1, .5)]
+    standardized_values = [LineStyle._get_dash_pattern(x) for x in values]
+
+    def test_bad_type(self):
+
+        p = LineStyle()
+        with pytest.raises(TypeError, match="^Linestyle must be .+, not list.$"):
+            p.standardize([1, 2])
+
+    def test_bad_style(self):
+
+        p = LineStyle()
+        with pytest.raises(ValueError, match="^Linestyle string must be .+, not 'o'.$"):
+            p.standardize("o")
+
+    def test_bad_dashes(self):
+
+        p = LineStyle()
+        with pytest.raises(TypeError, match="^Invalid dash pattern"):
+            p.standardize((1, 2, "x"))
+
+
+class TestFill(DataFixtures):
+
+    @pytest.fixture
+    def vectors(self):
+
+        return {
+            "cat": pd.Series(["a", "a", "b"]),
+            "num": pd.Series([1, 1, 2]),
+            "bool": pd.Series([True, True, False])
+        }
+
+    @pytest.fixture
+    def cat_vector(self, vectors):
+        return vectors["cat"]
+
+    @pytest.fixture
+    def num_vector(self, vectors):
+        return vectors["num"]
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_default(self, data_type, vectors):
+
+        x = vectors[data_type]
+        scale = Fill().default_scale(x)
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_inference_list(self, data_type, vectors):
+
+        x = vectors[data_type]
+        scale = Fill().infer_scale([True, False], x)
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+        assert scale.values == [True, False]
+
+    @pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
+    def test_inference_dict(self, data_type, vectors):
+
+        x = vectors[data_type]
+        values = dict(zip(x.unique(), [True, False]))
+        scale = Fill().infer_scale(values, x)
+        assert isinstance(scale, Boolean if data_type == "bool" else Nominal)
+        assert scale.values == values
+
+    def test_mapping_categorical_data(self, cat_vector):
+
+        mapping = Fill().get_mapping(Nominal(), cat_vector)
+        assert_array_equal(mapping([0, 1, 0]), [True, False, True])
+
+    def test_mapping_numeric_data(self, num_vector):
+
+        mapping = Fill().get_mapping(Nominal(), num_vector)
+        assert_array_equal(mapping([0, 1, 0]), [True, False, True])
+
+    def test_mapping_list(self, cat_vector):
+
+        mapping = Fill().get_mapping(Nominal([False, True]), cat_vector)
+        assert_array_equal(mapping([0, 1, 0]), [False, True, False])
+
+    def test_mapping_truthy_list(self, cat_vector):
+
+        mapping = Fill().get_mapping(Nominal([0, 1]), cat_vector)
+        assert_array_equal(mapping([0, 1, 0]), [False, True, False])
+
+    def test_mapping_dict(self, cat_vector):
+
+        values = dict(zip(cat_vector.unique(), [False, True]))
+        mapping = Fill().get_mapping(Nominal(values), cat_vector)
+        assert_array_equal(mapping([0, 1, 0]), [False, True, False])
+
+    def test_cycle_warning(self):
+
+        x = pd.Series(["a", "b", "c"])
+        with pytest.warns(UserWarning, match="The variable assigned to fill"):
+            Fill().get_mapping(Nominal(), x)
+
+    def test_values_error(self):
+
+        x = pd.Series(["a", "b"])
+        with pytest.raises(TypeError, match="Scale values for fill must be"):
+            Fill().get_mapping(Nominal("bad_values"), x)
+
+
+class IntervalBase(DataFixtures):
+
+    def norm(self, x):
+        return (x - x.min()) / (x.max() - x.min())
+
+    @pytest.mark.parametrize("data_type,scale_class", [
+        ("cat", Nominal),
+        ("num", Continuous),
+        ("bool", Boolean),
+    ])
+    def test_default(self, data_type, scale_class, vectors):
+
+        x = vectors[data_type]
+        scale = self.prop().default_scale(x)
+        assert isinstance(scale, scale_class)
+
+    @pytest.mark.parametrize("arg,data_type,scale_class", [
+        ((1, 3), "cat", Nominal),
+        ((1, 3), "num", Continuous),
+        ((1, 3), "bool", Boolean),
+        ([1, 2, 3], "cat", Nominal),
+        ([1, 2, 3], "num", Nominal),
+        ([1, 3], "bool", Boolean),
+        ({"a": 1, "b": 3, "c": 2}, "cat", Nominal),
+        ({2: 1, 4: 3, 8: 2}, "num", Nominal),
+        ({True: 4, False: 2}, "bool", Boolean),
+    ])
+    def test_inference(self, arg, data_type, scale_class, vectors):
+
+        x = vectors[data_type]
+        scale = self.prop().infer_scale(arg, x)
+        assert isinstance(scale, scale_class)
+        assert scale.values == arg
+
+    def test_mapped_interval_numeric(self, num_vector):
+
+        mapping = self.prop().get_mapping(Continuous(), num_vector)
+        assert_array_equal(mapping([0, 1]), self.prop().default_range)
+
+    def test_mapped_interval_categorical(self, cat_vector):
+
+        mapping = self.prop().get_mapping(Nominal(), cat_vector)
+        n = cat_vector.nunique()
+        assert_array_equal(mapping([n - 1, 0]), self.prop().default_range)
+
+    def test_bad_scale_values_numeric_data(self, num_vector):
+
+        prop_name = self.prop.__name__.lower()
+        err_stem = (
+            f"Values for {prop_name} variables with Continuous scale must be 2-tuple"
+        )
+
+        with pytest.raises(TypeError, match=f"{err_stem}; not ."):
+            self.prop().get_mapping(Continuous("abc"), num_vector)
+
+        with pytest.raises(TypeError, match=f"{err_stem}; not 3-tuple."):
+            self.prop().get_mapping(Continuous((1, 2, 3)), num_vector)
+
+    def test_bad_scale_values_categorical_data(self, cat_vector):
+
+        prop_name = self.prop.__name__.lower()
+        err_text = f"Values for {prop_name} variables with Nominal scale"
+        with pytest.raises(TypeError, match=err_text):
+            self.prop().get_mapping(Nominal("abc"), cat_vector)
+
+
+class TestAlpha(IntervalBase):
+    prop = Alpha
+
+
+class TestLineWidth(IntervalBase):
+    prop = LineWidth
+
+    def test_rcparam_default(self):
+
+        with mpl.rc_context({"lines.linewidth": 2}):
+            assert self.prop().default_range == (1, 4)
+
+
+class TestEdgeWidth(IntervalBase):
+    prop = EdgeWidth
+
+    def test_rcparam_default(self):
+
+        with mpl.rc_context({"patch.linewidth": 2}):
+            assert self.prop().default_range == (1, 4)
+
+
+class TestPointSize(IntervalBase):
+    prop = PointSize
+
+    def test_areal_scaling_numeric(self, num_vector):
+
+        limits = 5, 10
+        scale = Continuous(limits)
+        mapping = self.prop().get_mapping(scale, num_vector)
+        x = np.linspace(0, 1, 6)
+        expected = np.sqrt(np.linspace(*np.square(limits), num=len(x)))
+        assert_array_equal(mapping(x), expected)
+
+    def test_areal_scaling_categorical(self, cat_vector):
+
+        limits = (2, 4)
+        scale = Nominal(limits)
+        mapping = self.prop().get_mapping(scale, cat_vector)
+        assert_array_equal(mapping(np.arange(3)), [4, np.sqrt(10), 2])
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_rules.py b/testbed/mwaskom__seaborn/tests/_core/test_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..3eec1a6d9734280819a89e93a87d9145e7374f28
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_rules.py
@@ -0,0 +1,103 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+
+from seaborn._core.rules import (
+    VarType,
+    variable_type,
+    categorical_order,
+)
+
+
+def test_vartype_object():
+
+    v = VarType("numeric")
+    assert v == "numeric"
+    assert v != "categorical"
+    with pytest.raises(AssertionError):
+        v == "number"
+    with pytest.raises(AssertionError):
+        VarType("date")
+
+
+def test_variable_type():
+
+    s = pd.Series([1., 2., 3.])
+    assert variable_type(s) == "numeric"
+    assert variable_type(s.astype(int)) == "numeric"
+    assert variable_type(s.astype(object)) == "numeric"
+    assert variable_type(s.to_numpy()) == "numeric"
+    assert variable_type(s.to_list()) == "numeric"
+
+    s = pd.Series([1, 2, 3, np.nan], dtype=object)
+    assert variable_type(s) == "numeric"
+
+    s = pd.Series([np.nan, np.nan])
+    assert variable_type(s) == "numeric"
+
+    s = pd.Series([pd.NA, pd.NA])
+    assert variable_type(s) == "numeric"
+
+    s = pd.Series(["1", "2", "3"])
+    assert variable_type(s) == "categorical"
+    assert variable_type(s.to_numpy()) == "categorical"
+    assert variable_type(s.to_list()) == "categorical"
+
+    s = pd.Series([True, False, False])
+    assert variable_type(s) == "numeric"
+    assert variable_type(s, boolean_type="categorical") == "categorical"
+    assert variable_type(s, boolean_type="boolean") == "boolean"
+
+    s_cat = s.astype("category")
+    assert variable_type(s_cat, boolean_type="categorical") == "categorical"
+    assert variable_type(s_cat, boolean_type="numeric") == "categorical"
+    assert variable_type(s_cat, boolean_type="boolean") == "categorical"
+
+    s = pd.Series([1, 0, 0])
+    assert variable_type(s, boolean_type="boolean") == "boolean"
+    assert variable_type(s, boolean_type="boolean", strict_boolean=True) == "numeric"
+
+    s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])
+    assert variable_type(s) == "datetime"
+    assert variable_type(s.astype(object)) == "datetime"
+    assert variable_type(s.to_numpy()) == "datetime"
+    assert variable_type(s.to_list()) == "datetime"
+
+
+def test_categorical_order():
+
+    x = pd.Series(["a", "c", "c", "b", "a", "d"])
+    y = pd.Series([3, 2, 5, 1, 4])
+    order = ["a", "b", "c", "d"]
+
+    out = categorical_order(x)
+    assert out == ["a", "c", "b", "d"]
+
+    out = categorical_order(x, order)
+    assert out == order
+
+    out = categorical_order(x, ["b", "a"])
+    assert out == ["b", "a"]
+
+    out = categorical_order(y)
+    assert out == [1, 2, 3, 4, 5]
+
+    out = categorical_order(pd.Series(y))
+    assert out == [1, 2, 3, 4, 5]
+
+    y_cat = pd.Series(pd.Categorical(y, y))
+    out = categorical_order(y_cat)
+    assert out == list(y)
+
+    x = pd.Series(x).astype("category")
+    out = categorical_order(x)
+    assert out == list(x.cat.categories)
+
+    out = categorical_order(x, ["b", "a"])
+    assert out == ["b", "a"]
+
+    x = pd.Series(["a", np.nan, "c", "c", "b", "a", "d"])
+    out = categorical_order(x)
+    assert out == ["a", "c", "b", "d"]
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_scales.py b/testbed/mwaskom__seaborn/tests/_core/test_scales.py
new file mode 100644
index 0000000000000000000000000000000000000000..deee844d7a6c8461243ba14edbd07f4c24895465
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_scales.py
@@ -0,0 +1,805 @@
+import re
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+
+import pytest
+from numpy.testing import assert_array_equal
+from pandas.testing import assert_series_equal
+
+from seaborn._core.plot import Plot
+from seaborn._core.scales import (
+    Nominal,
+    Continuous,
+    Boolean,
+    Temporal,
+    PseudoAxis,
+)
+from seaborn._core.properties import (
+    IntervalProperty,
+    ObjectProperty,
+    Coordinate,
+    Alpha,
+    Color,
+    Fill,
+)
+from seaborn.palettes import color_palette
+from seaborn.utils import _version_predates
+
+
+class TestContinuous:
+
+    @pytest.fixture
+    def x(self):
+        return pd.Series([1, 3, 9], name="x", dtype=float)
+
+    def setup_ticks(self, x, *args, **kwargs):
+
+        s = Continuous().tick(*args, **kwargs)._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        a.set_view_interval(0, 1)
+        return a
+
+    def setup_labels(self, x, *args, **kwargs):
+
+        s = Continuous().label(*args, **kwargs)._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        a.set_view_interval(0, 1)
+        locs = a.major.locator()
+        return a, locs
+
+    def test_coordinate_defaults(self, x):
+
+        s = Continuous()._setup(x, Coordinate())
+        assert_series_equal(s(x), x)
+
+    def test_coordinate_transform(self, x):
+
+        s = Continuous(trans="log")._setup(x, Coordinate())
+        assert_series_equal(s(x), np.log10(x))
+
+    def test_coordinate_transform_with_parameter(self, x):
+
+        s = Continuous(trans="pow3")._setup(x, Coordinate())
+        assert_series_equal(s(x), np.power(x, 3))
+
+    def test_coordinate_transform_error(self, x):
+
+        s = Continuous(trans="bad")
+        with pytest.raises(ValueError, match="Unknown value provided"):
+            s._setup(x, Coordinate())
+
+    def test_interval_defaults(self, x):
+
+        s = Continuous()._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [0, .25, 1])
+
+    def test_interval_with_range(self, x):
+
+        s = Continuous((1, 3))._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [1, 1.5, 3])
+
+    def test_interval_with_norm(self, x):
+
+        s = Continuous(norm=(3, 7))._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [-.5, 0, 1.5])
+
+    def test_interval_with_range_norm_and_transform(self, x):
+
+        x = pd.Series([1, 10, 100])
+        # TODO param order?
+        s = Continuous((2, 3), (10, 100), "log")._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [1, 2, 3])
+
+    def test_interval_with_bools(self):
+
+        x = pd.Series([True, False, False])
+        s = Continuous()._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [1, 0, 0])
+
+    def test_color_defaults(self, x):
+
+        cmap = color_palette("ch:", as_cmap=True)
+        s = Continuous()._setup(x, Color())
+        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA
+
+    def test_color_named_values(self, x):
+
+        cmap = color_palette("viridis", as_cmap=True)
+        s = Continuous("viridis")._setup(x, Color())
+        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA
+
+    def test_color_tuple_values(self, x):
+
+        cmap = color_palette("blend:b,g", as_cmap=True)
+        s = Continuous(("b", "g"))._setup(x, Color())
+        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA
+
+    def test_color_callable_values(self, x):
+
+        cmap = color_palette("light:r", as_cmap=True)
+        s = Continuous(cmap)._setup(x, Color())
+        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA
+
+    def test_color_with_norm(self, x):
+
+        cmap = color_palette("ch:", as_cmap=True)
+        s = Continuous(norm=(3, 7))._setup(x, Color())
+        assert_array_equal(s(x), cmap([-.5, 0, 1.5])[:, :3])  # FIXME RGBA
+
+    def test_color_with_transform(self, x):
+
+        x = pd.Series([1, 10, 100], name="x", dtype=float)
+        cmap = color_palette("ch:", as_cmap=True)
+        s = Continuous(trans="log")._setup(x, Color())
+        assert_array_equal(s(x), cmap([0, .5, 1])[:, :3])  # FIXME RGBA
+
+    def test_tick_locator(self, x):
+
+        locs = [.2, .5, .8]
+        locator = mpl.ticker.FixedLocator(locs)
+        a = self.setup_ticks(x, locator)
+        assert_array_equal(a.major.locator(), locs)
+
+    def test_tick_locator_input_check(self, x):
+
+        err = "Tick locator must be an instance of .*?, not ."
+        with pytest.raises(TypeError, match=err):
+            Continuous().tick((1, 2))
+
+    def test_tick_upto(self, x):
+
+        for n in [2, 5, 10]:
+            a = self.setup_ticks(x, upto=n)
+            assert len(a.major.locator()) <= (n + 1)
+
+    def test_tick_every(self, x):
+
+        for d in [.05, .2, .5]:
+            a = self.setup_ticks(x, every=d)
+            assert np.allclose(np.diff(a.major.locator()), d)
+
+    def test_tick_every_between(self, x):
+
+        lo, hi = .2, .8
+        for d in [.05, .2, .5]:
+            a = self.setup_ticks(x, every=d, between=(lo, hi))
+            expected = np.arange(lo, hi + d, d)
+            assert_array_equal(a.major.locator(), expected)
+
+    def test_tick_at(self, x):
+
+        locs = [.2, .5, .9]
+        a = self.setup_ticks(x, at=locs)
+        assert_array_equal(a.major.locator(), locs)
+
+    def test_tick_count(self, x):
+
+        n = 8
+        a = self.setup_ticks(x, count=n)
+        assert_array_equal(a.major.locator(), np.linspace(0, 1, n))
+
+    def test_tick_count_between(self, x):
+
+        n = 5
+        lo, hi = .2, .7
+        a = self.setup_ticks(x, count=n, between=(lo, hi))
+        assert_array_equal(a.major.locator(), np.linspace(lo, hi, n))
+
+    def test_tick_minor(self, x):
+
+        n = 3
+        a = self.setup_ticks(x, count=2, minor=n)
+        # I am not sure why matplotlib's minor ticks include the
+        # largest major location but exclude the smalllest one ...
+        expected = np.linspace(0, 1, n + 2)[1:]
+        assert_array_equal(a.minor.locator(), expected)
+
+    def test_log_tick_default(self, x):
+
+        s = Continuous(trans="log")._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        a.set_view_interval(.5, 1050)
+        ticks = a.major.locator()
+        assert np.allclose(np.diff(np.log10(ticks)), 1)
+
+    def test_log_tick_upto(self, x):
+
+        n = 3
+        s = Continuous(trans="log").tick(upto=n)._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        assert a.major.locator.numticks == n
+
+    def test_log_tick_count(self, x):
+
+        with pytest.raises(RuntimeError, match="`count` requires"):
+            Continuous(trans="log").tick(count=4)
+
+        s = Continuous(trans="log").tick(count=4, between=(1, 1000))
+        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)
+        a.set_view_interval(.5, 1050)
+        assert_array_equal(a.major.locator(), [1, 10, 100, 1000])
+
+    def test_log_tick_format_disabled(self, x):
+
+        s = Continuous(trans="log").label(base=None)._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        a.set_view_interval(20, 20000)
+        labels = a.major.formatter.format_ticks(a.major.locator())
+        for text in labels:
+            assert re.match(r"^\d+$", text)
+
+    def test_log_tick_every(self, x):
+
+        with pytest.raises(RuntimeError, match="`every` not supported"):
+            Continuous(trans="log").tick(every=2)
+
+    def test_symlog_tick_default(self, x):
+
+        s = Continuous(trans="symlog")._setup(x, Coordinate())
+        a = PseudoAxis(s._matplotlib_scale)
+        a.set_view_interval(-1050, 1050)
+        ticks = a.major.locator()
+        assert ticks[0] == -ticks[-1]
+        pos_ticks = np.sort(np.unique(np.abs(ticks)))
+        assert np.allclose(np.diff(np.log10(pos_ticks[1:])), 1)
+        assert pos_ticks[0] == 0
+
+    def test_label_formatter(self, x):
+
+        fmt = mpl.ticker.FormatStrFormatter("%.3f")
+        a, locs = self.setup_labels(x, fmt)
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels:
+            assert re.match(r"^\d\.\d{3}$", text)
+
+    def test_label_like_pattern(self, x):
+
+        a, locs = self.setup_labels(x, like=".4f")
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels:
+            assert re.match(r"^\d\.\d{4}$", text)
+
+    def test_label_like_string(self, x):
+
+        a, locs = self.setup_labels(x, like="x = {x:.1f}")
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels:
+            assert re.match(r"^x = \d\.\d$", text)
+
+    def test_label_like_function(self, x):
+
+        a, locs = self.setup_labels(x, like="{:^5.1f}".format)
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels:
+            assert re.match(r"^ \d\.\d $", text)
+
+    def test_label_base(self, x):
+
+        a, locs = self.setup_labels(100 * x, base=2)
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels[1:]:
+            assert not text or "2^" in text
+
+    def test_label_unit(self, x):
+
+        a, locs = self.setup_labels(1000 * x, unit="g")
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels[1:-1]:
+            assert re.match(r"^\d+ mg$", text)
+
+    def test_label_unit_with_sep(self, x):
+
+        a, locs = self.setup_labels(1000 * x, unit=("", "g"))
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels[1:-1]:
+            assert re.match(r"^\d+mg$", text)
+
+    def test_label_empty_unit(self, x):
+
+        a, locs = self.setup_labels(1000 * x, unit="")
+        labels = a.major.formatter.format_ticks(locs)
+        for text in labels[1:-1]:
+            assert re.match(r"^\d+m$", text)
+
+    def test_label_base_from_transform(self, x):
+
+        s = Continuous(trans="log")
+        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)
+        a.set_view_interval(10, 1000)
+        label, = a.major.formatter.format_ticks([100])
+        assert r"10^{2}" in label
+
+    def test_label_type_checks(self):
+
+        s = Continuous()
+        with pytest.raises(TypeError, match="Label formatter must be"):
+            s.label("{x}")
+
+        with pytest.raises(TypeError, match="`like` must be"):
+            s.label(like=2)
+
+
+class TestNominal:
+
+    @pytest.fixture
+    def x(self):
+        return pd.Series(["a", "c", "b", "c"], name="x")
+
+    @pytest.fixture
+    def y(self):
+        return pd.Series([1, -1.5, 3, -1.5], name="y")
+
+    def test_coordinate_defaults(self, x):
+
+        s = Nominal()._setup(x, Coordinate())
+        assert_array_equal(s(x), np.array([0, 1, 2, 1], float))
+
+    def test_coordinate_with_order(self, x):
+
+        s = Nominal(order=["a", "b", "c"])._setup(x, Coordinate())
+        assert_array_equal(s(x), np.array([0, 2, 1, 2], float))
+
+    def test_coordinate_with_subset_order(self, x):
+
+        s = Nominal(order=["c", "a"])._setup(x, Coordinate())
+        assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))
+
+    def test_coordinate_axis(self, x):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal()._setup(x, Coordinate(), ax.xaxis)
+        assert_array_equal(s(x), np.array([0, 1, 2, 1], float))
+        f = ax.xaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2]) == ["a", "c", "b"]
+
+    def test_coordinate_axis_with_order(self, x):
+
+        order = ["a", "b", "c"]
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)
+        assert_array_equal(s(x), np.array([0, 2, 1, 2], float))
+        f = ax.xaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2]) == order
+
+    def test_coordinate_axis_with_subset_order(self, x):
+
+        order = ["c", "a"]
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)
+        assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))
+        f = ax.xaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2]) == [*order, ""]
+
+    def test_coordinate_axis_with_category_dtype(self, x):
+
+        order = ["b", "a", "d", "c"]
+        x = x.astype(pd.CategoricalDtype(order))
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal()._setup(x, Coordinate(), ax.xaxis)
+        assert_array_equal(s(x), np.array([1, 3, 0, 3], float))
+        f = ax.xaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2, 3]) == order
+
+    def test_coordinate_numeric_data(self, y):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal()._setup(y, Coordinate(), ax.yaxis)
+        assert_array_equal(s(y), np.array([1, 0, 2, 0], float))
+        f = ax.yaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2]) == ["-1.5", "1.0", "3.0"]
+
+    def test_coordinate_numeric_data_with_order(self, y):
+
+        order = [1, 4, -1.5]
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal(order=order)._setup(y, Coordinate(), ax.yaxis)
+        assert_array_equal(s(y), np.array([0, 2, np.nan, 2], float))
+        f = ax.yaxis.get_major_formatter()
+        assert f.format_ticks([0, 1, 2]) == ["1.0", "4.0", "-1.5"]
+
+    def test_color_defaults(self, x):
+
+        s = Nominal()._setup(x, Color())
+        cs = color_palette()
+        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
+
+    def test_color_named_palette(self, x):
+
+        pal = "flare"
+        s = Nominal(pal)._setup(x, Color())
+        cs = color_palette(pal, 3)
+        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
+
+    def test_color_list_palette(self, x):
+
+        cs = color_palette("crest", 3)
+        s = Nominal(cs)._setup(x, Color())
+        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
+
+    def test_color_dict_palette(self, x):
+
+        cs = color_palette("crest", 3)
+        pal = dict(zip("bac", cs))
+        s = Nominal(pal)._setup(x, Color())
+        assert_array_equal(s(x), [cs[1], cs[2], cs[0], cs[2]])
+
+    def test_color_numeric_data(self, y):
+
+        s = Nominal()._setup(y, Color())
+        cs = color_palette()
+        assert_array_equal(s(y), [cs[1], cs[0], cs[2], cs[0]])
+
+    def test_color_numeric_with_order_subset(self, y):
+
+        s = Nominal(order=[-1.5, 1])._setup(y, Color())
+        c1, c2 = color_palette(n_colors=2)
+        null = (np.nan, np.nan, np.nan)
+        assert_array_equal(s(y), [c2, c1, null, c1])
+
+    @pytest.mark.xfail(reason="Need to sort out float/int order")
+    def test_color_numeric_int_float_mix(self):
+
+        z = pd.Series([1, 2], name="z")
+        s = Nominal(order=[1.0, 2])._setup(z, Color())
+        c1, c2 = color_palette(n_colors=2)
+        null = (np.nan, np.nan, np.nan)
+        assert_array_equal(s(z), [c1, null, c2])
+
+    def test_color_alpha_in_palette(self, x):
+
+        cs = [(.2, .2, .3, .5), (.1, .2, .3, 1), (.5, .6, .2, 0)]
+        s = Nominal(cs)._setup(x, Color())
+        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
+
+    def test_color_unknown_palette(self, x):
+
+        pal = "not_a_palette"
+        err = f"'{pal}' is not a valid palette name"
+        with pytest.raises(ValueError, match=err):
+            Nominal(pal)._setup(x, Color())
+
+    def test_object_defaults(self, x):
+
+        class MockProperty(ObjectProperty):
+            def _default_values(self, n):
+                return list("xyz"[:n])
+
+        s = Nominal()._setup(x, MockProperty())
+        assert s(x) == ["x", "y", "z", "y"]
+
+    def test_object_list(self, x):
+
+        vs = ["x", "y", "z"]
+        s = Nominal(vs)._setup(x, ObjectProperty())
+        assert s(x) == ["x", "y", "z", "y"]
+
+    def test_object_dict(self, x):
+
+        vs = {"a": "x", "b": "y", "c": "z"}
+        s = Nominal(vs)._setup(x, ObjectProperty())
+        assert s(x) == ["x", "z", "y", "z"]
+
+    def test_object_order(self, x):
+
+        vs = ["x", "y", "z"]
+        s = Nominal(vs, order=["c", "a", "b"])._setup(x, ObjectProperty())
+        assert s(x) == ["y", "x", "z", "x"]
+
+    def test_object_order_subset(self, x):
+
+        vs = ["x", "y"]
+        s = Nominal(vs, order=["a", "c"])._setup(x, ObjectProperty())
+        assert s(x) == ["x", "y", None, "y"]
+
+    def test_objects_that_are_weird(self, x):
+
+        vs = [("x", 1), (None, None, 0), {}]
+        s = Nominal(vs)._setup(x, ObjectProperty())
+        assert s(x) == [vs[0], vs[1], vs[2], vs[1]]
+
+    def test_alpha_default(self, x):
+
+        s = Nominal()._setup(x, Alpha())
+        assert_array_equal(s(x), [.95, .625, .3, .625])
+
+    def test_fill(self):
+
+        x = pd.Series(["a", "a", "b", "a"], name="x")
+        s = Nominal()._setup(x, Fill())
+        assert_array_equal(s(x), [True, True, False, True])
+
+    def test_fill_dict(self):
+
+        x = pd.Series(["a", "a", "b", "a"], name="x")
+        vs = {"a": False, "b": True}
+        s = Nominal(vs)._setup(x, Fill())
+        assert_array_equal(s(x), [False, False, True, False])
+
+    def test_fill_nunique_warning(self):
+
+        x = pd.Series(["a", "b", "c", "a", "b"], name="x")
+        with pytest.warns(UserWarning, match="The variable assigned to fill"):
+            s = Nominal()._setup(x, Fill())
+        assert_array_equal(s(x), [True, False, True, True, False])
+
+    def test_interval_defaults(self, x):
+
+        class MockProperty(IntervalProperty):
+            _default_range = (1, 2)
+
+        s = Nominal()._setup(x, MockProperty())
+        assert_array_equal(s(x), [2, 1.5, 1, 1.5])
+
+    def test_interval_tuple(self, x):
+
+        s = Nominal((1, 2))._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [2, 1.5, 1, 1.5])
+
+    def test_interval_tuple_numeric(self, y):
+
+        s = Nominal((1, 2))._setup(y, IntervalProperty())
+        assert_array_equal(s(y), [1.5, 2, 1, 2])
+
+    def test_interval_list(self, x):
+
+        vs = [2, 5, 4]
+        s = Nominal(vs)._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [2, 5, 4, 5])
+
+    def test_interval_dict(self, x):
+
+        vs = {"a": 3, "b": 4, "c": 6}
+        s = Nominal(vs)._setup(x, IntervalProperty())
+        assert_array_equal(s(x), [3, 6, 4, 6])
+
+    def test_interval_with_transform(self, x):
+
+        class MockProperty(IntervalProperty):
+            _forward = np.square
+            _inverse = np.sqrt
+
+        s = Nominal((2, 4))._setup(x, MockProperty())
+        assert_array_equal(s(x), [4, np.sqrt(10), 2, np.sqrt(10)])
+
+    def test_empty_data(self):
+
+        x = pd.Series([], dtype=object, name="x")
+        s = Nominal()._setup(x, Coordinate())
+        assert_array_equal(s(x), [])
+
+    @pytest.mark.skipif(
+        _version_predates(mpl, "3.4.0"),
+        reason="Test failing on older matplotlib for unclear reasons",
+    )
+    def test_finalize(self, x):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Nominal()._setup(x, Coordinate(), ax.yaxis)
+        s._finalize(Plot(), ax.yaxis)
+
+        levels = x.unique()
+        assert ax.get_ylim() == (len(levels) - .5, -.5)
+        assert_array_equal(ax.get_yticks(), list(range(len(levels))))
+        for i, expected in enumerate(levels):
+            assert ax.yaxis.major.formatter(i) == expected
+
+
+class TestTemporal:
+
+    @pytest.fixture
+    def t(self):
+        dates = pd.to_datetime(["1972-09-27", "1975-06-24", "1980-12-14"])
+        return pd.Series(dates, name="x")
+
+    @pytest.fixture
+    def x(self, t):
+        return pd.Series(mpl.dates.date2num(t), name=t.name)
+
+    def test_coordinate_defaults(self, t, x):
+
+        s = Temporal()._setup(t, Coordinate())
+        assert_array_equal(s(t), x)
+
+    def test_interval_defaults(self, t, x):
+
+        s = Temporal()._setup(t, IntervalProperty())
+        normed = (x - x.min()) / (x.max() - x.min())
+        assert_array_equal(s(t), normed)
+
+    def test_interval_with_range(self, t, x):
+
+        values = (1, 3)
+        s = Temporal((1, 3))._setup(t, IntervalProperty())
+        normed = (x - x.min()) / (x.max() - x.min())
+        expected = normed * (values[1] - values[0]) + values[0]
+        assert_array_equal(s(t), expected)
+
+    def test_interval_with_norm(self, t, x):
+
+        norm = t[1], t[2]
+        s = Temporal(norm=norm)._setup(t, IntervalProperty())
+        n = mpl.dates.date2num(norm)
+        normed = (x - n[0]) / (n[1] - n[0])
+        assert_array_equal(s(t), normed)
+
+    def test_color_defaults(self, t, x):
+
+        cmap = color_palette("ch:", as_cmap=True)
+        s = Temporal()._setup(t, Color())
+        normed = (x - x.min()) / (x.max() - x.min())
+        assert_array_equal(s(t), cmap(normed)[:, :3])  # FIXME RGBA
+
+    def test_color_named_values(self, t, x):
+
+        name = "viridis"
+        cmap = color_palette(name, as_cmap=True)
+        s = Temporal(name)._setup(t, Color())
+        normed = (x - x.min()) / (x.max() - x.min())
+        assert_array_equal(s(t), cmap(normed)[:, :3])  # FIXME RGBA
+
+    def test_coordinate_axis(self, t, x):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Temporal()._setup(t, Coordinate(), ax.xaxis)
+        assert_array_equal(s(t), x)
+        locator = ax.xaxis.get_major_locator()
+        formatter = ax.xaxis.get_major_formatter()
+        assert isinstance(locator, mpl.dates.AutoDateLocator)
+        assert isinstance(formatter, mpl.dates.AutoDateFormatter)
+
+    def test_tick_locator(self, t):
+
+        locator = mpl.dates.YearLocator(month=3, day=15)
+        s = Temporal().tick(locator)
+        a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)
+        a.set_view_interval(0, 365)
+        assert 73 in a.major.locator()
+
+    def test_tick_upto(self, t, x):
+
+        n = 8
+        ax = mpl.figure.Figure().subplots()
+        Temporal().tick(upto=n)._setup(t, Coordinate(), ax.xaxis)
+        locator = ax.xaxis.get_major_locator()
+        assert set(locator.maxticks.values()) == {n}
+
+    def test_label_formatter(self, t):
+
+        formatter = mpl.dates.DateFormatter("%Y")
+        s = Temporal().label(formatter)
+        a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)
+        a.set_view_interval(10, 1000)
+        label, = a.major.formatter.format_ticks([100])
+        assert label == "1970"
+
+    def test_label_concise(self, t, x):
+
+        ax = mpl.figure.Figure().subplots()
+        Temporal().label(concise=True)._setup(t, Coordinate(), ax.xaxis)
+        formatter = ax.xaxis.get_major_formatter()
+        assert isinstance(formatter, mpl.dates.ConciseDateFormatter)
+
+
+class TestBoolean:
+
+    @pytest.fixture
+    def x(self):
+        return pd.Series([True, False, False, True], name="x", dtype=bool)
+
+    def test_coordinate(self, x):
+
+        s = Boolean()._setup(x, Coordinate())
+        assert_array_equal(s(x), x.astype(float))
+
+    def test_coordinate_axis(self, x):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Boolean()._setup(x, Coordinate(), ax.xaxis)
+        assert_array_equal(s(x), x.astype(float))
+        f = ax.xaxis.get_major_formatter()
+        assert f.format_ticks([0, 1]) == ["False", "True"]
+
+    @pytest.mark.parametrize(
+        "dtype,value",
+        [
+            (object, np.nan),
+            (object, None),
+            ("boolean", pd.NA),
+        ]
+    )
+    def test_coordinate_missing(self, x, dtype, value):
+
+        x = x.astype(dtype)
+        x[2] = value
+        s = Boolean()._setup(x, Coordinate())
+        assert_array_equal(s(x), x.astype(float))
+
+    def test_color_defaults(self, x):
+
+        s = Boolean()._setup(x, Color())
+        cs = color_palette()
+        expected = [cs[int(x_i)] for x_i in ~x]
+        assert_array_equal(s(x), expected)
+
+    def test_color_list_palette(self, x):
+
+        cs = color_palette("crest", 2)
+        s = Boolean(cs)._setup(x, Color())
+        expected = [cs[int(x_i)] for x_i in ~x]
+        assert_array_equal(s(x), expected)
+
+    def test_color_tuple_palette(self, x):
+
+        cs = tuple(color_palette("crest", 2))
+        s = Boolean(cs)._setup(x, Color())
+        expected = [cs[int(x_i)] for x_i in ~x]
+        assert_array_equal(s(x), expected)
+
+    def test_color_dict_palette(self, x):
+
+        cs = color_palette("crest", 2)
+        pal = {True: cs[0], False: cs[1]}
+        s = Boolean(pal)._setup(x, Color())
+        expected = [pal[x_i] for x_i in x]
+        assert_array_equal(s(x), expected)
+
+    def test_object_defaults(self, x):
+
+        vs = ["x", "y", "z"]
+
+        class MockProperty(ObjectProperty):
+            def _default_values(self, n):
+                return vs[:n]
+
+        s = Boolean()._setup(x, MockProperty())
+        expected = [vs[int(x_i)] for x_i in ~x]
+        assert s(x) == expected
+
+    def test_object_list(self, x):
+
+        vs = ["x", "y"]
+        s = Boolean(vs)._setup(x, ObjectProperty())
+        expected = [vs[int(x_i)] for x_i in ~x]
+        assert s(x) == expected
+
+    def test_object_dict(self, x):
+
+        vs = {True: "x", False: "y"}
+        s = Boolean(vs)._setup(x, ObjectProperty())
+        expected = [vs[x_i] for x_i in x]
+        assert s(x) == expected
+
+    def test_fill(self, x):
+
+        s = Boolean()._setup(x, Fill())
+        assert_array_equal(s(x), x)
+
+    def test_interval_defaults(self, x):
+
+        vs = (1, 2)
+
+        class MockProperty(IntervalProperty):
+            _default_range = vs
+
+        s = Boolean()._setup(x, MockProperty())
+        expected = [vs[int(x_i)] for x_i in x]
+        assert_array_equal(s(x), expected)
+
+    def test_interval_tuple(self, x):
+
+        vs = (3, 5)
+        s = Boolean(vs)._setup(x, IntervalProperty())
+        expected = [vs[int(x_i)] for x_i in x]
+        assert_array_equal(s(x), expected)
+
+    def test_finalize(self, x):
+
+        ax = mpl.figure.Figure().subplots()
+        s = Boolean()._setup(x, Coordinate(), ax.xaxis)
+        s._finalize(Plot(), ax.xaxis)
+        assert ax.get_xlim() == (1.5, -.5)
+        assert_array_equal(ax.get_xticks(), [0, 1])
+        assert ax.xaxis.major.formatter(0) == "False"
+        assert ax.xaxis.major.formatter(1) == "True"
diff --git a/testbed/mwaskom__seaborn/tests/_core/test_subplots.py b/testbed/mwaskom__seaborn/tests/_core/test_subplots.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9e2e340de7cae5e7c4040ccd6c5725cc9684685
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_core/test_subplots.py
@@ -0,0 +1,525 @@
+import itertools
+
+import numpy as np
+import pytest
+
+from seaborn._core.subplots import Subplots
+
+
+class TestSpecificationChecks:
+
+    def test_both_facets_and_wrap(self):
+
+        err = "Cannot wrap facets when specifying both `col` and `row`."
+        facet_spec = {"wrap": 3, "variables": {"col": "a", "row": "b"}}
+        with pytest.raises(RuntimeError, match=err):
+            Subplots({}, facet_spec, {})
+
+    def test_cross_xy_pairing_and_wrap(self):
+
+        err = "Cannot wrap subplots when pairing on both `x` and `y`."
+        pair_spec = {"wrap": 3, "structure": {"x": ["a", "b"], "y": ["y", "z"]}}
+        with pytest.raises(RuntimeError, match=err):
+            Subplots({}, {}, pair_spec)
+
+    def test_col_facets_and_x_pairing(self):
+
+        err = "Cannot facet the columns while pairing on `x`."
+        facet_spec = {"variables": {"col": "a"}}
+        pair_spec = {"structure": {"x": ["x", "y"]}}
+        with pytest.raises(RuntimeError, match=err):
+            Subplots({}, facet_spec, pair_spec)
+
+    def test_wrapped_columns_and_y_pairing(self):
+
+        err = "Cannot wrap the columns while pairing on `y`."
+        facet_spec = {"variables": {"col": "a"}, "wrap": 2}
+        pair_spec = {"structure": {"y": ["x", "y"]}}
+        with pytest.raises(RuntimeError, match=err):
+            Subplots({}, facet_spec, pair_spec)
+
+    def test_wrapped_x_pairing_and_facetd_rows(self):
+
+        err = "Cannot wrap the columns while faceting the rows."
+        facet_spec = {"variables": {"row": "a"}}
+        pair_spec = {"structure": {"x": ["x", "y"]}, "wrap": 2}
+        with pytest.raises(RuntimeError, match=err):
+            Subplots({}, facet_spec, pair_spec)
+
+
+class TestSubplotSpec:
+
+    def test_single_subplot(self):
+
+        s = Subplots({}, {}, {})
+
+        assert s.n_subplots == 1
+        assert s.subplot_spec["ncols"] == 1
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_single_facet(self):
+
+        key = "a"
+        order = list("abc")
+        spec = {"variables": {"col": key}, "structure": {"col": order}}
+        s = Subplots({}, spec, {})
+
+        assert s.n_subplots == len(order)
+        assert s.subplot_spec["ncols"] == len(order)
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_two_facets(self):
+
+        col_key = "a"
+        row_key = "b"
+        col_order = list("xy")
+        row_order = list("xyz")
+        spec = {
+            "variables": {"col": col_key, "row": row_key},
+            "structure": {"col": col_order, "row": row_order},
+
+        }
+        s = Subplots({}, spec, {})
+
+        assert s.n_subplots == len(col_order) * len(row_order)
+        assert s.subplot_spec["ncols"] == len(col_order)
+        assert s.subplot_spec["nrows"] == len(row_order)
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_col_facet_wrapped(self):
+
+        key = "b"
+        wrap = 3
+        order = list("abcde")
+        spec = {"variables": {"col": key}, "structure": {"col": order}, "wrap": wrap}
+        s = Subplots({}, spec, {})
+
+        assert s.n_subplots == len(order)
+        assert s.subplot_spec["ncols"] == wrap
+        assert s.subplot_spec["nrows"] == len(order) // wrap + 1
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_row_facet_wrapped(self):
+
+        key = "b"
+        wrap = 3
+        order = list("abcde")
+        spec = {"variables": {"row": key}, "structure": {"row": order}, "wrap": wrap}
+        s = Subplots({}, spec, {})
+
+        assert s.n_subplots == len(order)
+        assert s.subplot_spec["ncols"] == len(order) // wrap + 1
+        assert s.subplot_spec["nrows"] == wrap
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_col_facet_wrapped_single_row(self):
+
+        key = "b"
+        order = list("abc")
+        wrap = len(order) + 2
+        spec = {"variables": {"col": key}, "structure": {"col": order}, "wrap": wrap}
+        s = Subplots({}, spec, {})
+
+        assert s.n_subplots == len(order)
+        assert s.subplot_spec["ncols"] == len(order)
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is True
+
+    def test_x_and_y_paired(self):
+
+        x = ["x", "y", "z"]
+        y = ["a", "b"]
+        s = Subplots({}, {}, {"structure": {"x": x, "y": y}})
+
+        assert s.n_subplots == len(x) * len(y)
+        assert s.subplot_spec["ncols"] == len(x)
+        assert s.subplot_spec["nrows"] == len(y)
+        assert s.subplot_spec["sharex"] == "col"
+        assert s.subplot_spec["sharey"] == "row"
+
+    def test_x_paired(self):
+
+        x = ["x", "y", "z"]
+        s = Subplots({}, {}, {"structure": {"x": x}})
+
+        assert s.n_subplots == len(x)
+        assert s.subplot_spec["ncols"] == len(x)
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] == "col"
+        assert s.subplot_spec["sharey"] is True
+
+    def test_y_paired(self):
+
+        y = ["x", "y", "z"]
+        s = Subplots({}, {}, {"structure": {"y": y}})
+
+        assert s.n_subplots == len(y)
+        assert s.subplot_spec["ncols"] == 1
+        assert s.subplot_spec["nrows"] == len(y)
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] == "row"
+
+    def test_x_paired_and_wrapped(self):
+
+        x = ["a", "b", "x", "y", "z"]
+        wrap = 3
+        s = Subplots({}, {}, {"structure": {"x": x}, "wrap": wrap})
+
+        assert s.n_subplots == len(x)
+        assert s.subplot_spec["ncols"] == wrap
+        assert s.subplot_spec["nrows"] == len(x) // wrap + 1
+        assert s.subplot_spec["sharex"] is False
+        assert s.subplot_spec["sharey"] is True
+
+    def test_y_paired_and_wrapped(self):
+
+        y = ["a", "b", "x", "y", "z"]
+        wrap = 2
+        s = Subplots({}, {}, {"structure": {"y": y}, "wrap": wrap})
+
+        assert s.n_subplots == len(y)
+        assert s.subplot_spec["ncols"] == len(y) // wrap + 1
+        assert s.subplot_spec["nrows"] == wrap
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is False
+
+    def test_y_paired_and_wrapped_single_row(self):
+
+        y = ["x", "y", "z"]
+        wrap = 1
+        s = Subplots({}, {}, {"structure": {"y": y}, "wrap": wrap})
+
+        assert s.n_subplots == len(y)
+        assert s.subplot_spec["ncols"] == len(y)
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] is False
+
+    def test_col_faceted_y_paired(self):
+
+        y = ["x", "y", "z"]
+        key = "a"
+        order = list("abc")
+        facet_spec = {"variables": {"col": key}, "structure": {"col": order}}
+        pair_spec = {"structure": {"y": y}}
+        s = Subplots({}, facet_spec, pair_spec)
+
+        assert s.n_subplots == len(order) * len(y)
+        assert s.subplot_spec["ncols"] == len(order)
+        assert s.subplot_spec["nrows"] == len(y)
+        assert s.subplot_spec["sharex"] is True
+        assert s.subplot_spec["sharey"] == "row"
+
+    def test_row_faceted_x_paired(self):
+
+        x = ["f", "s"]
+        key = "a"
+        order = list("abc")
+        facet_spec = {"variables": {"row": key}, "structure": {"row": order}}
+        pair_spec = {"structure": {"x": x}}
+        s = Subplots({}, facet_spec, pair_spec)
+
+        assert s.n_subplots == len(order) * len(x)
+        assert s.subplot_spec["ncols"] == len(x)
+        assert s.subplot_spec["nrows"] == len(order)
+        assert s.subplot_spec["sharex"] == "col"
+        assert s.subplot_spec["sharey"] is True
+
+    def test_x_any_y_paired_non_cross(self):
+
+        x = ["a", "b", "c"]
+        y = ["x", "y", "z"]
+        spec = {"structure": {"x": x, "y": y}, "cross": False}
+        s = Subplots({}, {}, spec)
+
+        assert s.n_subplots == len(x)
+        assert s.subplot_spec["ncols"] == len(y)
+        assert s.subplot_spec["nrows"] == 1
+        assert s.subplot_spec["sharex"] is False
+        assert s.subplot_spec["sharey"] is False
+
+    def test_x_any_y_paired_non_cross_wrapped(self):
+
+        x = ["a", "b", "c"]
+        y = ["x", "y", "z"]
+        wrap = 2
+        spec = {"structure": {"x": x, "y": y}, "cross": False, "wrap": wrap}
+        s = Subplots({}, {}, spec)
+
+        assert s.n_subplots == len(x)
+        assert s.subplot_spec["ncols"] == wrap
+        assert s.subplot_spec["nrows"] == len(x) // wrap + 1
+        assert s.subplot_spec["sharex"] is False
+        assert s.subplot_spec["sharey"] is False
+
+    def test_forced_unshared_facets(self):
+
+        s = Subplots({"sharex": False, "sharey": "row"}, {}, {})
+        assert s.subplot_spec["sharex"] is False
+        assert s.subplot_spec["sharey"] == "row"
+
+
+class TestSubplotElements:
+
+    def test_single_subplot(self):
+
+        s = Subplots({}, {}, {})
+        f = s.init_figure({}, {})
+
+        assert len(s) == 1
+        for i, e in enumerate(s):
+            for side in ["left", "right", "bottom", "top"]:
+                assert e[side]
+            for dim in ["col", "row"]:
+                assert e[dim] is None
+            for axis in "xy":
+                assert e[axis] == axis
+            assert e["ax"] == f.axes[i]
+
+    @pytest.mark.parametrize("dim", ["col", "row"])
+    def test_single_facet_dim(self, dim):
+
+        key = "a"
+        order = list("abc")
+        spec = {"variables": {dim: key}, "structure": {dim: order}}
+        s = Subplots({}, spec, {})
+        s.init_figure(spec, {})
+
+        assert len(s) == len(order)
+
+        for i, e in enumerate(s):
+            assert e[dim] == order[i]
+            for axis in "xy":
+                assert e[axis] == axis
+            assert e["top"] == (dim == "col" or i == 0)
+            assert e["bottom"] == (dim == "col" or i == len(order) - 1)
+            assert e["left"] == (dim == "row" or i == 0)
+            assert e["right"] == (dim == "row" or i == len(order) - 1)
+
+    @pytest.mark.parametrize("dim", ["col", "row"])
+    def test_single_facet_dim_wrapped(self, dim):
+
+        key = "b"
+        order = list("abc")
+        wrap = len(order) - 1
+        spec = {"variables": {dim: key}, "structure": {dim: order}, "wrap": wrap}
+        s = Subplots({}, spec, {})
+        s.init_figure(spec, {})
+
+        assert len(s) == len(order)
+
+        for i, e in enumerate(s):
+            assert e[dim] == order[i]
+            for axis in "xy":
+                assert e[axis] == axis
+
+            sides = {
+                "col": ["top", "bottom", "left", "right"],
+                "row": ["left", "right", "top", "bottom"],
+            }
+            tests = (
+                i < wrap,
+                i >= wrap or i >= len(s) % wrap,
+                i % wrap == 0,
+                i % wrap == wrap - 1 or i + 1 == len(s),
+            )
+
+            for side, expected in zip(sides[dim], tests):
+                assert e[side] == expected
+
+    def test_both_facet_dims(self):
+
+        col = "a"
+        row = "b"
+        col_order = list("ab")
+        row_order = list("xyz")
+        facet_spec = {
+            "variables": {"col": col, "row": row},
+            "structure": {"col": col_order, "row": row_order},
+        }
+        s = Subplots({}, facet_spec, {})
+        s.init_figure(facet_spec, {})
+
+        n_cols = len(col_order)
+        n_rows = len(row_order)
+        assert len(s) == n_cols * n_rows
+        es = list(s)
+
+        for e in es[:n_cols]:
+            assert e["top"]
+        for e in es[::n_cols]:
+            assert e["left"]
+        for e in es[n_cols - 1::n_cols]:
+            assert e["right"]
+        for e in es[-n_cols:]:
+            assert e["bottom"]
+
+        for e, (row_, col_) in zip(es, itertools.product(row_order, col_order)):
+            assert e["col"] == col_
+            assert e["row"] == row_
+
+        for e in es:
+            assert e["x"] == "x"
+            assert e["y"] == "y"
+
+    @pytest.mark.parametrize("var", ["x", "y"])
+    def test_single_paired_var(self, var):
+
+        other_var = {"x": "y", "y": "x"}[var]
+        pairings = ["x", "y", "z"]
+        pair_spec = {
+            "variables": {f"{var}{i}": v for i, v in enumerate(pairings)},
+            "structure": {var: [f"{var}{i}" for i, _ in enumerate(pairings)]},
+        }
+
+        s = Subplots({}, {}, pair_spec)
+        s.init_figure(pair_spec)
+
+        assert len(s) == len(pair_spec["structure"][var])
+
+        for i, e in enumerate(s):
+            assert e[var] == f"{var}{i}"
+            assert e[other_var] == other_var
+            assert e["col"] is e["row"] is None
+
+        tests = i == 0, True, True, i == len(s) - 1
+        sides = {
+            "x": ["left", "right", "top", "bottom"],
+            "y": ["top", "bottom", "left", "right"],
+        }
+
+        for side, expected in zip(sides[var], tests):
+            assert e[side] == expected
+
+    @pytest.mark.parametrize("var", ["x", "y"])
+    def test_single_paired_var_wrapped(self, var):
+
+        other_var = {"x": "y", "y": "x"}[var]
+        pairings = ["x", "y", "z", "a", "b"]
+        wrap = len(pairings) - 2
+        pair_spec = {
+            "variables": {f"{var}{i}": val for i, val in enumerate(pairings)},
+            "structure": {var: [f"{var}{i}" for i, _ in enumerate(pairings)]},
+            "wrap": wrap
+        }
+        s = Subplots({}, {}, pair_spec)
+        s.init_figure(pair_spec)
+
+        assert len(s) == len(pairings)
+
+        for i, e in enumerate(s):
+            assert e[var] == f"{var}{i}"
+            assert e[other_var] == other_var
+            assert e["col"] is e["row"] is None
+
+            tests = (
+                i < wrap,
+                i >= wrap or i >= len(s) % wrap,
+                i % wrap == 0,
+                i % wrap == wrap - 1 or i + 1 == len(s),
+            )
+            sides = {
+                "x": ["top", "bottom", "left", "right"],
+                "y": ["left", "right", "top", "bottom"],
+            }
+            for side, expected in zip(sides[var], tests):
+                assert e[side] == expected
+
+    def test_both_paired_variables(self):
+
+        x = ["x0", "x1"]
+        y = ["y0", "y1", "y2"]
+        pair_spec = {"structure": {"x": x, "y": y}}
+        s = Subplots({}, {}, pair_spec)
+        s.init_figure(pair_spec)
+
+        n_cols = len(x)
+        n_rows = len(y)
+        assert len(s) == n_cols * n_rows
+        es = list(s)
+
+        for e in es[:n_cols]:
+            assert e["top"]
+        for e in es[::n_cols]:
+            assert e["left"]
+        for e in es[n_cols - 1::n_cols]:
+            assert e["right"]
+        for e in es[-n_cols:]:
+            assert e["bottom"]
+
+        for e in es:
+            assert e["col"] is e["row"] is None
+
+        for i in range(len(y)):
+            for j in range(len(x)):
+                e = es[i * len(x) + j]
+                assert e["x"] == f"x{j}"
+                assert e["y"] == f"y{i}"
+
+    def test_both_paired_non_cross(self):
+
+        pair_spec = {
+            "structure": {"x": ["x0", "x1", "x2"], "y": ["y0", "y1", "y2"]},
+            "cross": False
+        }
+        s = Subplots({}, {}, pair_spec)
+        s.init_figure(pair_spec)
+
+        for i, e in enumerate(s):
+            assert e["x"] == f"x{i}"
+            assert e["y"] == f"y{i}"
+            assert e["col"] is e["row"] is None
+            assert e["left"] == (i == 0)
+            assert e["right"] == (i == (len(s) - 1))
+            assert e["top"]
+            assert e["bottom"]
+
+    @pytest.mark.parametrize("dim,var", [("col", "y"), ("row", "x")])
+    def test_one_facet_one_paired(self, dim, var):
+
+        other_var = {"x": "y", "y": "x"}[var]
+        other_dim = {"col": "row", "row": "col"}[dim]
+        order = list("abc")
+        facet_spec = {"variables": {dim: "s"}, "structure": {dim: order}}
+
+        pairings = ["x", "y", "t"]
+        pair_spec = {
+            "variables": {f"{var}{i}": val for i, val in enumerate(pairings)},
+            "structure": {var: [f"{var}{i}" for i, _ in enumerate(pairings)]},
+        }
+
+        s = Subplots({}, facet_spec, pair_spec)
+        s.init_figure(pair_spec)
+
+        n_cols = len(order) if dim == "col" else len(pairings)
+        n_rows = len(order) if dim == "row" else len(pairings)
+
+        assert len(s) == len(order) * len(pairings)
+
+        es = list(s)
+
+        for e in es[:n_cols]:
+            assert e["top"]
+        for e in es[::n_cols]:
+            assert e["left"]
+        for e in es[n_cols - 1::n_cols]:
+            assert e["right"]
+        for e in es[-n_cols:]:
+            assert e["bottom"]
+
+        if dim == "row":
+            es = np.reshape(es, (n_rows, n_cols)).T.ravel()
+
+        for i, e in enumerate(es):
+            assert e[dim] == order[i % len(pairings)]
+            assert e[other_dim] is None
+            assert e[var] == f"{var}{i // len(order)}"
+            assert e[other_var] == other_var
diff --git a/testbed/mwaskom__seaborn/tests/_marks/__init__.py b/testbed/mwaskom__seaborn/tests/_marks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_area.py b/testbed/mwaskom__seaborn/tests/_marks/test_area.py
new file mode 100644
index 0000000000000000000000000000000000000000..d725e154ce0a3a1093d74fc4df2384ccfd5affb1
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_area.py
@@ -0,0 +1,128 @@
+
+import matplotlib as mpl
+from matplotlib.colors import to_rgba, to_rgba_array
+
+from numpy.testing import assert_array_equal
+
+from seaborn._core.plot import Plot
+from seaborn._marks.area import Area, Band
+
+
+class TestArea:
+
+    def test_single_defaults(self):
+
+        x, y = [1, 2, 3], [1, 2, 1]
+        p = Plot(x=x, y=y).add(Area()).plot()
+        ax = p._figure.axes[0]
+        poly = ax.patches[0]
+        verts = poly.get_path().vertices.T
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+
+        expected_x = [1, 2, 3, 3, 2, 1, 1]
+        assert_array_equal(verts[0], expected_x)
+
+        expected_y = [0, 0, 0, 1, 2, 1, 0]
+        assert_array_equal(verts[1], expected_y)
+
+        fc = poly.get_facecolor()
+        assert_array_equal(fc, to_rgba(colors[0], .2))
+
+        ec = poly.get_edgecolor()
+        assert_array_equal(ec, to_rgba(colors[0], 1))
+
+        lw = poly.get_linewidth()
+        assert_array_equal(lw, mpl.rcParams["patch.linewidth"] * 2)
+
+    def test_set_properties(self):
+
+        x, y = [1, 2, 3], [1, 2, 1]
+        mark = Area(
+            color=".33",
+            alpha=.3,
+            edgecolor=".88",
+            edgealpha=.8,
+            edgewidth=2,
+            edgestyle=(0, (2, 1)),
+        )
+        p = Plot(x=x, y=y).add(mark).plot()
+        ax = p._figure.axes[0]
+        poly = ax.patches[0]
+
+        fc = poly.get_facecolor()
+        assert_array_equal(fc, to_rgba(mark.color, mark.alpha))
+
+        ec = poly.get_edgecolor()
+        assert_array_equal(ec, to_rgba(mark.edgecolor, mark.edgealpha))
+
+        lw = poly.get_linewidth()
+        assert_array_equal(lw, mark.edgewidth * 2)
+
+        ls = poly.get_linestyle()
+        dash_on, dash_off = mark.edgestyle[1]
+        expected = (0, (mark.edgewidth * dash_on / 4, mark.edgewidth * dash_off / 4))
+        assert ls == expected
+
+    def test_mapped_properties(self):
+
+        x, y = [1, 2, 3, 2, 3, 4], [1, 2, 1, 1, 3, 2]
+        g = ["a", "a", "a", "b", "b", "b"]
+        cs = [".2", ".8"]
+        p = Plot(x=x, y=y, color=g, edgewidth=g).scale(color=cs).add(Area()).plot()
+        ax = p._figure.axes[0]
+
+        expected_x = [1, 2, 3, 3, 2, 1, 1], [2, 3, 4, 4, 3, 2, 2]
+        expected_y = [0, 0, 0, 1, 2, 1, 0], [0, 0, 0, 2, 3, 1, 0]
+
+        for i, poly in enumerate(ax.patches):
+            verts = poly.get_path().vertices.T
+            assert_array_equal(verts[0], expected_x[i])
+            assert_array_equal(verts[1], expected_y[i])
+
+        fcs = [p.get_facecolor() for p in ax.patches]
+        assert_array_equal(fcs, to_rgba_array(cs, .2))
+
+        ecs = [p.get_edgecolor() for p in ax.patches]
+        assert_array_equal(ecs, to_rgba_array(cs, 1))
+
+        lws = [p.get_linewidth() for p in ax.patches]
+        assert lws[0] > lws[1]
+
+    def test_unfilled(self):
+
+        x, y = [1, 2, 3], [1, 2, 1]
+        c = ".5"
+        p = Plot(x=x, y=y).add(Area(fill=False, color=c)).plot()
+        ax = p._figure.axes[0]
+        poly = ax.patches[0]
+        assert poly.get_facecolor() == to_rgba(c, 0)
+
+
+class TestBand:
+
+    def test_range(self):
+
+        x, ymin, ymax = [1, 2, 4], [2, 1, 4], [3, 3, 5]
+        p = Plot(x=x, ymin=ymin, ymax=ymax).add(Band()).plot()
+        ax = p._figure.axes[0]
+        verts = ax.patches[0].get_path().vertices.T
+
+        expected_x = [1, 2, 4, 4, 2, 1, 1]
+        assert_array_equal(verts[0], expected_x)
+
+        expected_y = [2, 1, 4, 5, 3, 3, 2]
+        assert_array_equal(verts[1], expected_y)
+
+    def test_auto_range(self):
+
+        x = [1, 1, 2, 2, 2]
+        y = [1, 2, 3, 4, 5]
+        p = Plot(x=x, y=y).add(Band()).plot()
+        ax = p._figure.axes[0]
+        verts = ax.patches[0].get_path().vertices.T
+
+        expected_x = [1, 2, 2, 1, 1]
+        assert_array_equal(verts[0], expected_x)
+
+        expected_y = [1, 3, 5, 2, 1]
+        assert_array_equal(verts[1], expected_y)
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_bar.py b/testbed/mwaskom__seaborn/tests/_marks/test_bar.py
new file mode 100644
index 0000000000000000000000000000000000000000..373882e12cc5294ff0579dca00c6624b151f41ef
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_bar.py
@@ -0,0 +1,202 @@
+
+import numpy as np
+import pandas as pd
+from matplotlib.colors import to_rgba, to_rgba_array
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn._core.plot import Plot
+from seaborn._marks.bar import Bar, Bars
+
+
+class TestBar:
+
+    def plot_bars(self, variables, mark_kws, layer_kws):
+
+        p = Plot(**variables).add(Bar(**mark_kws), **layer_kws).plot()
+        ax = p._figure.axes[0]
+        return [bar for barlist in ax.containers for bar in barlist]
+
+    def check_bar(self, bar, x, y, width, height):
+
+        assert bar.get_x() == pytest.approx(x)
+        assert bar.get_y() == pytest.approx(y)
+        assert bar.get_width() == pytest.approx(width)
+        assert bar.get_height() == pytest.approx(height)
+
+    def test_categorical_positions_vertical(self):
+
+        x = ["a", "b"]
+        y = [1, 2]
+        w = .8
+        bars = self.plot_bars({"x": x, "y": y}, {}, {})
+        for i, bar in enumerate(bars):
+            self.check_bar(bar, i - w / 2, 0, w, y[i])
+
+    def test_categorical_positions_horizontal(self):
+
+        x = [1, 2]
+        y = ["a", "b"]
+        w = .8
+        bars = self.plot_bars({"x": x, "y": y}, {}, {})
+        for i, bar in enumerate(bars):
+            self.check_bar(bar, 0, i - w / 2, x[i], w)
+
+    def test_numeric_positions_vertical(self):
+
+        x = [1, 2]
+        y = [3, 4]
+        w = .8
+        bars = self.plot_bars({"x": x, "y": y}, {}, {})
+        for i, bar in enumerate(bars):
+            self.check_bar(bar, x[i] - w / 2, 0, w, y[i])
+
+    def test_numeric_positions_horizontal(self):
+
+        x = [1, 2]
+        y = [3, 4]
+        w = .8
+        bars = self.plot_bars({"x": x, "y": y}, {}, {"orient": "h"})
+        for i, bar in enumerate(bars):
+            self.check_bar(bar, 0, y[i] - w / 2, x[i], w)
+
+    def test_set_properties(self):
+
+        x = ["a", "b", "c"]
+        y = [1, 3, 2]
+
+        mark = Bar(
+            color=".8",
+            alpha=.5,
+            edgecolor=".3",
+            edgealpha=.9,
+            edgestyle=(2, 1),
+            edgewidth=1.5,
+        )
+
+        p = Plot(x, y).add(mark).plot()
+        ax = p._figure.axes[0]
+        for bar in ax.patches:
+            assert bar.get_facecolor() == to_rgba(mark.color, mark.alpha)
+            assert bar.get_edgecolor() == to_rgba(mark.edgecolor, mark.edgealpha)
+            # See comments in plotting method for why we need these adjustments
+            assert bar.get_linewidth() == mark.edgewidth * 2
+            expected_dashes = (mark.edgestyle[0] / 2, mark.edgestyle[1] / 2)
+            assert bar.get_linestyle() == (0, expected_dashes)
+
+    def test_mapped_properties(self):
+
+        x = ["a", "b"]
+        y = [1, 2]
+        mark = Bar(alpha=.2)
+        p = Plot(x, y, color=x, edgewidth=y).add(mark).plot()
+        ax = p._figure.axes[0]
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+        for i, bar in enumerate(ax.patches):
+            assert bar.get_facecolor() == to_rgba(colors[i], mark.alpha)
+            assert bar.get_edgecolor() == to_rgba(colors[i], 1)
+        assert ax.patches[0].get_linewidth() < ax.patches[1].get_linewidth()
+
+    def test_zero_height_skipped(self):
+
+        p = Plot(["a", "b", "c"], [1, 0, 2]).add(Bar()).plot()
+        ax = p._figure.axes[0]
+        assert len(ax.patches) == 2
+
+    def test_artist_kws_clip(self):
+
+        p = Plot(["a", "b"], [1, 2]).add(Bar({"clip_on": False})).plot()
+        patch = p._figure.axes[0].patches[0]
+        assert patch.clipbox is None
+
+
+class TestBars:
+
+    @pytest.fixture
+    def x(self):
+        return pd.Series([4, 5, 6, 7, 8], name="x")
+
+    @pytest.fixture
+    def y(self):
+        return pd.Series([2, 8, 3, 5, 9], name="y")
+
+    @pytest.fixture
+    def color(self):
+        return pd.Series(["a", "b", "c", "a", "c"], name="color")
+
+    def test_positions(self, x, y):
+
+        p = Plot(x, y).add(Bars()).plot()
+        ax = p._figure.axes[0]
+        paths = ax.collections[0].get_paths()
+        assert len(paths) == len(x)
+        for i, path in enumerate(paths):
+            verts = path.vertices
+            assert verts[0, 0] == pytest.approx(x[i] - .5)
+            assert verts[1, 0] == pytest.approx(x[i] + .5)
+            assert verts[0, 1] == 0
+            assert verts[3, 1] == y[i]
+
+    def test_positions_horizontal(self, x, y):
+
+        p = Plot(x=y, y=x).add(Bars(), orient="h").plot()
+        ax = p._figure.axes[0]
+        paths = ax.collections[0].get_paths()
+        assert len(paths) == len(x)
+        for i, path in enumerate(paths):
+            verts = path.vertices
+            assert verts[0, 1] == pytest.approx(x[i] - .5)
+            assert verts[3, 1] == pytest.approx(x[i] + .5)
+            assert verts[0, 0] == 0
+            assert verts[1, 0] == y[i]
+
+    def test_width(self, x, y):
+
+        p = Plot(x, y).add(Bars(width=.4)).plot()
+        ax = p._figure.axes[0]
+        paths = ax.collections[0].get_paths()
+        for i, path in enumerate(paths):
+            verts = path.vertices
+            assert verts[0, 0] == pytest.approx(x[i] - .2)
+            assert verts[1, 0] == pytest.approx(x[i] + .2)
+
+    def test_mapped_color_direct_alpha(self, x, y, color):
+
+        alpha = .5
+        p = Plot(x, y, color=color).add(Bars(alpha=alpha)).plot()
+        ax = p._figure.axes[0]
+        fcs = ax.collections[0].get_facecolors()
+        C0, C1, C2, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        expected = to_rgba_array([C0, C1, C2, C0, C2], alpha)
+        assert_array_equal(fcs, expected)
+
+    def test_mapped_edgewidth(self, x, y):
+
+        p = Plot(x, y, edgewidth=y).add(Bars()).plot()
+        ax = p._figure.axes[0]
+        lws = ax.collections[0].get_linewidths()
+        assert_array_equal(np.argsort(lws), np.argsort(y))
+
+    def test_auto_edgewidth(self):
+
+        x0 = np.arange(10)
+        x1 = np.arange(1000)
+
+        p0 = Plot(x0, x0).add(Bars()).plot()
+        p1 = Plot(x1, x1).add(Bars()).plot()
+
+        lw0 = p0._figure.axes[0].collections[0].get_linewidths()
+        lw1 = p1._figure.axes[0].collections[0].get_linewidths()
+
+        assert (lw0 > lw1).all()
+
+    def test_unfilled(self, x, y):
+
+        p = Plot(x, y).add(Bars(fill=False, edgecolor="C4")).plot()
+        ax = p._figure.axes[0]
+        fcs = ax.collections[0].get_facecolors()
+        ecs = ax.collections[0].get_edgecolors()
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+        assert_array_equal(fcs, to_rgba_array([colors[0]] * len(x), 0))
+        assert_array_equal(ecs, to_rgba_array([colors[4]] * len(x), 1))
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_base.py b/testbed/mwaskom__seaborn/tests/_marks/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..70714aeef6587d90fd88e70977e7d18b047608e5
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_base.py
@@ -0,0 +1,158 @@
+from dataclasses import dataclass
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn._marks.base import Mark, Mappable, resolve_color
+
+
+class TestMappable:
+
+    def mark(self, **features):
+
+        @dataclass
+        class MockMark(Mark):
+            linewidth: float = Mappable(rc="lines.linewidth")
+            pointsize: float = Mappable(4)
+            color: str = Mappable("C0")
+            fillcolor: str = Mappable(depend="color")
+            alpha: float = Mappable(1)
+            fillalpha: float = Mappable(depend="alpha")
+
+        m = MockMark(**features)
+        return m
+
+    def test_repr(self):
+
+        assert str(Mappable(.5)) == "<0.5>"
+        assert str(Mappable("CO")) == "<'CO'>"
+        assert str(Mappable(rc="lines.linewidth")) == ""
+        assert str(Mappable(depend="color")) == ""
+        assert str(Mappable(auto=True)) == ""
+
+    def test_input_checks(self):
+
+        with pytest.raises(AssertionError):
+            Mappable(rc="bogus.parameter")
+        with pytest.raises(AssertionError):
+            Mappable(depend="nonexistent_feature")
+
+    def test_value(self):
+
+        val = 3
+        m = self.mark(linewidth=val)
+        assert m._resolve({}, "linewidth") == val
+
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+        assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val))
+
+    def test_default(self):
+
+        val = 3
+        m = self.mark(linewidth=Mappable(val))
+        assert m._resolve({}, "linewidth") == val
+
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+        assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val))
+
+    def test_rcparam(self):
+
+        param = "lines.linewidth"
+        val = mpl.rcParams[param]
+
+        m = self.mark(linewidth=Mappable(rc=param))
+        assert m._resolve({}, "linewidth") == val
+
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+        assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val))
+
+    def test_depends(self):
+
+        val = 2
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+
+        m = self.mark(pointsize=Mappable(val), linewidth=Mappable(depend="pointsize"))
+        assert m._resolve({}, "linewidth") == val
+        assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val))
+
+        m = self.mark(pointsize=val * 2, linewidth=Mappable(depend="pointsize"))
+        assert m._resolve({}, "linewidth") == val * 2
+        assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val * 2))
+
+    def test_mapped(self):
+
+        values = {"a": 1, "b": 2, "c": 3}
+
+        def f(x):
+            return np.array([values[x_i] for x_i in x])
+
+        m = self.mark(linewidth=Mappable(2))
+        scales = {"linewidth": f}
+
+        assert m._resolve({"linewidth": "c"}, "linewidth", scales) == 3
+
+        df = pd.DataFrame({"linewidth": ["a", "b", "c"]})
+        expected = np.array([1, 2, 3], float)
+        assert_array_equal(m._resolve(df, "linewidth", scales), expected)
+
+    def test_color(self):
+
+        c, a = "C1", .5
+        m = self.mark(color=c, alpha=a)
+
+        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)
+
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+        cs = [c] * len(df)
+        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))
+
+    def test_color_mapped_alpha(self):
+
+        c = "r"
+        values = {"a": .2, "b": .5, "c": .8}
+
+        m = self.mark(color=c, alpha=Mappable(1))
+        scales = {"alpha": lambda s: np.array([values[s_i] for s_i in s])}
+
+        assert resolve_color(m, {"alpha": "b"}, "", scales) == mpl.colors.to_rgba(c, .5)
+
+        df = pd.DataFrame({"alpha": list(values.keys())})
+
+        # Do this in two steps for mpl 3.2 compat
+        expected = mpl.colors.to_rgba_array([c] * len(df))
+        expected[:, 3] = list(values.values())
+
+        assert_array_equal(resolve_color(m, df, "", scales), expected)
+
+    def test_color_scaled_as_strings(self):
+
+        colors = ["C1", "dodgerblue", "#445566"]
+        m = self.mark()
+        scales = {"color": lambda s: colors}
+
+        actual = resolve_color(m, {"color": pd.Series(["a", "b", "c"])}, "", scales)
+        expected = mpl.colors.to_rgba_array(colors)
+        assert_array_equal(actual, expected)
+
+    def test_fillcolor(self):
+
+        c, a = "green", .8
+        fa = .2
+        m = self.mark(
+            color=c, alpha=a,
+            fillcolor=Mappable(depend="color"), fillalpha=Mappable(fa),
+        )
+
+        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)
+        assert resolve_color(m, {}, "fill") == mpl.colors.to_rgba(c, fa)
+
+        df = pd.DataFrame(index=pd.RangeIndex(10))
+        cs = [c] * len(df)
+        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))
+        assert_array_equal(
+            resolve_color(m, df, "fill"), mpl.colors.to_rgba_array(cs, fa)
+        )
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_dot.py b/testbed/mwaskom__seaborn/tests/_marks/test_dot.py
new file mode 100644
index 0000000000000000000000000000000000000000..49b5e8f129f7a85b6e3812e023fd2b1fa31ddac0
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_dot.py
@@ -0,0 +1,178 @@
+from matplotlib.colors import to_rgba, to_rgba_array
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn.palettes import color_palette
+from seaborn._core.plot import Plot
+from seaborn._marks.dot import Dot, Dots
+
+
+@pytest.fixture(autouse=True)
+def default_palette():
+    with color_palette("deep"):
+        yield
+
+
+class DotBase:
+
+    def check_offsets(self, points, x, y):
+
+        offsets = points.get_offsets().T
+        assert_array_equal(offsets[0], x)
+        assert_array_equal(offsets[1], y)
+
+    def check_colors(self, part, points, colors, alpha=None):
+
+        rgba = to_rgba_array(colors, alpha)
+
+        getter = getattr(points, f"get_{part}colors")
+        assert_array_equal(getter(), rgba)
+
+
+class TestDot(DotBase):
+
+    def test_simple(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        p = Plot(x=x, y=y).add(Dot()).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [C0] * 3, 1)
+        self.check_colors("edge", points, [C0] * 3, 1)
+
+    def test_filled_unfilled_mix(self):
+
+        x = [1, 2]
+        y = [4, 5]
+        marker = ["a", "b"]
+        shapes = ["o", "x"]
+
+        mark = Dot(edgecolor="w", stroke=2, edgewidth=1)
+        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [C0, to_rgba(C0, 0)], None)
+        self.check_colors("edge", points, ["w", C0], 1)
+
+        expected = [mark.edgewidth, mark.stroke]
+        assert_array_equal(points.get_linewidths(), expected)
+
+    def test_missing_coordinate_data(self):
+
+        x = [1, float("nan"), 3]
+        y = [5, 3, 4]
+
+        p = Plot(x=x, y=y).add(Dot()).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        self.check_offsets(points, [1, 3], [5, 4])
+
+    @pytest.mark.parametrize("prop", ["color", "fill", "marker", "pointsize"])
+    def test_missing_semantic_data(self, prop):
+
+        x = [1, 2, 3]
+        y = [5, 3, 4]
+        z = ["a", float("nan"), "b"]
+
+        p = Plot(x=x, y=y, **{prop: z}).add(Dot()).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        self.check_offsets(points, [1, 3], [5, 4])
+
+
+class TestDots(DotBase):
+
+    def test_simple(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        p = Plot(x=x, y=y).add(Dots()).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [C0] * 3, .2)
+        self.check_colors("edge", points, [C0] * 3, 1)
+
+    def test_set_color(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        m = Dots(color=".25")
+        p = Plot(x=x, y=y).add(m).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [m.color] * 3, .2)
+        self.check_colors("edge", points, [m.color] * 3, 1)
+
+    def test_map_color(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        c = ["a", "b", "a"]
+        p = Plot(x=x, y=y, color=c).add(Dots()).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, C1, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [C0, C1, C0], .2)
+        self.check_colors("edge", points, [C0, C1, C0], 1)
+
+    def test_fill(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        c = ["a", "b", "a"]
+        p = Plot(x=x, y=y, color=c).add(Dots(fill=False)).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, C1, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [C0, C1, C0], 0)
+        self.check_colors("edge", points, [C0, C1, C0], 1)
+
+    def test_pointsize(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        s = 3
+        p = Plot(x=x, y=y).add(Dots(pointsize=s)).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        self.check_offsets(points, x, y)
+        assert_array_equal(points.get_sizes(), [s ** 2] * 3)
+
+    def test_stroke(self):
+
+        x = [1, 2, 3]
+        y = [4, 5, 2]
+        s = 3
+        p = Plot(x=x, y=y).add(Dots(stroke=s)).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        self.check_offsets(points, x, y)
+        assert_array_equal(points.get_linewidths(), [s] * 3)
+
+    def test_filled_unfilled_mix(self):
+
+        x = [1, 2]
+        y = [4, 5]
+        marker = ["a", "b"]
+        shapes = ["o", "x"]
+
+        mark = Dots(stroke=2)
+        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()
+        ax = p._figure.axes[0]
+        points, = ax.collections
+        C0, C1, *_ = p._theme["axes.prop_cycle"].by_key()["color"]
+        self.check_offsets(points, x, y)
+        self.check_colors("face", points, [to_rgba(C0, .2), to_rgba(C0, 0)], None)
+        self.check_colors("edge", points, [C0, C0], 1)
+        assert_array_equal(points.get_linewidths(), [mark.stroke] * 2)
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_line.py b/testbed/mwaskom__seaborn/tests/_marks/test_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..1339b85945ea9ce9f3de4c6aa5e3ae3fa0ad4eb3
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_line.py
@@ -0,0 +1,411 @@
+
+import numpy as np
+import matplotlib as mpl
+from matplotlib.colors import same_color, to_rgba
+
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn._core.plot import Plot
+from seaborn._core.moves import Dodge
+from seaborn._marks.line import Dash, Line, Path, Lines, Paths, Range
+
+
+class TestPath:
+
+    def test_xy_data(self):
+
+        x = [1, 5, 3, np.nan, 2]
+        y = [1, 4, 2, 5, 3]
+        g = [1, 2, 1, 1, 2]
+        p = Plot(x=x, y=y, group=g).add(Path()).plot()
+        line1, line2 = p._figure.axes[0].get_lines()
+
+        assert_array_equal(line1.get_xdata(), [1, 3, np.nan])
+        assert_array_equal(line1.get_ydata(), [1, 2, np.nan])
+        assert_array_equal(line2.get_xdata(), [5, 2])
+        assert_array_equal(line2.get_ydata(), [4, 3])
+
+    def test_shared_colors_direct(self):
+
+        x = y = [1, 2, 3]
+        color = ".44"
+        m = Path(color=color)
+        p = Plot(x=x, y=y).add(m).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert same_color(line.get_color(), color)
+        assert same_color(line.get_markeredgecolor(), color)
+        assert same_color(line.get_markerfacecolor(), color)
+
+    def test_separate_colors_direct(self):
+
+        x = y = [1, 2, 3]
+        y = [1, 2, 3]
+        m = Path(color=".22", edgecolor=".55", fillcolor=".77")
+        p = Plot(x=x, y=y).add(m).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert same_color(line.get_color(), m.color)
+        assert same_color(line.get_markeredgecolor(), m.edgecolor)
+        assert same_color(line.get_markerfacecolor(), m.fillcolor)
+
+    def test_shared_colors_mapped(self):
+
+        x = y = [1, 2, 3, 4]
+        c = ["a", "a", "b", "b"]
+        m = Path()
+        p = Plot(x=x, y=y, color=c).add(m).plot()
+        ax = p._figure.axes[0]
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+        for i, line in enumerate(ax.get_lines()):
+            assert same_color(line.get_color(), colors[i])
+            assert same_color(line.get_markeredgecolor(), colors[i])
+            assert same_color(line.get_markerfacecolor(), colors[i])
+
+    def test_separate_colors_mapped(self):
+
+        x = y = [1, 2, 3, 4]
+        c = ["a", "a", "b", "b"]
+        d = ["x", "y", "x", "y"]
+        m = Path()
+        p = Plot(x=x, y=y, color=c, fillcolor=d).add(m).plot()
+        ax = p._figure.axes[0]
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+        for i, line in enumerate(ax.get_lines()):
+            assert same_color(line.get_color(), colors[i // 2])
+            assert same_color(line.get_markeredgecolor(), colors[i // 2])
+            assert same_color(line.get_markerfacecolor(), colors[i % 2])
+
+    def test_color_with_alpha(self):
+
+        x = y = [1, 2, 3]
+        m = Path(color=(.4, .9, .2, .5), fillcolor=(.2, .2, .3, .9))
+        p = Plot(x=x, y=y).add(m).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert same_color(line.get_color(), m.color)
+        assert same_color(line.get_markeredgecolor(), m.color)
+        assert same_color(line.get_markerfacecolor(), m.fillcolor)
+
+    def test_color_and_alpha(self):
+
+        x = y = [1, 2, 3]
+        m = Path(color=(.4, .9, .2), fillcolor=(.2, .2, .3), alpha=.5)
+        p = Plot(x=x, y=y).add(m).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert same_color(line.get_color(), to_rgba(m.color, m.alpha))
+        assert same_color(line.get_markeredgecolor(), to_rgba(m.color, m.alpha))
+        assert same_color(line.get_markerfacecolor(), to_rgba(m.fillcolor, m.alpha))
+
+    def test_other_props_direct(self):
+
+        x = y = [1, 2, 3]
+        m = Path(marker="s", linestyle="--", linewidth=3, pointsize=10, edgewidth=1)
+        p = Plot(x=x, y=y).add(m).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert line.get_marker() == m.marker
+        assert line.get_linestyle() == m.linestyle
+        assert line.get_linewidth() == m.linewidth
+        assert line.get_markersize() == m.pointsize
+        assert line.get_markeredgewidth() == m.edgewidth
+
+    def test_other_props_mapped(self):
+
+        x = y = [1, 2, 3, 4]
+        g = ["a", "a", "b", "b"]
+        m = Path()
+        p = Plot(x=x, y=y, marker=g, linestyle=g, pointsize=g).add(m).plot()
+        line1, line2 = p._figure.axes[0].get_lines()
+        assert line1.get_marker() != line2.get_marker()
+        # Matplotlib bug in storing linestyle from dash pattern
+        # assert line1.get_linestyle() != line2.get_linestyle()
+        assert line1.get_markersize() != line2.get_markersize()
+
+    def test_capstyle(self):
+
+        x = y = [1, 2]
+        rc = {"lines.solid_capstyle": "projecting", "lines.dash_capstyle": "round"}
+
+        p = Plot(x, y).add(Path()).theme(rc).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert line.get_dash_capstyle() == "projecting"
+
+        p = Plot(x, y).add(Path(linestyle="--")).theme(rc).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert line.get_dash_capstyle() == "round"
+
+        p = Plot(x, y).add(Path({"solid_capstyle": "butt"})).theme(rc).plot()
+        line, = p._figure.axes[0].get_lines()
+        assert line.get_solid_capstyle() == "butt"
+
+
+class TestLine:
+
+    # Most behaviors shared with Path and covered by above tests
+
+    def test_xy_data(self):
+
+        x = [1, 5, 3, np.nan, 2]
+        y = [1, 4, 2, 5, 3]
+        g = [1, 2, 1, 1, 2]
+        p = Plot(x=x, y=y, group=g).add(Line()).plot()
+        line1, line2 = p._figure.axes[0].get_lines()
+
+        assert_array_equal(line1.get_xdata(), [1, 3])
+        assert_array_equal(line1.get_ydata(), [1, 2])
+        assert_array_equal(line2.get_xdata(), [2, 5])
+        assert_array_equal(line2.get_ydata(), [3, 4])
+
+
+class TestPaths:
+
+    def test_xy_data(self):
+
+        x = [1, 5, 3, np.nan, 2]
+        y = [1, 4, 2, 5, 3]
+        g = [1, 2, 1, 1, 2]
+        p = Plot(x=x, y=y, group=g).add(Paths()).plot()
+        lines, = p._figure.axes[0].collections
+
+        verts = lines.get_paths()[0].vertices.T
+        assert_array_equal(verts[0], [1, 3, np.nan])
+        assert_array_equal(verts[1], [1, 2, np.nan])
+
+        verts = lines.get_paths()[1].vertices.T
+        assert_array_equal(verts[0], [5, 2])
+        assert_array_equal(verts[1], [4, 3])
+
+    def test_set_properties(self):
+
+        x = y = [1, 2, 3]
+        m = Paths(color=".737", linewidth=1, linestyle=(3, 1))
+        p = Plot(x=x, y=y).add(m).plot()
+        lines, = p._figure.axes[0].collections
+
+        assert same_color(lines.get_color().squeeze(), m.color)
+        assert lines.get_linewidth().item() == m.linewidth
+        assert lines.get_linestyle()[0] == (0, list(m.linestyle))
+
+    def test_mapped_properties(self):
+
+        x = y = [1, 2, 3, 4]
+        g = ["a", "a", "b", "b"]
+        p = Plot(x=x, y=y, color=g, linewidth=g, linestyle=g).add(Paths()).plot()
+        lines, = p._figure.axes[0].collections
+
+        assert not np.array_equal(lines.get_colors()[0], lines.get_colors()[1])
+        assert lines.get_linewidths()[0] != lines.get_linewidth()[1]
+        assert lines.get_linestyle()[0] != lines.get_linestyle()[1]
+
+    def test_color_with_alpha(self):
+
+        x = y = [1, 2, 3]
+        m = Paths(color=(.2, .6, .9, .5))
+        p = Plot(x=x, y=y).add(m).plot()
+        lines, = p._figure.axes[0].collections
+        assert same_color(lines.get_colors().squeeze(), m.color)
+
+    def test_color_and_alpha(self):
+
+        x = y = [1, 2, 3]
+        m = Paths(color=(.2, .6, .9), alpha=.5)
+        p = Plot(x=x, y=y).add(m).plot()
+        lines, = p._figure.axes[0].collections
+        assert same_color(lines.get_colors().squeeze(), to_rgba(m.color, m.alpha))
+
+    def test_capstyle(self):
+
+        x = y = [1, 2]
+        rc = {"lines.solid_capstyle": "projecting"}
+
+        with mpl.rc_context(rc):
+            p = Plot(x, y).add(Paths()).plot()
+            lines = p._figure.axes[0].collections[0]
+            assert lines.get_capstyle() == "projecting"
+
+            p = Plot(x, y).add(Paths(linestyle="--")).plot()
+            lines = p._figure.axes[0].collections[0]
+            assert lines.get_capstyle() == "projecting"
+
+            p = Plot(x, y).add(Paths({"capstyle": "butt"})).plot()
+            lines = p._figure.axes[0].collections[0]
+            assert lines.get_capstyle() == "butt"
+
+
+class TestLines:
+
+    def test_xy_data(self):
+
+        x = [1, 5, 3, np.nan, 2]
+        y = [1, 4, 2, 5, 3]
+        g = [1, 2, 1, 1, 2]
+        p = Plot(x=x, y=y, group=g).add(Lines()).plot()
+        lines, = p._figure.axes[0].collections
+
+        verts = lines.get_paths()[0].vertices.T
+        assert_array_equal(verts[0], [1, 3])
+        assert_array_equal(verts[1], [1, 2])
+
+        verts = lines.get_paths()[1].vertices.T
+        assert_array_equal(verts[0], [2, 5])
+        assert_array_equal(verts[1], [3, 4])
+
+    def test_single_orient_value(self):
+
+        x = [1, 1, 1]
+        y = [1, 2, 3]
+        p = Plot(x, y).add(Lines()).plot()
+        lines, = p._figure.axes[0].collections
+        verts = lines.get_paths()[0].vertices.T
+        assert_array_equal(verts[0], x)
+        assert_array_equal(verts[1], y)
+
+
+class TestRange:
+
+    def test_xy_data(self):
+
+        x = [1, 2]
+        ymin = [1, 4]
+        ymax = [2, 3]
+
+        p = Plot(x=x, ymin=ymin, ymax=ymax).add(Range()).plot()
+        lines, = p._figure.axes[0].collections
+
+        for i, path in enumerate(lines.get_paths()):
+            verts = path.vertices.T
+            assert_array_equal(verts[0], [x[i], x[i]])
+            assert_array_equal(verts[1], [ymin[i], ymax[i]])
+
+    def test_auto_range(self):
+
+        x = [1, 1, 2, 2, 2]
+        y = [1, 2, 3, 4, 5]
+
+        p = Plot(x=x, y=y).add(Range()).plot()
+        lines, = p._figure.axes[0].collections
+        paths = lines.get_paths()
+        assert_array_equal(paths[0].vertices, [(1, 1), (1, 2)])
+        assert_array_equal(paths[1].vertices, [(2, 3), (2, 5)])
+
+    def test_mapped_color(self):
+
+        x = [1, 2, 1, 2]
+        ymin = [1, 4, 3, 2]
+        ymax = [2, 3, 1, 4]
+        group = ["a", "a", "b", "b"]
+
+        p = Plot(x=x, ymin=ymin, ymax=ymax, color=group).add(Range()).plot()
+        lines, = p._figure.axes[0].collections
+        colors = p._theme["axes.prop_cycle"].by_key()["color"]
+
+        for i, path in enumerate(lines.get_paths()):
+            verts = path.vertices.T
+            assert_array_equal(verts[0], [x[i], x[i]])
+            assert_array_equal(verts[1], [ymin[i], ymax[i]])
+            assert same_color(lines.get_colors()[i], colors[i // 2])
+
+    def test_direct_properties(self):
+
+        x = [1, 2]
+        ymin = [1, 4]
+        ymax = [2, 3]
+
+        m = Range(color=".654", linewidth=4)
+        p = Plot(x=x, ymin=ymin, ymax=ymax).add(m).plot()
+        lines, = p._figure.axes[0].collections
+
+        for i, path in enumerate(lines.get_paths()):
+            assert same_color(lines.get_colors()[i], m.color)
+            assert lines.get_linewidths()[i] == m.linewidth
+
+
+class TestDash:
+
+    def test_xy_data(self):
+
+        x = [0, 0, 1, 2]
+        y = [1, 2, 3, 4]
+
+        p = Plot(x=x, y=y).add(Dash()).plot()
+        lines, = p._figure.axes[0].collections
+
+        for i, path in enumerate(lines.get_paths()):
+            verts = path.vertices.T
+            assert_array_almost_equal(verts[0], [x[i] - .4, x[i] + .4])
+            assert_array_equal(verts[1], [y[i], y[i]])
+
+    def test_xy_data_grouped(self):
+
+        x = [0, 0, 1, 2]
+        y = [1, 2, 3, 4]
+        color = ["a", "b", "a", "b"]
+
+        p = Plot(x=x, y=y, color=color).add(Dash()).plot()
+        lines, = p._figure.axes[0].collections
+
+        idx = [0, 2, 1, 3]
+        for i, path in zip(idx, lines.get_paths()):
+            verts = path.vertices.T
+            assert_array_almost_equal(verts[0], [x[i] - .4, x[i] + .4])
+            assert_array_equal(verts[1], [y[i], y[i]])
+
+    def test_set_properties(self):
+
+        x = [0, 0, 1, 2]
+        y = [1, 2, 3, 4]
+
+        m = Dash(color=".8", linewidth=4)
+        p = Plot(x=x, y=y).add(m).plot()
+        lines, = p._figure.axes[0].collections
+
+        for color in lines.get_color():
+            assert same_color(color, m.color)
+        for linewidth in lines.get_linewidth():
+            assert linewidth == m.linewidth
+
+    def test_mapped_properties(self):
+
+        x = [0, 1]
+        y = [1, 2]
+        color = ["a", "b"]
+        linewidth = [1, 2]
+
+        p = Plot(x=x, y=y, color=color, linewidth=linewidth).add(Dash()).plot()
+        lines, = p._figure.axes[0].collections
+        palette = p._theme["axes.prop_cycle"].by_key()["color"]
+
+        for color, line_color in zip(palette, lines.get_color()):
+            assert same_color(color, line_color)
+
+        linewidths = lines.get_linewidths()
+        assert linewidths[1] > linewidths[0]
+
+    def test_width(self):
+
+        x = [0, 0, 1, 2]
+        y = [1, 2, 3, 4]
+
+        p = Plot(x=x, y=y).add(Dash(width=.4)).plot()
+        lines, = p._figure.axes[0].collections
+
+        for i, path in enumerate(lines.get_paths()):
+            verts = path.vertices.T
+            assert_array_almost_equal(verts[0], [x[i] - .2, x[i] + .2])
+            assert_array_equal(verts[1], [y[i], y[i]])
+
+    def test_dodge(self):
+
+        x = [0, 1]
+        y = [1, 2]
+        group = ["a", "b"]
+
+        p = Plot(x=x, y=y, group=group).add(Dash(), Dodge()).plot()
+        lines, = p._figure.axes[0].collections
+
+        paths = lines.get_paths()
+
+        v0 = paths[0].vertices.T
+        assert_array_almost_equal(v0[0], [-.4, 0])
+        assert_array_equal(v0[1], [y[0], y[0]])
+
+        v1 = paths[1].vertices.T
+        assert_array_almost_equal(v1[0], [1, 1.4])
+        assert_array_equal(v1[1], [y[1], y[1]])
diff --git a/testbed/mwaskom__seaborn/tests/_marks/test_text.py b/testbed/mwaskom__seaborn/tests/_marks/test_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..241b1742e0f624e5732fd87c5d1ccf95b8f868f4
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_marks/test_text.py
@@ -0,0 +1,129 @@
+
+import numpy as np
+from matplotlib.colors import to_rgba
+from matplotlib.text import Text as MPLText
+
+from numpy.testing import assert_array_almost_equal
+
+from seaborn._core.plot import Plot
+from seaborn._marks.text import Text
+
+
+class TestText:
+
+    def get_texts(self, ax):
+        if ax.texts:
+            return list(ax.texts)
+        else:
+            # Compatibility with matplotlib < 3.5 (I think)
+            return [a for a in ax.artists if isinstance(a, MPLText)]
+
+    def test_simple(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+
+        p = Plot(x, y, text=s).add(Text()).plot()
+        ax = p._figure.axes[0]
+        for i, text in enumerate(self.get_texts(ax)):
+            x_, y_ = text.get_position()
+            assert x_ == x[i]
+            assert y_ == y[i]
+            assert text.get_text() == s[i]
+            assert text.get_horizontalalignment() == "center"
+            assert text.get_verticalalignment() == "center_baseline"
+
+    def test_set_properties(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        color = "red"
+        alpha = .6
+        fontsize = 6
+        valign = "bottom"
+
+        m = Text(color=color, alpha=alpha, fontsize=fontsize, valign=valign)
+        p = Plot(x, y, text=s).add(m).plot()
+        ax = p._figure.axes[0]
+        for i, text in enumerate(self.get_texts(ax)):
+            assert text.get_text() == s[i]
+            assert text.get_color() == to_rgba(m.color, m.alpha)
+            assert text.get_fontsize() == m.fontsize
+            assert text.get_verticalalignment() == m.valign
+
+    def test_mapped_properties(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        color = list("aab")
+        fontsize = [1, 2, 4]
+
+        p = Plot(x, y, color=color, fontsize=fontsize, text=s).add(Text()).plot()
+        ax = p._figure.axes[0]
+        texts = self.get_texts(ax)
+        assert texts[0].get_color() == texts[1].get_color()
+        assert texts[0].get_color() != texts[2].get_color()
+        assert (
+            texts[0].get_fontsize()
+            < texts[1].get_fontsize()
+            < texts[2].get_fontsize()
+        )
+
+    def test_mapped_alignment(self):
+
+        x = [1, 2]
+        p = Plot(x=x, y=x, halign=x, valign=x, text=x).add(Text()).plot()
+        ax = p._figure.axes[0]
+        t1, t2 = self.get_texts(ax)
+        assert t1.get_horizontalalignment() == "left"
+        assert t2.get_horizontalalignment() == "right"
+        assert t1.get_verticalalignment() == "top"
+        assert t2.get_verticalalignment() == "bottom"
+
+    def test_identity_fontsize(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        fs = [5, 8, 12]
+        p = Plot(x, y, text=s, fontsize=fs).add(Text()).scale(fontsize=None).plot()
+        ax = p._figure.axes[0]
+        for i, text in enumerate(self.get_texts(ax)):
+            assert text.get_fontsize() == fs[i]
+
+    def test_offset_centered(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        p = Plot(x, y, text=s).add(Text()).plot()
+        ax = p._figure.axes[0]
+        ax_trans = ax.transData.get_matrix()
+        for text in self.get_texts(ax):
+            assert_array_almost_equal(text.get_transform().get_matrix(), ax_trans)
+
+    def test_offset_valign(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        m = Text(valign="bottom", fontsize=5, offset=.1)
+        p = Plot(x, y, text=s).add(m).plot()
+        ax = p._figure.axes[0]
+        expected_shift_matrix = np.zeros((3, 3))
+        expected_shift_matrix[1, -1] = m.offset * ax.figure.dpi / 72
+        ax_trans = ax.transData.get_matrix()
+        for text in self.get_texts(ax):
+            shift_matrix = text.get_transform().get_matrix() - ax_trans
+            assert_array_almost_equal(shift_matrix, expected_shift_matrix)
+
+    def test_offset_halign(self):
+
+        x = y = [1, 2, 3]
+        s = list("abc")
+        m = Text(halign="right", fontsize=10, offset=.5)
+        p = Plot(x, y, text=s).add(m).plot()
+        ax = p._figure.axes[0]
+        expected_shift_matrix = np.zeros((3, 3))
+        expected_shift_matrix[0, -1] = -m.offset * ax.figure.dpi / 72
+        ax_trans = ax.transData.get_matrix()
+        for text in self.get_texts(ax):
+            shift_matrix = text.get_transform().get_matrix() - ax_trans
+            assert_array_almost_equal(shift_matrix, expected_shift_matrix)
diff --git a/testbed/mwaskom__seaborn/tests/_stats/__init__.py b/testbed/mwaskom__seaborn/tests/_stats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/mwaskom__seaborn/tests/_stats/test_aggregation.py b/testbed/mwaskom__seaborn/tests/_stats/test_aggregation.py
new file mode 100644
index 0000000000000000000000000000000000000000..08291d449b708c123db6a11565d8cf7fba624716
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_stats/test_aggregation.py
@@ -0,0 +1,125 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+from pandas.testing import assert_frame_equal
+
+from seaborn._core.groupby import GroupBy
+from seaborn._stats.aggregation import Agg, Est
+
+
+class AggregationFixtures:
+
+    @pytest.fixture
+    def df(self, rng):
+
+        n = 30
+        return pd.DataFrame(dict(
+            x=rng.uniform(0, 7, n).round(),
+            y=rng.normal(size=n),
+            color=rng.choice(["a", "b", "c"], n),
+            group=rng.choice(["x", "y"], n),
+        ))
+
+    def get_groupby(self, df, orient):
+
+        other = {"x": "y", "y": "x"}[orient]
+        cols = [c for c in df if c != other]
+        return GroupBy(cols)
+
+
+class TestAgg(AggregationFixtures):
+
+    def test_default(self, df):
+
+        ori = "x"
+        df = df[["x", "y"]]
+        gb = self.get_groupby(df, ori)
+        res = Agg()(df, gb, ori, {})
+
+        expected = df.groupby("x", as_index=False)["y"].mean()
+        assert_frame_equal(res, expected)
+
+    def test_default_multi(self, df):
+
+        ori = "x"
+        gb = self.get_groupby(df, ori)
+        res = Agg()(df, gb, ori, {})
+
+        grp = ["x", "color", "group"]
+        index = pd.MultiIndex.from_product(
+            [sorted(df["x"].unique()), df["color"].unique(), df["group"].unique()],
+            names=["x", "color", "group"]
+        )
+        expected = (
+            df
+            .groupby(grp)
+            .agg("mean")
+            .reindex(index=index)
+            .dropna()
+            .reset_index()
+            .reindex(columns=df.columns)
+        )
+        assert_frame_equal(res, expected)
+
+    @pytest.mark.parametrize("func", ["max", lambda x: float(len(x) % 2)])
+    def test_func(self, df, func):
+
+        ori = "x"
+        df = df[["x", "y"]]
+        gb = self.get_groupby(df, ori)
+        res = Agg(func)(df, gb, ori, {})
+
+        expected = df.groupby("x", as_index=False)["y"].agg(func)
+        assert_frame_equal(res, expected)
+
+
+class TestEst(AggregationFixtures):
+
+    # Note: Most of the underlying code is exercised in tests/test_statistics
+
+    @pytest.mark.parametrize("func", [np.mean, "mean"])
+    def test_mean_sd(self, df, func):
+
+        ori = "x"
+        df = df[["x", "y"]]
+        gb = self.get_groupby(df, ori)
+        res = Est(func, "sd")(df, gb, ori, {})
+
+        grouped = df.groupby("x", as_index=False)["y"]
+        est = grouped.mean()
+        err = grouped.std().fillna(0)  # fillna needed only on pinned tests
+        expected = est.assign(ymin=est["y"] - err["y"], ymax=est["y"] + err["y"])
+        assert_frame_equal(res, expected)
+
+    def test_sd_single_obs(self):
+
+        y = 1.5
+        ori = "x"
+        df = pd.DataFrame([{"x": "a", "y": y}])
+        gb = self.get_groupby(df, ori)
+        res = Est("mean", "sd")(df, gb, ori, {})
+        expected = df.assign(ymin=y, ymax=y)
+        assert_frame_equal(res, expected)
+
+    def test_median_pi(self, df):
+
+        ori = "x"
+        df = df[["x", "y"]]
+        gb = self.get_groupby(df, ori)
+        res = Est("median", ("pi", 100))(df, gb, ori, {})
+
+        grouped = df.groupby("x", as_index=False)["y"]
+        est = grouped.median()
+        expected = est.assign(ymin=grouped.min()["y"], ymax=grouped.max()["y"])
+        assert_frame_equal(res, expected)
+
+    def test_seed(self, df):
+
+        ori = "x"
+        gb = self.get_groupby(df, ori)
+        args = df, gb, ori, {}
+        res1 = Est("mean", "ci", seed=99)(*args)
+        res2 = Est("mean", "ci", seed=99)(*args)
+        assert_frame_equal(res1, res2)
diff --git a/testbed/mwaskom__seaborn/tests/_stats/test_counting.py b/testbed/mwaskom__seaborn/tests/_stats/test_counting.py
new file mode 100644
index 0000000000000000000000000000000000000000..7656654492aa5ce56d47cbe9cf923376ed714643
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_stats/test_counting.py
@@ -0,0 +1,262 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn._core.groupby import GroupBy
+from seaborn._stats.counting import Hist, Count
+
+
+class TestCount:
+
+    @pytest.fixture
+    def df(self, rng):
+
+        n = 30
+        return pd.DataFrame(dict(
+            x=rng.uniform(0, 7, n).round(),
+            y=rng.normal(size=n),
+            color=rng.choice(["a", "b", "c"], n),
+            group=rng.choice(["x", "y"], n),
+        ))
+
+    def get_groupby(self, df, orient):
+
+        other = {"x": "y", "y": "x"}[orient]
+        cols = [c for c in df if c != other]
+        return GroupBy(cols)
+
+    def test_single_grouper(self, df):
+
+        ori = "x"
+        df = df[["x"]]
+        gb = self.get_groupby(df, ori)
+        res = Count()(df, gb, ori, {})
+        expected = df.groupby("x").size()
+        assert_array_equal(res.sort_values("x")["y"], expected)
+
+    def test_multiple_groupers(self, df):
+
+        ori = "x"
+        df = df[["x", "group"]].sort_values("group")
+        gb = self.get_groupby(df, ori)
+        res = Count()(df, gb, ori, {})
+        expected = df.groupby(["x", "group"]).size()
+        assert_array_equal(res.sort_values(["x", "group"])["y"], expected)
+
+
+class TestHist:
+
+    @pytest.fixture
+    def single_args(self):
+
+        groupby = GroupBy(["group"])
+
+        class Scale:
+            scale_type = "continuous"
+
+        return groupby, "x", {"x": Scale()}
+
+    @pytest.fixture
+    def triple_args(self):
+
+        groupby = GroupBy(["group", "a", "s"])
+
+        class Scale:
+            scale_type = "continuous"
+
+        return groupby, "x", {"x": Scale()}
+
+    def test_string_bins(self, long_df):
+
+        h = Hist(bins="sqrt")
+        bin_kws = h._define_bin_params(long_df, "x", "continuous")
+        assert bin_kws["range"] == (long_df["x"].min(), long_df["x"].max())
+        assert bin_kws["bins"] == int(np.sqrt(len(long_df)))
+
+    def test_int_bins(self, long_df):
+
+        n = 24
+        h = Hist(bins=n)
+        bin_kws = h._define_bin_params(long_df, "x", "continuous")
+        assert bin_kws["range"] == (long_df["x"].min(), long_df["x"].max())
+        assert bin_kws["bins"] == n
+
+    def test_array_bins(self, long_df):
+
+        bins = [-3, -2, 1, 2, 3]
+        h = Hist(bins=bins)
+        bin_kws = h._define_bin_params(long_df, "x", "continuous")
+        assert_array_equal(bin_kws["bins"], bins)
+
+    def test_binwidth(self, long_df):
+
+        binwidth = .5
+        h = Hist(binwidth=binwidth)
+        bin_kws = h._define_bin_params(long_df, "x", "continuous")
+        n_bins = bin_kws["bins"]
+        left, right = bin_kws["range"]
+        assert (right - left) / n_bins == pytest.approx(binwidth)
+
+    def test_binrange(self, long_df):
+
+        binrange = (-4, 4)
+        h = Hist(binrange=binrange)
+        bin_kws = h._define_bin_params(long_df, "x", "continuous")
+        assert bin_kws["range"] == binrange
+
+    def test_discrete_bins(self, long_df):
+
+        h = Hist(discrete=True)
+        x = long_df["x"].astype(int)
+        bin_kws = h._define_bin_params(long_df.assign(x=x), "x", "continuous")
+        assert bin_kws["range"] == (x.min() - .5, x.max() + .5)
+        assert bin_kws["bins"] == (x.max() - x.min() + 1)
+
+    def test_discrete_bins_from_nominal_scale(self, rng):
+
+        h = Hist()
+        x = rng.randint(0, 5, 10)
+        df = pd.DataFrame({"x": x})
+        bin_kws = h._define_bin_params(df, "x", "nominal")
+        assert bin_kws["range"] == (x.min() - .5, x.max() + .5)
+        assert bin_kws["bins"] == (x.max() - x.min() + 1)
+
+    def test_count_stat(self, long_df, single_args):
+
+        h = Hist(stat="count")
+        out = h(long_df, *single_args)
+        assert out["y"].sum() == len(long_df)
+
+    def test_probability_stat(self, long_df, single_args):
+
+        h = Hist(stat="probability")
+        out = h(long_df, *single_args)
+        assert out["y"].sum() == 1
+
+    def test_proportion_stat(self, long_df, single_args):
+
+        h = Hist(stat="proportion")
+        out = h(long_df, *single_args)
+        assert out["y"].sum() == 1
+
+    def test_percent_stat(self, long_df, single_args):
+
+        h = Hist(stat="percent")
+        out = h(long_df, *single_args)
+        assert out["y"].sum() == 100
+
+    def test_density_stat(self, long_df, single_args):
+
+        h = Hist(stat="density")
+        out = h(long_df, *single_args)
+        assert (out["y"] * out["space"]).sum() == 1
+
+    def test_frequency_stat(self, long_df, single_args):
+
+        h = Hist(stat="frequency")
+        out = h(long_df, *single_args)
+        assert (out["y"] * out["space"]).sum() == len(long_df)
+
+    def test_invalid_stat(self):
+
+        with pytest.raises(ValueError, match="The `stat` parameter for `Hist`"):
+            Hist(stat="invalid")
+
+    def test_cumulative_count(self, long_df, single_args):
+
+        h = Hist(stat="count", cumulative=True)
+        out = h(long_df, *single_args)
+        assert out["y"].max() == len(long_df)
+
+    def test_cumulative_proportion(self, long_df, single_args):
+
+        h = Hist(stat="proportion", cumulative=True)
+        out = h(long_df, *single_args)
+        assert out["y"].max() == 1
+
+    def test_cumulative_density(self, long_df, single_args):
+
+        h = Hist(stat="density", cumulative=True)
+        out = h(long_df, *single_args)
+        assert out["y"].max() == 1
+
+    def test_common_norm_default(self, long_df, triple_args):
+
+        h = Hist(stat="percent")
+        out = h(long_df, *triple_args)
+        assert out["y"].sum() == pytest.approx(100)
+
+    def test_common_norm_false(self, long_df, triple_args):
+
+        h = Hist(stat="percent", common_norm=False)
+        out = h(long_df, *triple_args)
+        for _, out_part in out.groupby(["a", "s"]):
+            assert out_part["y"].sum() == pytest.approx(100)
+
+    def test_common_norm_subset(self, long_df, triple_args):
+
+        h = Hist(stat="percent", common_norm=["a"])
+        out = h(long_df, *triple_args)
+        for _, out_part in out.groupby("a"):
+            assert out_part["y"].sum() == pytest.approx(100)
+
+    def test_common_norm_warning(self, long_df, triple_args):
+
+        h = Hist(common_norm=["b"])
+        with pytest.warns(UserWarning, match=r"Undefined variable\(s\)"):
+            h(long_df, *triple_args)
+
+    def test_common_bins_default(self, long_df, triple_args):
+
+        h = Hist()
+        out = h(long_df, *triple_args)
+        bins = []
+        for _, out_part in out.groupby(["a", "s"]):
+            bins.append(tuple(out_part["x"]))
+        assert len(set(bins)) == 1
+
+    def test_common_bins_false(self, long_df, triple_args):
+
+        h = Hist(common_bins=False)
+        out = h(long_df, *triple_args)
+        bins = []
+        for _, out_part in out.groupby(["a", "s"]):
+            bins.append(tuple(out_part["x"]))
+        assert len(set(bins)) == len(out.groupby(["a", "s"]))
+
+    def test_common_bins_subset(self, long_df, triple_args):
+
+        h = Hist(common_bins=False)
+        out = h(long_df, *triple_args)
+        bins = []
+        for _, out_part in out.groupby("a"):
+            bins.append(tuple(out_part["x"]))
+        assert len(set(bins)) == out["a"].nunique()
+
+    def test_common_bins_warning(self, long_df, triple_args):
+
+        h = Hist(common_bins=["b"])
+        with pytest.warns(UserWarning, match=r"Undefined variable\(s\)"):
+            h(long_df, *triple_args)
+
+    def test_histogram_single(self, long_df, single_args):
+
+        h = Hist()
+        out = h(long_df, *single_args)
+        hist, edges = np.histogram(long_df["x"], bins="auto")
+        assert_array_equal(out["y"], hist)
+        assert_array_equal(out["space"], np.diff(edges))
+
+    def test_histogram_multiple(self, long_df, triple_args):
+
+        h = Hist()
+        out = h(long_df, *triple_args)
+        bins = np.histogram_bin_edges(long_df["x"], "auto")
+        for (a, s), out_part in out.groupby(["a", "s"]):
+            x = long_df.loc[(long_df["a"] == a) & (long_df["s"] == s), "x"]
+            hist, edges = np.histogram(x, bins=bins)
+            assert_array_equal(out_part["y"], hist)
+            assert_array_equal(out_part["space"], np.diff(edges))
diff --git a/testbed/mwaskom__seaborn/tests/_stats/test_density.py b/testbed/mwaskom__seaborn/tests/_stats/test_density.py
new file mode 100644
index 0000000000000000000000000000000000000000..ead182acdf07984592d877e1ac2beef3f80703aa
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_stats/test_density.py
@@ -0,0 +1,202 @@
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn._core.groupby import GroupBy
+from seaborn._stats.density import KDE, _no_scipy
+
+
+class TestKDE:
+
+    @pytest.fixture
+    def df(self, rng):
+
+        n = 100
+        return pd.DataFrame(dict(
+            x=rng.uniform(0, 7, n).round(),
+            y=rng.normal(size=n),
+            color=rng.choice(["a", "b", "c"], n),
+            alpha=rng.choice(["x", "y"], n),
+        ))
+
+    def get_groupby(self, df, orient):
+
+        cols = [c for c in df if c != orient]
+        return GroupBy([*cols, "group"])
+
+    def integrate(self, y, x):
+        y = np.asarray(y)
+        x = np.asarray(x)
+        dx = np.diff(x)
+        return (dx * y[:-1] + dx * y[1:]).sum() / 2
+
+    @pytest.mark.parametrize("ori", ["x", "y"])
+    def test_columns(self, df, ori):
+
+        df = df[[ori, "alpha"]]
+        gb = self.get_groupby(df, ori)
+        res = KDE()(df, gb, ori, {})
+        other = {"x": "y", "y": "x"}[ori]
+        expected = [ori, "alpha", "density", other]
+        assert list(res.columns) == expected
+
+    @pytest.mark.parametrize("gridsize", [20, 30, None])
+    def test_gridsize(self, df, gridsize):
+
+        ori = "y"
+        df = df[[ori]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(gridsize=gridsize)(df, gb, ori, {})
+        if gridsize is None:
+            assert_array_equal(res[ori], df[ori])
+        else:
+            assert len(res) == gridsize
+
+    @pytest.mark.parametrize("cut", [1, 2])
+    def test_cut(self, df, cut):
+
+        ori = "y"
+        df = df[[ori]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(cut=cut, bw_method=1)(df, gb, ori, {})
+
+        vals = df[ori]
+        bw = vals.std()
+        assert res[ori].min() == pytest.approx(vals.min() - bw * cut, abs=1e-2)
+        assert res[ori].max() == pytest.approx(vals.max() + bw * cut, abs=1e-2)
+
+    @pytest.mark.parametrize("common_grid", [True, False])
+    def test_common_grid(self, df, common_grid):
+
+        ori = "y"
+        df = df[[ori, "alpha"]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(common_grid=common_grid)(df, gb, ori, {})
+
+        vals = df["alpha"].unique()
+        a = res.loc[res["alpha"] == vals[0], ori].to_numpy()
+        b = res.loc[res["alpha"] == vals[1], ori].to_numpy()
+        if common_grid:
+            assert_array_equal(a, b)
+        else:
+            assert np.not_equal(a, b).all()
+
+    @pytest.mark.parametrize("common_norm", [True, False])
+    def test_common_norm(self, df, common_norm):
+
+        ori = "y"
+        df = df[[ori, "alpha"]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(common_norm=common_norm)(df, gb, ori, {})
+
+        areas = (
+            res.groupby("alpha")
+            .apply(lambda x: self.integrate(x["density"], x[ori]))
+        )
+
+        if common_norm:
+            assert areas.sum() == pytest.approx(1, abs=1e-3)
+        else:
+            assert_array_almost_equal(areas, [1, 1], decimal=3)
+
+    def test_common_norm_variables(self, df):
+
+        ori = "y"
+        df = df[[ori, "alpha", "color"]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(common_norm=["alpha"])(df, gb, ori, {})
+
+        def integrate_by_color_and_sum(x):
+            return (
+                x.groupby("color")
+                .apply(lambda y: self.integrate(y["density"], y[ori]))
+                .sum()
+            )
+
+        areas = res.groupby("alpha").apply(integrate_by_color_and_sum)
+        assert_array_almost_equal(areas, [1, 1], decimal=3)
+
+    @pytest.mark.parametrize("param", ["norm", "grid"])
+    def test_common_input_checks(self, df, param):
+
+        ori = "y"
+        df = df[[ori, "alpha"]]
+        gb = self.get_groupby(df, ori)
+        msg = rf"Undefined variable\(s\) passed for KDE.common_{param}"
+        with pytest.warns(UserWarning, match=msg):
+            KDE(**{f"common_{param}": ["color", "alpha"]})(df, gb, ori, {})
+
+        msg = f"KDE.common_{param} must be a boolean or list of strings"
+        with pytest.raises(TypeError, match=msg):
+            KDE(**{f"common_{param}": "alpha"})(df, gb, ori, {})
+
+    def test_bw_adjust(self, df):
+
+        ori = "y"
+        df = df[[ori]]
+        gb = self.get_groupby(df, ori)
+        res1 = KDE(bw_adjust=0.5)(df, gb, ori, {})
+        res2 = KDE(bw_adjust=2.0)(df, gb, ori, {})
+
+        mad1 = res1["density"].diff().abs().mean()
+        mad2 = res2["density"].diff().abs().mean()
+        assert mad1 > mad2
+
+    def test_bw_method_scalar(self, df):
+
+        ori = "y"
+        df = df[[ori]]
+        gb = self.get_groupby(df, ori)
+        res1 = KDE(bw_method=0.5)(df, gb, ori, {})
+        res2 = KDE(bw_method=2.0)(df, gb, ori, {})
+
+        mad1 = res1["density"].diff().abs().mean()
+        mad2 = res2["density"].diff().abs().mean()
+        assert mad1 > mad2
+
+    @pytest.mark.skipif(_no_scipy, reason="KDE.cumulative requires scipy")
+    @pytest.mark.parametrize("common_norm", [True, False])
+    def test_cumulative(self, df, common_norm):
+
+        ori = "y"
+        df = df[[ori, "alpha"]]
+        gb = self.get_groupby(df, ori)
+        res = KDE(cumulative=True, common_norm=common_norm)(df, gb, ori, {})
+
+        for _, group_res in res.groupby("alpha"):
+            assert (group_res["density"].diff().dropna() >= 0).all()
+            if not common_norm:
+                assert group_res["density"].max() == pytest.approx(1, abs=1e-3)
+
+    def test_cumulative_requires_scipy(self):
+
+        if _no_scipy:
+            err = "Cumulative KDE evaluation requires scipy"
+            with pytest.raises(RuntimeError, match=err):
+                KDE(cumulative=True)
+
+    @pytest.mark.parametrize("vals", [[], [1], [1] * 5, [1929245168.06679] * 18])
+    def test_singular(self, df, vals):
+
+        df1 = pd.DataFrame({"y": vals, "alpha": ["z"] * len(vals)})
+        gb = self.get_groupby(df1, "y")
+        res = KDE()(df1, gb, "y", {})
+        assert res.empty
+
+        df2 = pd.concat([df[["y", "alpha"]], df1], ignore_index=True)
+        gb = self.get_groupby(df2, "y")
+        res = KDE()(df2, gb, "y", {})
+        assert set(res["alpha"]) == set(df["alpha"])
+
+    @pytest.mark.parametrize("col", ["y", "weight"])
+    def test_missing(self, df, col):
+
+        val, ori = "xy"
+        df["weight"] = 1
+        df = df[[ori, "weight"]]
+        df.loc[:4, col] = np.nan
+        gb = self.get_groupby(df, ori)
+        res = KDE()(df, gb, ori, {})
+        assert self.integrate(res[val], res[ori]) == pytest.approx(1, abs=1e-3)
diff --git a/testbed/mwaskom__seaborn/tests/_stats/test_order.py b/testbed/mwaskom__seaborn/tests/_stats/test_order.py
new file mode 100644
index 0000000000000000000000000000000000000000..7376e8a154f2acafcb719fc22f37d2ddcd73677e
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_stats/test_order.py
@@ -0,0 +1,87 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn._core.groupby import GroupBy
+from seaborn._stats.order import Perc
+from seaborn.utils import _version_predates
+
+
+class Fixtures:
+
+    @pytest.fixture
+    def df(self, rng):
+        return pd.DataFrame(dict(x="", y=rng.normal(size=30)))
+
+    def get_groupby(self, df, orient):
+        # TODO note, copied from aggregation
+        other = {"x": "y", "y": "x"}[orient]
+        cols = [c for c in df if c != other]
+        return GroupBy(cols)
+
+
+class TestPerc(Fixtures):
+
+    def test_int_k(self, df):
+
+        ori = "x"
+        gb = self.get_groupby(df, ori)
+        res = Perc(3)(df, gb, ori, {})
+        percentiles = [0, 50, 100]
+        assert_array_equal(res["percentile"], percentiles)
+        assert_array_equal(res["y"], np.percentile(df["y"], percentiles))
+
+    def test_list_k(self, df):
+
+        ori = "x"
+        gb = self.get_groupby(df, ori)
+        percentiles = [0, 20, 100]
+        res = Perc(k=percentiles)(df, gb, ori, {})
+        assert_array_equal(res["percentile"], percentiles)
+        assert_array_equal(res["y"], np.percentile(df["y"], percentiles))
+
+    def test_orientation(self, df):
+
+        df = df.rename(columns={"x": "y", "y": "x"})
+        ori = "y"
+        gb = self.get_groupby(df, ori)
+        res = Perc(k=3)(df, gb, ori, {})
+        assert_array_equal(res["x"], np.percentile(df["x"], [0, 50, 100]))
+
+    def test_method(self, df):
+
+        ori = "x"
+        gb = self.get_groupby(df, ori)
+        method = "nearest"
+        res = Perc(k=5, method=method)(df, gb, ori, {})
+        percentiles = [0, 25, 50, 75, 100]
+        if _version_predates(np, "1.22.0"):
+            expected = np.percentile(df["y"], percentiles, interpolation=method)
+        else:
+            expected = np.percentile(df["y"], percentiles, method=method)
+        assert_array_equal(res["y"], expected)
+
+    def test_grouped(self, df, rng):
+
+        ori = "x"
+        df = df.assign(x=rng.choice(["a", "b", "c"], len(df)))
+        gb = self.get_groupby(df, ori)
+        k = [10, 90]
+        res = Perc(k)(df, gb, ori, {})
+        for x, res_x in res.groupby("x"):
+            assert_array_equal(res_x["percentile"], k)
+            expected = np.percentile(df.loc[df["x"] == x, "y"], k)
+            assert_array_equal(res_x["y"], expected)
+
+    def test_with_na(self, df):
+
+        ori = "x"
+        df.loc[:5, "y"] = np.nan
+        gb = self.get_groupby(df, ori)
+        k = [10, 90]
+        res = Perc(k)(df, gb, ori, {})
+        expected = np.percentile(df["y"].dropna(), k)
+        assert_array_equal(res["y"], expected)
diff --git a/testbed/mwaskom__seaborn/tests/_stats/test_regression.py b/testbed/mwaskom__seaborn/tests/_stats/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..16807fd7c03f45cdb2c810239283f6212ddd5dd0
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/_stats/test_regression.py
@@ -0,0 +1,61 @@
+
+import numpy as np
+import pandas as pd
+
+import pytest
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+from pandas.testing import assert_frame_equal
+
+from seaborn._core.groupby import GroupBy
+from seaborn._stats.regression import PolyFit
+
+
+class TestPolyFit:
+
+    @pytest.fixture
+    def df(self, rng):
+
+        n = 100
+        return pd.DataFrame(dict(
+            x=rng.normal(0, 1, n),
+            y=rng.normal(0, 1, n),
+            color=rng.choice(["a", "b", "c"], n),
+            group=rng.choice(["x", "y"], n),
+        ))
+
+    def test_no_grouper(self, df):
+
+        groupby = GroupBy(["group"])
+        res = PolyFit(order=1, gridsize=100)(df[["x", "y"]], groupby, "x", {})
+
+        assert_array_equal(res.columns, ["x", "y"])
+
+        grid = np.linspace(df["x"].min(), df["x"].max(), 100)
+        assert_array_equal(res["x"], grid)
+        assert_array_almost_equal(
+            res["y"].diff().diff().dropna(), np.zeros(grid.size - 2)
+        )
+
+    def test_one_grouper(self, df):
+
+        groupby = GroupBy(["group"])
+        gridsize = 50
+        res = PolyFit(gridsize=gridsize)(df, groupby, "x", {})
+
+        assert res.columns.to_list() == ["x", "y", "group"]
+
+        ngroups = df["group"].nunique()
+        assert_array_equal(res.index, np.arange(ngroups * gridsize))
+
+        for _, part in res.groupby("group"):
+            grid = np.linspace(part["x"].min(), part["x"].max(), gridsize)
+            assert_array_equal(part["x"], grid)
+            assert part["y"].diff().diff().dropna().abs().gt(0).all()
+
+    def test_missing_data(self, df):
+
+        groupby = GroupBy(["group"])
+        df.iloc[5:10] = np.nan
+        res1 = PolyFit()(df[["x", "y"]], groupby, "x", {})
+        res2 = PolyFit()(df[["x", "y"]].dropna(), groupby, "x", {})
+        assert_frame_equal(res1, res2)
\ No newline at end of file
diff --git a/testbed/mwaskom__seaborn/tests/conftest.py b/testbed/mwaskom__seaborn/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..0366d1643ef8b278994a082968248e256a1da27a
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/conftest.py
@@ -0,0 +1,180 @@
+import numpy as np
+import pandas as pd
+
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def close_figs():
+    yield
+    import matplotlib.pyplot as plt
+    plt.close("all")
+
+
+@pytest.fixture(autouse=True)
+def random_seed():
+    seed = sum(map(ord, "seaborn random global"))
+    np.random.seed(seed)
+
+
+@pytest.fixture()
+def rng():
+    seed = sum(map(ord, "seaborn random object"))
+    return np.random.RandomState(seed)
+
+
+@pytest.fixture
+def wide_df(rng):
+
+    columns = list("abc")
+    index = pd.RangeIndex(10, 50, 2, name="wide_index")
+    values = rng.normal(size=(len(index), len(columns)))
+    return pd.DataFrame(values, index=index, columns=columns)
+
+
+@pytest.fixture
+def wide_array(wide_df):
+
+    return wide_df.to_numpy()
+
+
+# TODO s/flat/thin?
+@pytest.fixture
+def flat_series(rng):
+
+    index = pd.RangeIndex(10, 30, name="t")
+    return pd.Series(rng.normal(size=20), index, name="s")
+
+
+@pytest.fixture
+def flat_array(flat_series):
+
+    return flat_series.to_numpy()
+
+
+@pytest.fixture
+def flat_list(flat_series):
+
+    return flat_series.to_list()
+
+
+@pytest.fixture(params=["series", "array", "list"])
+def flat_data(rng, request):
+
+    index = pd.RangeIndex(10, 30, name="t")
+    series = pd.Series(rng.normal(size=20), index, name="s")
+    if request.param == "series":
+        data = series
+    elif request.param == "array":
+        data = series.to_numpy()
+    elif request.param == "list":
+        data = series.to_list()
+    return data
+
+
+@pytest.fixture
+def wide_list_of_series(rng):
+
+    return [pd.Series(rng.normal(size=20), np.arange(20), name="a"),
+            pd.Series(rng.normal(size=10), np.arange(5, 15), name="b")]
+
+
+@pytest.fixture
+def wide_list_of_arrays(wide_list_of_series):
+
+    return [s.to_numpy() for s in wide_list_of_series]
+
+
+@pytest.fixture
+def wide_list_of_lists(wide_list_of_series):
+
+    return [s.to_list() for s in wide_list_of_series]
+
+
+@pytest.fixture
+def wide_dict_of_series(wide_list_of_series):
+
+    return {s.name: s for s in wide_list_of_series}
+
+
+@pytest.fixture
+def wide_dict_of_arrays(wide_list_of_series):
+
+    return {s.name: s.to_numpy() for s in wide_list_of_series}
+
+
+@pytest.fixture
+def wide_dict_of_lists(wide_list_of_series):
+
+    return {s.name: s.to_list() for s in wide_list_of_series}
+
+
+@pytest.fixture
+def long_df(rng):
+
+    n = 100
+    df = pd.DataFrame(dict(
+        x=rng.uniform(0, 20, n).round().astype("int"),
+        y=rng.normal(size=n),
+        z=rng.lognormal(size=n),
+        a=rng.choice(list("abc"), n),
+        b=rng.choice(list("mnop"), n),
+        c=rng.choice([0, 1], n, [.3, .7]),
+        d=rng.choice(np.arange("2004-07-30", "2007-07-30", dtype="datetime64[Y]"), n),
+        t=rng.choice(np.arange("2004-07-30", "2004-07-31", dtype="datetime64[m]"), n),
+        s=rng.choice([2, 4, 8], n),
+        f=rng.choice([0.2, 0.3], n),
+    ))
+
+    a_cat = df["a"].astype("category")
+    new_categories = np.roll(a_cat.cat.categories, 1)
+    df["a_cat"] = a_cat.cat.reorder_categories(new_categories)
+
+    df["s_cat"] = df["s"].astype("category")
+    df["s_str"] = df["s"].astype(str)
+
+    return df
+
+
+@pytest.fixture
+def long_dict(long_df):
+
+    return long_df.to_dict()
+
+
+@pytest.fixture
+def repeated_df(rng):
+
+    n = 100
+    return pd.DataFrame(dict(
+        x=np.tile(np.arange(n // 2), 2),
+        y=rng.normal(size=n),
+        a=rng.choice(list("abc"), n),
+        u=np.repeat(np.arange(2), n // 2),
+    ))
+
+
+@pytest.fixture
+def missing_df(rng, long_df):
+
+    df = long_df.copy()
+    for col in df:
+        idx = rng.permutation(df.index)[:10]
+        df.loc[idx, col] = np.nan
+    return df
+
+
+@pytest.fixture
+def object_df(rng, long_df):
+
+    df = long_df.copy()
+    # objectify numeric columns
+    for col in ["c", "s", "f"]:
+        df[col] = df[col].astype(object)
+    return df
+
+
+@pytest.fixture
+def null_series(flat_series):
+
+    return pd.Series(index=flat_series.index, dtype='float64')
diff --git a/testbed/mwaskom__seaborn/tests/test_algorithms.py b/testbed/mwaskom__seaborn/tests/test_algorithms.py
new file mode 100644
index 0000000000000000000000000000000000000000..81cdcdb76a13900e639be51b8f2a738525f65cb3
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_algorithms.py
@@ -0,0 +1,172 @@
+import numpy as np
+
+import pytest
+from numpy.testing import assert_array_equal
+
+from seaborn import algorithms as algo
+
+
+@pytest.fixture
+def random():
+    np.random.seed(sum(map(ord, "test_algorithms")))
+
+
+def test_bootstrap(random):
+    """Test that bootstrapping gives the right answer in dumb cases."""
+    a_ones = np.ones(10)
+    n_boot = 5
+    out1 = algo.bootstrap(a_ones, n_boot=n_boot)
+    assert_array_equal(out1, np.ones(n_boot))
+    out2 = algo.bootstrap(a_ones, n_boot=n_boot, func=np.median)
+    assert_array_equal(out2, np.ones(n_boot))
+
+
+def test_bootstrap_length(random):
+    """Test that we get a bootstrap array of the right shape."""
+    a_norm = np.random.randn(1000)
+    out = algo.bootstrap(a_norm)
+    assert len(out) == 10000
+
+    n_boot = 100
+    out = algo.bootstrap(a_norm, n_boot=n_boot)
+    assert len(out) == n_boot
+
+
+def test_bootstrap_range(random):
+    """Test that bootstrapping a random array stays within the right range."""
+    a_norm = np.random.randn(1000)
+    amin, amax = a_norm.min(), a_norm.max()
+    out = algo.bootstrap(a_norm)
+    assert amin <= out.min()
+    assert amax >= out.max()
+
+
+def test_bootstrap_multiarg(random):
+    """Test that bootstrap works with multiple input arrays."""
+    x = np.vstack([[1, 10] for i in range(10)])
+    y = np.vstack([[5, 5] for i in range(10)])
+
+    def f(x, y):
+        return np.vstack((x, y)).max(axis=0)
+
+    out_actual = algo.bootstrap(x, y, n_boot=2, func=f)
+    out_wanted = np.array([[5, 10], [5, 10]])
+    assert_array_equal(out_actual, out_wanted)
+
+
+def test_bootstrap_axis(random):
+    """Test axis kwarg to bootstrap function."""
+    x = np.random.randn(10, 20)
+    n_boot = 100
+
+    out_default = algo.bootstrap(x, n_boot=n_boot)
+    assert out_default.shape == (n_boot,)
+
+    out_axis = algo.bootstrap(x, n_boot=n_boot, axis=0)
+    assert out_axis.shape, (n_boot, x.shape[1])
+
+
+def test_bootstrap_seed(random):
+    """Test that we can get reproducible resamples by seeding the RNG."""
+    data = np.random.randn(50)
+    seed = 42
+    boots1 = algo.bootstrap(data, seed=seed)
+    boots2 = algo.bootstrap(data, seed=seed)
+    assert_array_equal(boots1, boots2)
+
+
+def test_bootstrap_ols(random):
+    """Test bootstrap of OLS model fit."""
+    def ols_fit(X, y):
+        XtXinv = np.linalg.inv(np.dot(X.T, X))
+        return XtXinv.dot(X.T).dot(y)
+
+    X = np.column_stack((np.random.randn(50, 4), np.ones(50)))
+    w = [2, 4, 0, 3, 5]
+    y_noisy = np.dot(X, w) + np.random.randn(50) * 20
+    y_lownoise = np.dot(X, w) + np.random.randn(50)
+
+    n_boot = 500
+    w_boot_noisy = algo.bootstrap(X, y_noisy,
+                                  n_boot=n_boot,
+                                  func=ols_fit)
+    w_boot_lownoise = algo.bootstrap(X, y_lownoise,
+                                     n_boot=n_boot,
+                                     func=ols_fit)
+
+    assert w_boot_noisy.shape == (n_boot, 5)
+    assert w_boot_lownoise.shape == (n_boot, 5)
+    assert w_boot_noisy.std() > w_boot_lownoise.std()
+
+
+def test_bootstrap_units(random):
+    """Test that results make sense when passing unit IDs to bootstrap."""
+    data = np.random.randn(50)
+    ids = np.repeat(range(10), 5)
+    bwerr = np.random.normal(0, 2, 10)
+    bwerr = bwerr[ids]
+    data_rm = data + bwerr
+    seed = 77
+
+    boots_orig = algo.bootstrap(data_rm, seed=seed)
+    boots_rm = algo.bootstrap(data_rm, units=ids, seed=seed)
+    assert boots_rm.std() > boots_orig.std()
+
+
+def test_bootstrap_arglength():
+    """Test that different length args raise ValueError."""
+    with pytest.raises(ValueError):
+        algo.bootstrap(np.arange(5), np.arange(10))
+
+
+def test_bootstrap_string_func():
+    """Test that named numpy methods are the same as the numpy function."""
+    x = np.random.randn(100)
+
+    res_a = algo.bootstrap(x, func="mean", seed=0)
+    res_b = algo.bootstrap(x, func=np.mean, seed=0)
+    assert np.array_equal(res_a, res_b)
+
+    res_a = algo.bootstrap(x, func="std", seed=0)
+    res_b = algo.bootstrap(x, func=np.std, seed=0)
+    assert np.array_equal(res_a, res_b)
+
+    with pytest.raises(AttributeError):
+        algo.bootstrap(x, func="not_a_method_name")
+
+
+def test_bootstrap_reproducibility(random):
+    """Test that bootstrapping uses the internal random state."""
+    data = np.random.randn(50)
+    boots1 = algo.bootstrap(data, seed=100)
+    boots2 = algo.bootstrap(data, seed=100)
+    assert_array_equal(boots1, boots2)
+
+    random_state1 = np.random.RandomState(200)
+    boots1 = algo.bootstrap(data, seed=random_state1)
+    random_state2 = np.random.RandomState(200)
+    boots2 = algo.bootstrap(data, seed=random_state2)
+    assert_array_equal(boots1, boots2)
+
+    with pytest.warns(UserWarning):
+        # Deprecated, remove when removing random_seed
+        boots1 = algo.bootstrap(data, random_seed=100)
+        boots2 = algo.bootstrap(data, random_seed=100)
+        assert_array_equal(boots1, boots2)
+
+
+def test_nanaware_func_auto(random):
+
+    x = np.random.normal(size=10)
+    x[0] = np.nan
+    boots = algo.bootstrap(x, func="mean")
+    assert not np.isnan(boots).any()
+
+
+def test_nanaware_func_warning(random):
+
+    x = np.random.normal(size=10)
+    x[0] = np.nan
+    with pytest.warns(UserWarning, match="Data contain nans but"):
+        boots = algo.bootstrap(x, func="ptp")
+    assert np.isnan(boots).any()
diff --git a/testbed/mwaskom__seaborn/tests/test_axisgrid.py b/testbed/mwaskom__seaborn/tests/test_axisgrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..af8bf19da825c01bfc877994caf0499b3493fb09
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_axisgrid.py
@@ -0,0 +1,1847 @@
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+
+import pytest
+import numpy.testing as npt
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+try:
+    import pandas.testing as tm
+except ImportError:
+    import pandas.util.testing as tm
+
+from seaborn._oldcore import categorical_order
+from seaborn import rcmod
+from seaborn.palettes import color_palette
+from seaborn.relational import scatterplot
+from seaborn.distributions import histplot, kdeplot, distplot
+from seaborn.categorical import pointplot
+from seaborn import axisgrid as ag
+from seaborn._testing import (
+    assert_plots_equal,
+    assert_colors_equal,
+)
+
+rs = np.random.RandomState(0)
+
+
+class TestFacetGrid:
+
+    df = pd.DataFrame(dict(x=rs.normal(size=60),
+                           y=rs.gamma(4, size=60),
+                           a=np.repeat(list("abc"), 20),
+                           b=np.tile(list("mn"), 30),
+                           c=np.tile(list("tuv"), 20),
+                           d=np.tile(list("abcdefghijkl"), 5)))
+
+    def test_self_data(self):
+
+        g = ag.FacetGrid(self.df)
+        assert g.data is self.df
+
+    def test_self_figure(self):
+
+        g = ag.FacetGrid(self.df)
+        assert isinstance(g.figure, plt.Figure)
+        assert g.figure is g._figure
+
+    def test_self_axes(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c")
+        for ax in g.axes.flat:
+            assert isinstance(ax, plt.Axes)
+
+    def test_axes_array_size(self):
+
+        g = ag.FacetGrid(self.df)
+        assert g.axes.shape == (1, 1)
+
+        g = ag.FacetGrid(self.df, row="a")
+        assert g.axes.shape == (3, 1)
+
+        g = ag.FacetGrid(self.df, col="b")
+        assert g.axes.shape == (1, 2)
+
+        g = ag.FacetGrid(self.df, hue="c")
+        assert g.axes.shape == (1, 1)
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c")
+        assert g.axes.shape == (3, 2)
+        for ax in g.axes.flat:
+            assert isinstance(ax, plt.Axes)
+
+    def test_single_axes(self):
+
+        g = ag.FacetGrid(self.df)
+        assert isinstance(g.ax, plt.Axes)
+
+        g = ag.FacetGrid(self.df, row="a")
+        with pytest.raises(AttributeError):
+            g.ax
+
+        g = ag.FacetGrid(self.df, col="a")
+        with pytest.raises(AttributeError):
+            g.ax
+
+        g = ag.FacetGrid(self.df, col="a", row="b")
+        with pytest.raises(AttributeError):
+            g.ax
+
+    def test_col_wrap(self):
+
+        n = len(self.df.d.unique())
+
+        g = ag.FacetGrid(self.df, col="d")
+        assert g.axes.shape == (1, n)
+        assert g.facet_axis(0, 8) is g.axes[0, 8]
+
+        g_wrap = ag.FacetGrid(self.df, col="d", col_wrap=4)
+        assert g_wrap.axes.shape == (n,)
+        assert g_wrap.facet_axis(0, 8) is g_wrap.axes[8]
+        assert g_wrap._ncol == 4
+        assert g_wrap._nrow == (n / 4)
+
+        with pytest.raises(ValueError):
+            g = ag.FacetGrid(self.df, row="b", col="d", col_wrap=4)
+
+        df = self.df.copy()
+        df.loc[df.d == "j"] = np.nan
+        g_missing = ag.FacetGrid(df, col="d")
+        assert g_missing.axes.shape == (1, n - 1)
+
+        g_missing_wrap = ag.FacetGrid(df, col="d", col_wrap=4)
+        assert g_missing_wrap.axes.shape == (n - 1,)
+
+        g = ag.FacetGrid(self.df, col="d", col_wrap=1)
+        assert len(list(g.facet_data())) == n
+
+    def test_normal_axes(self):
+
+        null = np.empty(0, object).flat
+
+        g = ag.FacetGrid(self.df)
+        npt.assert_array_equal(g._bottom_axes, g.axes.flat)
+        npt.assert_array_equal(g._not_bottom_axes, null)
+        npt.assert_array_equal(g._left_axes, g.axes.flat)
+        npt.assert_array_equal(g._not_left_axes, null)
+        npt.assert_array_equal(g._inner_axes, null)
+
+        g = ag.FacetGrid(self.df, col="c")
+        npt.assert_array_equal(g._bottom_axes, g.axes.flat)
+        npt.assert_array_equal(g._not_bottom_axes, null)
+        npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)
+        npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)
+        npt.assert_array_equal(g._inner_axes, null)
+
+        g = ag.FacetGrid(self.df, row="c")
+        npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)
+        npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)
+        npt.assert_array_equal(g._left_axes, g.axes.flat)
+        npt.assert_array_equal(g._not_left_axes, null)
+        npt.assert_array_equal(g._inner_axes, null)
+
+        g = ag.FacetGrid(self.df, col="a", row="c")
+        npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)
+        npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)
+        npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)
+        npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)
+        npt.assert_array_equal(g._inner_axes, g.axes[:-1, 1:].flat)
+
+    def test_wrapped_axes(self):
+
+        null = np.empty(0, object).flat
+
+        g = ag.FacetGrid(self.df, col="a", col_wrap=2)
+        npt.assert_array_equal(g._bottom_axes,
+                               g.axes[np.array([1, 2])].flat)
+        npt.assert_array_equal(g._not_bottom_axes, g.axes[:1].flat)
+        npt.assert_array_equal(g._left_axes, g.axes[np.array([0, 2])].flat)
+        npt.assert_array_equal(g._not_left_axes, g.axes[np.array([1])].flat)
+        npt.assert_array_equal(g._inner_axes, null)
+
+    def test_axes_dict(self):
+
+        g = ag.FacetGrid(self.df)
+        assert isinstance(g.axes_dict, dict)
+        assert not g.axes_dict
+
+        g = ag.FacetGrid(self.df, row="c")
+        assert list(g.axes_dict.keys()) == g.row_names
+        for (name, ax) in zip(g.row_names, g.axes.flat):
+            assert g.axes_dict[name] is ax
+
+        g = ag.FacetGrid(self.df, col="c")
+        assert list(g.axes_dict.keys()) == g.col_names
+        for (name, ax) in zip(g.col_names, g.axes.flat):
+            assert g.axes_dict[name] is ax
+
+        g = ag.FacetGrid(self.df, col="a", col_wrap=2)
+        assert list(g.axes_dict.keys()) == g.col_names
+        for (name, ax) in zip(g.col_names, g.axes.flat):
+            assert g.axes_dict[name] is ax
+
+        g = ag.FacetGrid(self.df, row="a", col="c")
+        for (row_var, col_var), ax in g.axes_dict.items():
+            i = g.row_names.index(row_var)
+            j = g.col_names.index(col_var)
+            assert g.axes[i, j] is ax
+
+    def test_figure_size(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        npt.assert_array_equal(g.figure.get_size_inches(), (6, 9))
+
+        g = ag.FacetGrid(self.df, row="a", col="b", height=6)
+        npt.assert_array_equal(g.figure.get_size_inches(), (12, 18))
+
+        g = ag.FacetGrid(self.df, col="c", height=4, aspect=.5)
+        npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))
+
+    def test_figure_size_with_legend(self):
+
+        g = ag.FacetGrid(self.df, col="a", hue="c", height=4, aspect=.5)
+        npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))
+        g.add_legend()
+        assert g.figure.get_size_inches()[0] > 6
+
+        g = ag.FacetGrid(self.df, col="a", hue="c", height=4, aspect=.5,
+                         legend_out=False)
+        npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))
+        g.add_legend()
+        npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))
+
+    def test_legend_data(self):
+
+        g = ag.FacetGrid(self.df, hue="a")
+        g.map(plt.plot, "x", "y")
+        g.add_legend()
+        palette = color_palette(n_colors=3)
+
+        assert g._legend.get_title().get_text() == "a"
+
+        a_levels = sorted(self.df.a.unique())
+
+        lines = g._legend.get_lines()
+        assert len(lines) == len(a_levels)
+
+        for line, hue in zip(lines, palette):
+            assert_colors_equal(line.get_color(), hue)
+
+        labels = g._legend.get_texts()
+        assert len(labels) == len(a_levels)
+
+        for label, level in zip(labels, a_levels):
+            assert label.get_text() == level
+
+    def test_legend_data_missing_level(self):
+
+        g = ag.FacetGrid(self.df, hue="a", hue_order=list("azbc"))
+        g.map(plt.plot, "x", "y")
+        g.add_legend()
+
+        c1, c2, c3, c4 = color_palette(n_colors=4)
+        palette = [c1, c3, c4]
+
+        assert g._legend.get_title().get_text() == "a"
+
+        a_levels = sorted(self.df.a.unique())
+
+        lines = g._legend.get_lines()
+        assert len(lines) == len(a_levels)
+
+        for line, hue in zip(lines, palette):
+            assert_colors_equal(line.get_color(), hue)
+
+        labels = g._legend.get_texts()
+        assert len(labels) == 4
+
+        for label, level in zip(labels, list("azbc")):
+            assert label.get_text() == level
+
+    def test_get_boolean_legend_data(self):
+
+        self.df["b_bool"] = self.df.b == "m"
+        g = ag.FacetGrid(self.df, hue="b_bool")
+        g.map(plt.plot, "x", "y")
+        g.add_legend()
+        palette = color_palette(n_colors=2)
+
+        assert g._legend.get_title().get_text() == "b_bool"
+
+        b_levels = list(map(str, categorical_order(self.df.b_bool)))
+
+        lines = g._legend.get_lines()
+        assert len(lines) == len(b_levels)
+
+        for line, hue in zip(lines, palette):
+            assert_colors_equal(line.get_color(), hue)
+
+        labels = g._legend.get_texts()
+        assert len(labels) == len(b_levels)
+
+        for label, level in zip(labels, b_levels):
+            assert label.get_text() == level
+
+    def test_legend_tuples(self):
+
+        g = ag.FacetGrid(self.df, hue="a")
+        g.map(plt.plot, "x", "y")
+
+        handles, labels = g.ax.get_legend_handles_labels()
+        label_tuples = [("", l) for l in labels]
+        legend_data = dict(zip(label_tuples, handles))
+        g.add_legend(legend_data, label_tuples)
+        for entry, label in zip(g._legend.get_texts(), labels):
+            assert entry.get_text() == label
+
+    def test_legend_options(self):
+
+        g = ag.FacetGrid(self.df, hue="b")
+        g.map(plt.plot, "x", "y")
+        g.add_legend()
+
+        g1 = ag.FacetGrid(self.df, hue="b", legend_out=False)
+        g1.add_legend(adjust_subtitles=True)
+
+        g1 = ag.FacetGrid(self.df, hue="b", legend_out=False)
+        g1.add_legend(adjust_subtitles=False)
+
+    def test_legendout_with_colwrap(self):
+
+        g = ag.FacetGrid(self.df, col="d", hue='b',
+                         col_wrap=4, legend_out=False)
+        g.map(plt.plot, "x", "y", linewidth=3)
+        g.add_legend()
+
+    def test_legend_tight_layout(self):
+
+        g = ag.FacetGrid(self.df, hue='b')
+        g.map(plt.plot, "x", "y", linewidth=3)
+        g.add_legend()
+        g.tight_layout()
+
+        axes_right_edge = g.ax.get_window_extent().xmax
+        legend_left_edge = g._legend.get_window_extent().xmin
+
+        assert axes_right_edge < legend_left_edge
+
+    def test_subplot_kws(self):
+
+        g = ag.FacetGrid(self.df, despine=False,
+                         subplot_kws=dict(projection="polar"))
+        for ax in g.axes.flat:
+            assert "PolarAxesSubplot" in str(type(ax))
+
+    def test_gridspec_kws(self):
+        ratios = [3, 1, 2]
+
+        gskws = dict(width_ratios=ratios)
+        g = ag.FacetGrid(self.df, col='c', row='a', gridspec_kws=gskws)
+
+        for ax in g.axes.flat:
+            ax.set_xticks([])
+            ax.set_yticks([])
+
+        g.figure.tight_layout()
+
+        for (l, m, r) in g.axes:
+            assert l.get_position().width > m.get_position().width
+            assert r.get_position().width > m.get_position().width
+
+    def test_gridspec_kws_col_wrap(self):
+        ratios = [3, 1, 2, 1, 1]
+
+        gskws = dict(width_ratios=ratios)
+        with pytest.warns(UserWarning):
+            ag.FacetGrid(self.df, col='d', col_wrap=5, gridspec_kws=gskws)
+
+    def test_data_generator(self):
+
+        g = ag.FacetGrid(self.df, row="a")
+        d = list(g.facet_data())
+        assert len(d) == 3
+
+        tup, data = d[0]
+        assert tup == (0, 0, 0)
+        assert (data["a"] == "a").all()
+
+        tup, data = d[1]
+        assert tup == (1, 0, 0)
+        assert (data["a"] == "b").all()
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        d = list(g.facet_data())
+        assert len(d) == 6
+
+        tup, data = d[0]
+        assert tup == (0, 0, 0)
+        assert (data["a"] == "a").all()
+        assert (data["b"] == "m").all()
+
+        tup, data = d[1]
+        assert tup == (0, 1, 0)
+        assert (data["a"] == "a").all()
+        assert (data["b"] == "n").all()
+
+        tup, data = d[2]
+        assert tup == (1, 0, 0)
+        assert (data["a"] == "b").all()
+        assert (data["b"] == "m").all()
+
+        g = ag.FacetGrid(self.df, hue="c")
+        d = list(g.facet_data())
+        assert len(d) == 3
+        tup, data = d[1]
+        assert tup == (0, 0, 1)
+        assert (data["c"] == "u").all()
+
+    def test_map(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c")
+        g.map(plt.plot, "x", "y", linewidth=3)
+
+        lines = g.axes[0, 0].lines
+        assert len(lines) == 3
+
+        line1, _, _ = lines
+        assert line1.get_linewidth() == 3
+        x, y = line1.get_data()
+        mask = (self.df.a == "a") & (self.df.b == "m") & (self.df.c == "t")
+        npt.assert_array_equal(x, self.df.x[mask])
+        npt.assert_array_equal(y, self.df.y[mask])
+
+    def test_map_dataframe(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c")
+
+        def plot(x, y, data=None, **kws):
+            plt.plot(data[x], data[y], **kws)
+        # Modify __module__ so this doesn't look like a seaborn function
+        plot.__module__ = "test"
+
+        g.map_dataframe(plot, "x", "y", linestyle="--")
+
+        lines = g.axes[0, 0].lines
+        assert len(g.axes[0, 0].lines) == 3
+
+        line1, _, _ = lines
+        assert line1.get_linestyle() == "--"
+        x, y = line1.get_data()
+        mask = (self.df.a == "a") & (self.df.b == "m") & (self.df.c == "t")
+        npt.assert_array_equal(x, self.df.x[mask])
+        npt.assert_array_equal(y, self.df.y[mask])
+
+    def test_set(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        xlim = (-2, 5)
+        ylim = (3, 6)
+        xticks = [-2, 0, 3, 5]
+        yticks = [3, 4.5, 6]
+        g.set(xlim=xlim, ylim=ylim, xticks=xticks, yticks=yticks)
+        for ax in g.axes.flat:
+            npt.assert_array_equal(ax.get_xlim(), xlim)
+            npt.assert_array_equal(ax.get_ylim(), ylim)
+            npt.assert_array_equal(ax.get_xticks(), xticks)
+            npt.assert_array_equal(ax.get_yticks(), yticks)
+
+    def test_set_titles(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        g.map(plt.plot, "x", "y")
+
+        # Test the default titles
+        assert g.axes[0, 0].get_title() == "a = a | b = m"
+        assert g.axes[0, 1].get_title() == "a = a | b = n"
+        assert g.axes[1, 0].get_title() == "a = b | b = m"
+
+        # Test a provided title
+        g.set_titles("{row_var} == {row_name} \\/ {col_var} == {col_name}")
+        assert g.axes[0, 0].get_title() == "a == a \\/ b == m"
+        assert g.axes[0, 1].get_title() == "a == a \\/ b == n"
+        assert g.axes[1, 0].get_title() == "a == b \\/ b == m"
+
+        # Test a single row
+        g = ag.FacetGrid(self.df, col="b")
+        g.map(plt.plot, "x", "y")
+
+        # Test the default titles
+        assert g.axes[0, 0].get_title() == "b = m"
+        assert g.axes[0, 1].get_title() == "b = n"
+
+        # test with dropna=False
+        g = ag.FacetGrid(self.df, col="b", hue="b", dropna=False)
+        g.map(plt.plot, 'x', 'y')
+
+    def test_set_titles_margin_titles(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", margin_titles=True)
+        g.map(plt.plot, "x", "y")
+
+        # Test the default titles
+        assert g.axes[0, 0].get_title() == "b = m"
+        assert g.axes[0, 1].get_title() == "b = n"
+        assert g.axes[1, 0].get_title() == ""
+
+        # Test the row "titles"
+        assert g.axes[0, 1].texts[0].get_text() == "a = a"
+        assert g.axes[1, 1].texts[0].get_text() == "a = b"
+        assert g.axes[0, 1].texts[0] is g._margin_titles_texts[0]
+
+        # Test provided titles
+        g.set_titles(col_template="{col_name}", row_template="{row_name}")
+        assert g.axes[0, 0].get_title() == "m"
+        assert g.axes[0, 1].get_title() == "n"
+        assert g.axes[1, 0].get_title() == ""
+
+        assert len(g.axes[1, 1].texts) == 1
+        assert g.axes[1, 1].texts[0].get_text() == "b"
+
+    def test_set_ticklabels(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        g.map(plt.plot, "x", "y")
+
+        ax = g.axes[-1, 0]
+        xlab = [l.get_text() + "h" for l in ax.get_xticklabels()]
+        ylab = [l.get_text() + "i" for l in ax.get_yticklabels()]
+
+        g.set_xticklabels(xlab)
+        g.set_yticklabels(ylab)
+        got_x = [l.get_text() for l in g.axes[-1, 1].get_xticklabels()]
+        got_y = [l.get_text() for l in g.axes[0, 0].get_yticklabels()]
+        npt.assert_array_equal(got_x, xlab)
+        npt.assert_array_equal(got_y, ylab)
+
+        x, y = np.arange(10), np.arange(10)
+        df = pd.DataFrame(np.c_[x, y], columns=["x", "y"])
+        g = ag.FacetGrid(df).map_dataframe(pointplot, x="x", y="y", order=x)
+        g.set_xticklabels(step=2)
+        got_x = [int(l.get_text()) for l in g.axes[0, 0].get_xticklabels()]
+        npt.assert_array_equal(x[::2], got_x)
+
+        g = ag.FacetGrid(self.df, col="d", col_wrap=5)
+        g.map(plt.plot, "x", "y")
+        g.set_xticklabels(rotation=45)
+        g.set_yticklabels(rotation=75)
+        for ax in g._bottom_axes:
+            for l in ax.get_xticklabels():
+                assert l.get_rotation() == 45
+        for ax in g._left_axes:
+            for l in ax.get_yticklabels():
+                assert l.get_rotation() == 75
+
+    def test_set_axis_labels(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        g.map(plt.plot, "x", "y")
+        xlab = 'xx'
+        ylab = 'yy'
+
+        g.set_axis_labels(xlab, ylab)
+
+        got_x = [ax.get_xlabel() for ax in g.axes[-1, :]]
+        got_y = [ax.get_ylabel() for ax in g.axes[:, 0]]
+        npt.assert_array_equal(got_x, xlab)
+        npt.assert_array_equal(got_y, ylab)
+
+        for ax in g.axes.flat:
+            ax.set(xlabel="x", ylabel="y")
+
+        g.set_axis_labels(xlab, ylab)
+        for ax in g._not_bottom_axes:
+            assert not ax.get_xlabel()
+        for ax in g._not_left_axes:
+            assert not ax.get_ylabel()
+
+    def test_axis_lims(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", xlim=(0, 4), ylim=(-2, 3))
+        assert g.axes[0, 0].get_xlim() == (0, 4)
+        assert g.axes[0, 0].get_ylim() == (-2, 3)
+
+    def test_data_orders(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c")
+
+        assert g.row_names == list("abc")
+        assert g.col_names == list("mn")
+        assert g.hue_names == list("tuv")
+        assert g.axes.shape == (3, 2)
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c",
+                         row_order=list("bca"),
+                         col_order=list("nm"),
+                         hue_order=list("vtu"))
+
+        assert g.row_names == list("bca")
+        assert g.col_names == list("nm")
+        assert g.hue_names == list("vtu")
+        assert g.axes.shape == (3, 2)
+
+        g = ag.FacetGrid(self.df, row="a", col="b", hue="c",
+                         row_order=list("bcda"),
+                         col_order=list("nom"),
+                         hue_order=list("qvtu"))
+
+        assert g.row_names == list("bcda")
+        assert g.col_names == list("nom")
+        assert g.hue_names == list("qvtu")
+        assert g.axes.shape == (4, 3)
+
+    def test_palette(self):
+
+        rcmod.set()
+
+        g = ag.FacetGrid(self.df, hue="c")
+        assert g._colors == color_palette(n_colors=len(self.df.c.unique()))
+
+        g = ag.FacetGrid(self.df, hue="d")
+        assert g._colors == color_palette("husl", len(self.df.d.unique()))
+
+        g = ag.FacetGrid(self.df, hue="c", palette="Set2")
+        assert g._colors == color_palette("Set2", len(self.df.c.unique()))
+
+        dict_pal = dict(t="red", u="green", v="blue")
+        list_pal = color_palette(["red", "green", "blue"], 3)
+        g = ag.FacetGrid(self.df, hue="c", palette=dict_pal)
+        assert g._colors == list_pal
+
+        list_pal = color_palette(["green", "blue", "red"], 3)
+        g = ag.FacetGrid(self.df, hue="c", hue_order=list("uvt"),
+                         palette=dict_pal)
+        assert g._colors == list_pal
+
+    def test_hue_kws(self):
+
+        kws = dict(marker=["o", "s", "D"])
+        g = ag.FacetGrid(self.df, hue="c", hue_kws=kws)
+        g.map(plt.plot, "x", "y")
+
+        for line, marker in zip(g.axes[0, 0].lines, kws["marker"]):
+            assert line.get_marker() == marker
+
+    def test_dropna(self):
+
+        df = self.df.copy()
+        hasna = pd.Series(np.tile(np.arange(6), 10), dtype=float)
+        hasna[hasna == 5] = np.nan
+        df["hasna"] = hasna
+        g = ag.FacetGrid(df, dropna=False, row="hasna")
+        assert g._not_na.sum() == 60
+
+        g = ag.FacetGrid(df, dropna=True, row="hasna")
+        assert g._not_na.sum() == 50
+
+    def test_categorical_column_missing_categories(self):
+
+        df = self.df.copy()
+        df['a'] = df['a'].astype('category')
+
+        g = ag.FacetGrid(df[df['a'] == 'a'], col="a", col_wrap=1)
+
+        assert g.axes.shape == (len(df['a'].cat.categories),)
+
+    def test_categorical_warning(self):
+
+        g = ag.FacetGrid(self.df, col="b")
+        with pytest.warns(UserWarning):
+            g.map(pointplot, "b", "x")
+
+    def test_refline(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        g.refline()
+        for ax in g.axes.flat:
+            assert not ax.lines
+
+        refx = refy = 0.5
+        hline = np.array([[0, refy], [1, refy]])
+        vline = np.array([[refx, 0], [refx, 1]])
+        g.refline(x=refx, y=refy)
+        for ax in g.axes.flat:
+            assert ax.lines[0].get_color() == '.5'
+            assert ax.lines[0].get_linestyle() == '--'
+            assert len(ax.lines) == 2
+            npt.assert_array_equal(ax.lines[0].get_xydata(), vline)
+            npt.assert_array_equal(ax.lines[1].get_xydata(), hline)
+
+        color, linestyle = 'red', '-'
+        g.refline(x=refx, color=color, linestyle=linestyle)
+        npt.assert_array_equal(g.axes[0, 0].lines[-1].get_xydata(), vline)
+        assert g.axes[0, 0].lines[-1].get_color() == color
+        assert g.axes[0, 0].lines[-1].get_linestyle() == linestyle
+
+    def test_apply(self, long_df):
+
+        def f(grid, color):
+            grid.figure.set_facecolor(color)
+
+        color = (.1, .6, .3, .9)
+        g = ag.FacetGrid(long_df)
+        res = g.apply(f, color)
+        assert res is g
+        assert g.figure.get_facecolor() == color
+
+    def test_pipe(self, long_df):
+
+        def f(grid, color):
+            grid.figure.set_facecolor(color)
+            return color
+
+        color = (.1, .6, .3, .9)
+        g = ag.FacetGrid(long_df)
+        res = g.pipe(f, color)
+        assert res == color
+        assert g.figure.get_facecolor() == color
+
+    def test_tick_params(self):
+
+        g = ag.FacetGrid(self.df, row="a", col="b")
+        color = "blue"
+        pad = 3
+        g.tick_params(pad=pad, color=color)
+        for ax in g.axes.flat:
+            for axis in ["xaxis", "yaxis"]:
+                for tick in getattr(ax, axis).get_major_ticks():
+                    assert mpl.colors.same_color(tick.tick1line.get_color(), color)
+                    assert mpl.colors.same_color(tick.tick2line.get_color(), color)
+                    assert tick.get_pad() == pad
+
+
+class TestPairGrid:
+
+    rs = np.random.RandomState(sum(map(ord, "PairGrid")))
+    df = pd.DataFrame(dict(x=rs.normal(size=60),
+                           y=rs.randint(0, 4, size=(60)),
+                           z=rs.gamma(3, size=60),
+                           a=np.repeat(list("abc"), 20),
+                           b=np.repeat(list("abcdefghijkl"), 5)))
+
+    def test_self_data(self):
+
+        g = ag.PairGrid(self.df)
+        assert g.data is self.df
+
+    def test_ignore_datelike_data(self):
+
+        df = self.df.copy()
+        df['date'] = pd.date_range('2010-01-01', periods=len(df), freq='d')
+        result = ag.PairGrid(self.df).data
+        expected = df.drop('date', axis=1)
+        tm.assert_frame_equal(result, expected)
+
+    def test_self_figure(self):
+
+        g = ag.PairGrid(self.df)
+        assert isinstance(g.figure, plt.Figure)
+        assert g.figure is g._figure
+
+    def test_self_axes(self):
+
+        g = ag.PairGrid(self.df)
+        for ax in g.axes.flat:
+            assert isinstance(ax, plt.Axes)
+
+    def test_default_axes(self):
+
+        g = ag.PairGrid(self.df)
+        assert g.axes.shape == (3, 3)
+        assert g.x_vars == ["x", "y", "z"]
+        assert g.y_vars == ["x", "y", "z"]
+        assert g.square_grid
+
+    @pytest.mark.parametrize("vars", [["z", "x"], np.array(["z", "x"])])
+    def test_specific_square_axes(self, vars):
+
+        g = ag.PairGrid(self.df, vars=vars)
+        assert g.axes.shape == (len(vars), len(vars))
+        assert g.x_vars == list(vars)
+        assert g.y_vars == list(vars)
+        assert g.square_grid
+
+    def test_remove_hue_from_default(self):
+
+        hue = "z"
+        g = ag.PairGrid(self.df, hue=hue)
+        assert hue not in g.x_vars
+        assert hue not in g.y_vars
+
+        vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df, hue=hue, vars=vars)
+        assert hue in g.x_vars
+        assert hue in g.y_vars
+
+    @pytest.mark.parametrize(
+        "x_vars, y_vars",
+        [
+            (["x", "y"], ["z", "y", "x"]),
+            (["x", "y"], "z"),
+            (np.array(["x", "y"]), np.array(["z", "y", "x"])),
+        ],
+    )
+    def test_specific_nonsquare_axes(self, x_vars, y_vars):
+
+        g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)
+        assert g.axes.shape == (len(y_vars), len(x_vars))
+        assert g.x_vars == list(x_vars)
+        assert g.y_vars == list(y_vars)
+        assert not g.square_grid
+
+    def test_corner(self):
+
+        plot_vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df, vars=plot_vars, corner=True)
+        corner_size = sum(i + 1 for i in range(len(plot_vars)))
+        assert len(g.figure.axes) == corner_size
+
+        g.map_diag(plt.hist)
+        assert len(g.figure.axes) == (corner_size + len(plot_vars))
+
+        for ax in np.diag(g.axes):
+            assert not ax.yaxis.get_visible()
+
+        plot_vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df, vars=plot_vars, corner=True)
+        g.map(scatterplot)
+        assert len(g.figure.axes) == corner_size
+        assert g.axes[0, 0].get_ylabel() == "x"
+
+    def test_size(self):
+
+        g1 = ag.PairGrid(self.df, height=3)
+        npt.assert_array_equal(g1.fig.get_size_inches(), (9, 9))
+
+        g2 = ag.PairGrid(self.df, height=4, aspect=.5)
+        npt.assert_array_equal(g2.fig.get_size_inches(), (6, 12))
+
+        g3 = ag.PairGrid(self.df, y_vars=["z"], x_vars=["x", "y"],
+                         height=2, aspect=2)
+        npt.assert_array_equal(g3.fig.get_size_inches(), (8, 2))
+
+    def test_empty_grid(self):
+
+        with pytest.raises(ValueError, match="No variables found"):
+            ag.PairGrid(self.df[["a", "b"]])
+
+    def test_map(self):
+
+        vars = ["x", "y", "z"]
+        g1 = ag.PairGrid(self.df)
+        g1.map(plt.scatter)
+
+        for i, axes_i in enumerate(g1.axes):
+            for j, ax in enumerate(axes_i):
+                x_in = self.df[vars[j]]
+                y_in = self.df[vars[i]]
+                x_out, y_out = ax.collections[0].get_offsets().T
+                npt.assert_array_equal(x_in, x_out)
+                npt.assert_array_equal(y_in, y_out)
+
+        g2 = ag.PairGrid(self.df, hue="a")
+        g2.map(plt.scatter)
+
+        for i, axes_i in enumerate(g2.axes):
+            for j, ax in enumerate(axes_i):
+                x_in = self.df[vars[j]]
+                y_in = self.df[vars[i]]
+                for k, k_level in enumerate(self.df.a.unique()):
+                    x_in_k = x_in[self.df.a == k_level]
+                    y_in_k = y_in[self.df.a == k_level]
+                    x_out, y_out = ax.collections[k].get_offsets().T
+                npt.assert_array_equal(x_in_k, x_out)
+                npt.assert_array_equal(y_in_k, y_out)
+
+    def test_map_nonsquare(self):
+
+        x_vars = ["x"]
+        y_vars = ["y", "z"]
+        g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)
+        g.map(plt.scatter)
+
+        x_in = self.df.x
+        for i, i_var in enumerate(y_vars):
+            ax = g.axes[i, 0]
+            y_in = self.df[i_var]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+    def test_map_lower(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df)
+        g.map_lower(plt.scatter)
+
+        for i, j in zip(*np.tril_indices_from(g.axes, -1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.triu_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+    def test_map_upper(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df)
+        g.map_upper(plt.scatter)
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.tril_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+    def test_map_mixed_funcsig(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df, vars=vars)
+        g.map_lower(scatterplot)
+        g.map_upper(plt.scatter)
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+    def test_map_diag(self):
+
+        g = ag.PairGrid(self.df)
+        g.map_diag(plt.hist)
+
+        for var, ax in zip(g.diag_vars, g.diag_axes):
+            assert len(ax.patches) == 10
+            assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()
+
+        g = ag.PairGrid(self.df, hue="a")
+        g.map_diag(plt.hist)
+
+        for ax in g.diag_axes:
+            assert len(ax.patches) == 30
+
+        g = ag.PairGrid(self.df, hue="a")
+        g.map_diag(plt.hist, histtype='step')
+
+        for ax in g.diag_axes:
+            for ptch in ax.patches:
+                assert not ptch.fill
+
+    def test_map_diag_rectangular(self):
+
+        x_vars = ["x", "y"]
+        y_vars = ["x", "z", "y"]
+        g1 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)
+        g1.map_diag(plt.hist)
+        g1.map_offdiag(plt.scatter)
+
+        assert set(g1.diag_vars) == (set(x_vars) & set(y_vars))
+
+        for var, ax in zip(g1.diag_vars, g1.diag_axes):
+            assert len(ax.patches) == 10
+            assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()
+
+        for j, x_var in enumerate(x_vars):
+            for i, y_var in enumerate(y_vars):
+
+                ax = g1.axes[i, j]
+                if x_var == y_var:
+                    diag_ax = g1.diag_axes[j]  # because fewer x than y vars
+                    assert ax.bbox.bounds == diag_ax.bbox.bounds
+
+                else:
+                    x, y = ax.collections[0].get_offsets().T
+                    assert_array_equal(x, self.df[x_var])
+                    assert_array_equal(y, self.df[y_var])
+
+        g2 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars, hue="a")
+        g2.map_diag(plt.hist)
+        g2.map_offdiag(plt.scatter)
+
+        assert set(g2.diag_vars) == (set(x_vars) & set(y_vars))
+
+        for ax in g2.diag_axes:
+            assert len(ax.patches) == 30
+
+        x_vars = ["x", "y", "z"]
+        y_vars = ["x", "z"]
+        g3 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)
+        g3.map_diag(plt.hist)
+        g3.map_offdiag(plt.scatter)
+
+        assert set(g3.diag_vars) == (set(x_vars) & set(y_vars))
+
+        for var, ax in zip(g3.diag_vars, g3.diag_axes):
+            assert len(ax.patches) == 10
+            assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()
+
+        for j, x_var in enumerate(x_vars):
+            for i, y_var in enumerate(y_vars):
+
+                ax = g3.axes[i, j]
+                if x_var == y_var:
+                    diag_ax = g3.diag_axes[i]  # because fewer y than x vars
+                    assert ax.bbox.bounds == diag_ax.bbox.bounds
+                else:
+                    x, y = ax.collections[0].get_offsets().T
+                    assert_array_equal(x, self.df[x_var])
+                    assert_array_equal(y, self.df[y_var])
+
+    def test_map_diag_color(self):
+
+        color = "red"
+
+        g1 = ag.PairGrid(self.df)
+        g1.map_diag(plt.hist, color=color)
+
+        for ax in g1.diag_axes:
+            for patch in ax.patches:
+                assert_colors_equal(patch.get_facecolor(), color)
+
+        g2 = ag.PairGrid(self.df)
+        g2.map_diag(kdeplot, color='red')
+
+        for ax in g2.diag_axes:
+            for line in ax.lines:
+                assert_colors_equal(line.get_color(), color)
+
+    def test_map_diag_palette(self):
+
+        palette = "muted"
+        pal = color_palette(palette, n_colors=len(self.df.a.unique()))
+        g = ag.PairGrid(self.df, hue="a", palette=palette)
+        g.map_diag(kdeplot)
+
+        for ax in g.diag_axes:
+            for line, color in zip(ax.lines[::-1], pal):
+                assert_colors_equal(line.get_color(), color)
+
+    def test_map_diag_and_offdiag(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.PairGrid(self.df)
+        g.map_offdiag(plt.scatter)
+        g.map_diag(plt.hist)
+
+        for ax in g.diag_axes:
+            assert len(ax.patches) == 10
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.tril_indices_from(g.axes, -1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.diag_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+    def test_diag_sharey(self):
+
+        g = ag.PairGrid(self.df, diag_sharey=True)
+        g.map_diag(kdeplot)
+        for ax in g.diag_axes[1:]:
+            assert ax.get_ylim() == g.diag_axes[0].get_ylim()
+
+    def test_map_diag_matplotlib(self):
+
+        bins = 10
+        g = ag.PairGrid(self.df)
+        g.map_diag(plt.hist, bins=bins)
+        for ax in g.diag_axes:
+            assert len(ax.patches) == bins
+
+        levels = len(self.df["a"].unique())
+        g = ag.PairGrid(self.df, hue="a")
+        g.map_diag(plt.hist, bins=bins)
+        for ax in g.diag_axes:
+            assert len(ax.patches) == (bins * levels)
+
+    def test_palette(self):
+
+        rcmod.set()
+
+        g = ag.PairGrid(self.df, hue="a")
+        assert g.palette == color_palette(n_colors=len(self.df.a.unique()))
+
+        g = ag.PairGrid(self.df, hue="b")
+        assert g.palette == color_palette("husl", len(self.df.b.unique()))
+
+        g = ag.PairGrid(self.df, hue="a", palette="Set2")
+        assert g.palette == color_palette("Set2", len(self.df.a.unique()))
+
+        dict_pal = dict(a="red", b="green", c="blue")
+        list_pal = color_palette(["red", "green", "blue"])
+        g = ag.PairGrid(self.df, hue="a", palette=dict_pal)
+        assert g.palette == list_pal
+
+        list_pal = color_palette(["blue", "red", "green"])
+        g = ag.PairGrid(self.df, hue="a", hue_order=list("cab"),
+                        palette=dict_pal)
+        assert g.palette == list_pal
+
+    def test_hue_kws(self):
+
+        kws = dict(marker=["o", "s", "d", "+"])
+        g = ag.PairGrid(self.df, hue="a", hue_kws=kws)
+        g.map(plt.plot)
+
+        for line, marker in zip(g.axes[0, 0].lines, kws["marker"]):
+            assert line.get_marker() == marker
+
+        g = ag.PairGrid(self.df, hue="a", hue_kws=kws,
+                        hue_order=list("dcab"))
+        g.map(plt.plot)
+
+        for line, marker in zip(g.axes[0, 0].lines, kws["marker"]):
+            assert line.get_marker() == marker
+
+    def test_hue_order(self):
+
+        order = list("dcab")
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map(plt.plot)
+
+        for line, level in zip(g.axes[1, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "y"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_diag(plt.plot)
+
+        for line, level in zip(g.axes[0, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "x"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_lower(plt.plot)
+
+        for line, level in zip(g.axes[1, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "y"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_upper(plt.plot)
+
+        for line, level in zip(g.axes[0, 1].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "y"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "x"])
+
+        plt.close("all")
+
+    def test_hue_order_missing_level(self):
+
+        order = list("dcaeb")
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map(plt.plot)
+
+        for line, level in zip(g.axes[1, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "y"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_diag(plt.plot)
+
+        for line, level in zip(g.axes[0, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "x"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_lower(plt.plot)
+
+        for line, level in zip(g.axes[1, 0].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "x"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "y"])
+
+        plt.close("all")
+
+        g = ag.PairGrid(self.df, hue="a", hue_order=order)
+        g.map_upper(plt.plot)
+
+        for line, level in zip(g.axes[0, 1].lines, order):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, self.df.loc[self.df.a == level, "y"])
+            npt.assert_array_equal(y, self.df.loc[self.df.a == level, "x"])
+
+        plt.close("all")
+
+    def test_hue_in_map(self, long_df):
+
+        g = ag.PairGrid(long_df, vars=["x", "y"])
+        g.map(scatterplot, hue=long_df["a"])
+        ax = g.axes.flat[0]
+        points = ax.collections[0]
+        assert len(set(map(tuple, points.get_facecolors()))) == 3
+
+    def test_nondefault_index(self):
+
+        df = self.df.copy().set_index("b")
+
+        plot_vars = ["x", "y", "z"]
+        g1 = ag.PairGrid(df)
+        g1.map(plt.scatter)
+
+        for i, axes_i in enumerate(g1.axes):
+            for j, ax in enumerate(axes_i):
+                x_in = self.df[plot_vars[j]]
+                y_in = self.df[plot_vars[i]]
+                x_out, y_out = ax.collections[0].get_offsets().T
+                npt.assert_array_equal(x_in, x_out)
+                npt.assert_array_equal(y_in, y_out)
+
+        g2 = ag.PairGrid(df, hue="a")
+        g2.map(plt.scatter)
+
+        for i, axes_i in enumerate(g2.axes):
+            for j, ax in enumerate(axes_i):
+                x_in = self.df[plot_vars[j]]
+                y_in = self.df[plot_vars[i]]
+                for k, k_level in enumerate(self.df.a.unique()):
+                    x_in_k = x_in[self.df.a == k_level]
+                    y_in_k = y_in[self.df.a == k_level]
+                    x_out, y_out = ax.collections[k].get_offsets().T
+                    npt.assert_array_equal(x_in_k, x_out)
+                    npt.assert_array_equal(y_in_k, y_out)
+
+    @pytest.mark.parametrize("func", [scatterplot, plt.scatter])
+    def test_dropna(self, func):
+
+        df = self.df.copy()
+        n_null = 20
+        df.loc[np.arange(n_null), "x"] = np.nan
+
+        plot_vars = ["x", "y", "z"]
+
+        g1 = ag.PairGrid(df, vars=plot_vars, dropna=True)
+        g1.map(func)
+
+        for i, axes_i in enumerate(g1.axes):
+            for j, ax in enumerate(axes_i):
+                x_in = df[plot_vars[j]]
+                y_in = df[plot_vars[i]]
+                x_out, y_out = ax.collections[0].get_offsets().T
+
+                n_valid = (x_in * y_in).notnull().sum()
+
+                assert n_valid == len(x_out)
+                assert n_valid == len(y_out)
+
+        g1.map_diag(histplot)
+        for i, ax in enumerate(g1.diag_axes):
+            var = plot_vars[i]
+            count = sum(p.get_height() for p in ax.patches)
+            assert count == df[var].notna().sum()
+
+    def test_histplot_legend(self):
+
+        # Tests _extract_legend_handles
+        g = ag.PairGrid(self.df, vars=["x", "y"], hue="a")
+        g.map_offdiag(histplot)
+        g.add_legend()
+
+        assert len(g._legend.legendHandles) == len(self.df["a"].unique())
+
+    def test_pairplot(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.pairplot(self.df)
+
+        for ax in g.diag_axes:
+            assert len(ax.patches) > 1
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.tril_indices_from(g.axes, -1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.diag_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+        g = ag.pairplot(self.df, hue="a")
+        n = len(self.df.a.unique())
+
+        for ax in g.diag_axes:
+            assert len(ax.collections) == n
+
+    def test_pairplot_reg(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.pairplot(self.df, diag_kind="hist", kind="reg")
+
+        for ax in g.diag_axes:
+            assert len(ax.patches)
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+            assert len(ax.lines) == 1
+            assert len(ax.collections) == 2
+
+        for i, j in zip(*np.tril_indices_from(g.axes, -1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+            assert len(ax.lines) == 1
+            assert len(ax.collections) == 2
+
+        for i, j in zip(*np.diag_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+    def test_pairplot_reg_hue(self):
+
+        markers = ["o", "s", "d"]
+        g = ag.pairplot(self.df, kind="reg", hue="a", markers=markers)
+
+        ax = g.axes[-1, 0]
+        c1 = ax.collections[0]
+        c2 = ax.collections[2]
+
+        assert not np.array_equal(c1.get_facecolor(), c2.get_facecolor())
+        assert not np.array_equal(
+            c1.get_paths()[0].vertices, c2.get_paths()[0].vertices,
+        )
+
+    def test_pairplot_diag_kde(self):
+
+        vars = ["x", "y", "z"]
+        g = ag.pairplot(self.df, diag_kind="kde")
+
+        for ax in g.diag_axes:
+            assert len(ax.collections) == 1
+
+        for i, j in zip(*np.triu_indices_from(g.axes, 1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.tril_indices_from(g.axes, -1)):
+            ax = g.axes[i, j]
+            x_in = self.df[vars[j]]
+            y_in = self.df[vars[i]]
+            x_out, y_out = ax.collections[0].get_offsets().T
+            npt.assert_array_equal(x_in, x_out)
+            npt.assert_array_equal(y_in, y_out)
+
+        for i, j in zip(*np.diag_indices_from(g.axes)):
+            ax = g.axes[i, j]
+            assert len(ax.collections) == 0
+
+    def test_pairplot_kde(self):
+
+        f, ax1 = plt.subplots()
+        kdeplot(data=self.df, x="x", y="y", ax=ax1)
+
+        g = ag.pairplot(self.df, kind="kde")
+        ax2 = g.axes[1, 0]
+
+        assert_plots_equal(ax1, ax2, labels=False)
+
+    def test_pairplot_hist(self):
+
+        f, ax1 = plt.subplots()
+        histplot(data=self.df, x="x", y="y", ax=ax1)
+
+        g = ag.pairplot(self.df, kind="hist")
+        ax2 = g.axes[1, 0]
+
+        assert_plots_equal(ax1, ax2, labels=False)
+
+    def test_pairplot_markers(self):
+
+        vars = ["x", "y", "z"]
+        markers = ["o", "X", "s"]
+        g = ag.pairplot(self.df, hue="a", vars=vars, markers=markers)
+        m1 = g._legend.legendHandles[0].get_paths()[0]
+        m2 = g._legend.legendHandles[1].get_paths()[0]
+        assert m1 != m2
+
+        with pytest.warns(UserWarning):
+            g = ag.pairplot(self.df, hue="a", vars=vars, markers=markers[:-2])
+
+    def test_corner_despine(self):
+
+        g = ag.PairGrid(self.df, corner=True, despine=False)
+        g.map_diag(histplot)
+        assert g.axes[0, 0].spines["top"].get_visible()
+
+    def test_corner_set(self):
+
+        g = ag.PairGrid(self.df, corner=True, despine=False)
+        g.set(xlim=(0, 10))
+        assert g.axes[-1, 0].get_xlim() == (0, 10)
+
+    def test_legend(self):
+
+        g1 = ag.pairplot(self.df, hue="a")
+        assert isinstance(g1.legend, mpl.legend.Legend)
+
+        g2 = ag.pairplot(self.df)
+        assert g2.legend is None
+
+    def test_tick_params(self):
+
+        g = ag.PairGrid(self.df)
+        color = "red"
+        pad = 3
+        g.tick_params(pad=pad, color=color)
+        for ax in g.axes.flat:
+            for axis in ["xaxis", "yaxis"]:
+                for tick in getattr(ax, axis).get_major_ticks():
+                    assert mpl.colors.same_color(tick.tick1line.get_color(), color)
+                    assert mpl.colors.same_color(tick.tick2line.get_color(), color)
+                    assert tick.get_pad() == pad
+
+
+class TestJointGrid:
+
+    rs = np.random.RandomState(sum(map(ord, "JointGrid")))
+    x = rs.randn(100)
+    y = rs.randn(100)
+    x_na = x.copy()
+    x_na[10] = np.nan
+    x_na[20] = np.nan
+    data = pd.DataFrame(dict(x=x, y=y, x_na=x_na))
+
+    def test_margin_grid_from_lists(self):
+
+        g = ag.JointGrid(x=self.x.tolist(), y=self.y.tolist())
+        npt.assert_array_equal(g.x, self.x)
+        npt.assert_array_equal(g.y, self.y)
+
+    def test_margin_grid_from_arrays(self):
+
+        g = ag.JointGrid(x=self.x, y=self.y)
+        npt.assert_array_equal(g.x, self.x)
+        npt.assert_array_equal(g.y, self.y)
+
+    def test_margin_grid_from_series(self):
+
+        g = ag.JointGrid(x=self.data.x, y=self.data.y)
+        npt.assert_array_equal(g.x, self.x)
+        npt.assert_array_equal(g.y, self.y)
+
+    def test_margin_grid_from_dataframe(self):
+
+        g = ag.JointGrid(x="x", y="y", data=self.data)
+        npt.assert_array_equal(g.x, self.x)
+        npt.assert_array_equal(g.y, self.y)
+
+    def test_margin_grid_from_dataframe_bad_variable(self):
+
+        with pytest.raises(ValueError):
+            ag.JointGrid(x="x", y="bad_column", data=self.data)
+
+    def test_margin_grid_axis_labels(self):
+
+        g = ag.JointGrid(x="x", y="y", data=self.data)
+
+        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()
+        assert xlabel == "x"
+        assert ylabel == "y"
+
+        g.set_axis_labels("x variable", "y variable")
+        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()
+        assert xlabel == "x variable"
+        assert ylabel == "y variable"
+
+    def test_dropna(self):
+
+        g = ag.JointGrid(x="x_na", y="y", data=self.data, dropna=False)
+        assert len(g.x) == len(self.x_na)
+
+        g = ag.JointGrid(x="x_na", y="y", data=self.data, dropna=True)
+        assert len(g.x) == pd.notnull(self.x_na).sum()
+
+    def test_axlims(self):
+
+        lim = (-3, 3)
+        g = ag.JointGrid(x="x", y="y", data=self.data, xlim=lim, ylim=lim)
+
+        assert g.ax_joint.get_xlim() == lim
+        assert g.ax_joint.get_ylim() == lim
+
+        assert g.ax_marg_x.get_xlim() == lim
+        assert g.ax_marg_y.get_ylim() == lim
+
+    def test_marginal_ticks(self):
+
+        g = ag.JointGrid(marginal_ticks=False)
+        assert not sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())
+        assert not sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())
+
+        g = ag.JointGrid(marginal_ticks=True)
+        assert sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())
+        assert sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())
+
+    def test_bivariate_plot(self):
+
+        g = ag.JointGrid(x="x", y="y", data=self.data)
+        g.plot_joint(plt.plot)
+
+        x, y = g.ax_joint.lines[0].get_xydata().T
+        npt.assert_array_equal(x, self.x)
+        npt.assert_array_equal(y, self.y)
+
+    def test_univariate_plot(self):
+
+        g = ag.JointGrid(x="x", y="x", data=self.data)
+        g.plot_marginals(kdeplot)
+
+        _, y1 = g.ax_marg_x.lines[0].get_xydata().T
+        y2, _ = g.ax_marg_y.lines[0].get_xydata().T
+        npt.assert_array_equal(y1, y2)
+
+    def test_univariate_plot_distplot(self):
+
+        bins = 10
+        g = ag.JointGrid(x="x", y="x", data=self.data)
+        with pytest.warns(UserWarning):
+            g.plot_marginals(distplot, bins=bins)
+        assert len(g.ax_marg_x.patches) == bins
+        assert len(g.ax_marg_y.patches) == bins
+        for x, y in zip(g.ax_marg_x.patches, g.ax_marg_y.patches):
+            assert x.get_height() == y.get_width()
+
+    def test_univariate_plot_matplotlib(self):
+
+        bins = 10
+        g = ag.JointGrid(x="x", y="x", data=self.data)
+        g.plot_marginals(plt.hist, bins=bins)
+        assert len(g.ax_marg_x.patches) == bins
+        assert len(g.ax_marg_y.patches) == bins
+
+    def test_plot(self):
+
+        g = ag.JointGrid(x="x", y="x", data=self.data)
+        g.plot(plt.plot, kdeplot)
+
+        x, y = g.ax_joint.lines[0].get_xydata().T
+        npt.assert_array_equal(x, self.x)
+        npt.assert_array_equal(y, self.x)
+
+        _, y1 = g.ax_marg_x.lines[0].get_xydata().T
+        y2, _ = g.ax_marg_y.lines[0].get_xydata().T
+        npt.assert_array_equal(y1, y2)
+
+    def test_space(self):
+
+        g = ag.JointGrid(x="x", y="y", data=self.data, space=0)
+
+        joint_bounds = g.ax_joint.bbox.bounds
+        marg_x_bounds = g.ax_marg_x.bbox.bounds
+        marg_y_bounds = g.ax_marg_y.bbox.bounds
+
+        assert joint_bounds[2] == marg_x_bounds[2]
+        assert joint_bounds[3] == marg_y_bounds[3]
+
+    @pytest.mark.parametrize(
+        "as_vector", [True, False],
+    )
+    def test_hue(self, long_df, as_vector):
+
+        if as_vector:
+            data = None
+            x, y, hue = long_df["x"], long_df["y"], long_df["a"]
+        else:
+            data = long_df
+            x, y, hue = "x", "y", "a"
+
+        g = ag.JointGrid(data=data, x=x, y=y, hue=hue)
+        g.plot_joint(scatterplot)
+        g.plot_marginals(histplot)
+
+        g2 = ag.JointGrid()
+        scatterplot(data=long_df, x=x, y=y, hue=hue, ax=g2.ax_joint)
+        histplot(data=long_df, x=x, hue=hue, ax=g2.ax_marg_x)
+        histplot(data=long_df, y=y, hue=hue, ax=g2.ax_marg_y)
+
+        assert_plots_equal(g.ax_joint, g2.ax_joint)
+        assert_plots_equal(g.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_refline(self):
+
+        g = ag.JointGrid(x="x", y="y", data=self.data)
+        g.plot(scatterplot, histplot)
+        g.refline()
+        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines
+
+        refx = refy = 0.5
+        hline = np.array([[0, refy], [1, refy]])
+        vline = np.array([[refx, 0], [refx, 1]])
+        g.refline(x=refx, y=refy, joint=False, marginal=False)
+        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines
+
+        g.refline(x=refx, y=refy)
+        assert g.ax_joint.lines[0].get_color() == '.5'
+        assert g.ax_joint.lines[0].get_linestyle() == '--'
+        assert len(g.ax_joint.lines) == 2
+        assert len(g.ax_marg_x.lines) == 1
+        assert len(g.ax_marg_y.lines) == 1
+        npt.assert_array_equal(g.ax_joint.lines[0].get_xydata(), vline)
+        npt.assert_array_equal(g.ax_joint.lines[1].get_xydata(), hline)
+        npt.assert_array_equal(g.ax_marg_x.lines[0].get_xydata(), vline)
+        npt.assert_array_equal(g.ax_marg_y.lines[0].get_xydata(), hline)
+
+        color, linestyle = 'red', '-'
+        g.refline(x=refx, marginal=False, color=color, linestyle=linestyle)
+        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), vline)
+        assert g.ax_joint.lines[-1].get_color() == color
+        assert g.ax_joint.lines[-1].get_linestyle() == linestyle
+        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)
+
+        g.refline(x=refx, joint=False)
+        npt.assert_array_equal(g.ax_marg_x.lines[-1].get_xydata(), vline)
+        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines) + 1
+
+        g.refline(y=refy, joint=False)
+        npt.assert_array_equal(g.ax_marg_y.lines[-1].get_xydata(), hline)
+        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)
+
+        g.refline(y=refy, marginal=False)
+        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), hline)
+        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)
+
+
+class TestJointPlot:
+
+    rs = np.random.RandomState(sum(map(ord, "jointplot")))
+    x = rs.randn(100)
+    y = rs.randn(100)
+    data = pd.DataFrame(dict(x=x, y=y))
+
+    def test_scatter(self):
+
+        g = ag.jointplot(x="x", y="y", data=self.data)
+        assert len(g.ax_joint.collections) == 1
+
+        x, y = g.ax_joint.collections[0].get_offsets().T
+        assert_array_equal(self.x, x)
+        assert_array_equal(self.y, y)
+
+        assert_array_almost_equal(
+            [b.get_x() for b in g.ax_marg_x.patches],
+            np.histogram_bin_edges(self.x, "auto")[:-1],
+        )
+
+        assert_array_almost_equal(
+            [b.get_y() for b in g.ax_marg_y.patches],
+            np.histogram_bin_edges(self.y, "auto")[:-1],
+        )
+
+    def test_scatter_hue(self, long_df):
+
+        g1 = ag.jointplot(data=long_df, x="x", y="y", hue="a")
+
+        g2 = ag.JointGrid()
+        scatterplot(data=long_df, x="x", y="y", hue="a", ax=g2.ax_joint)
+        kdeplot(data=long_df, x="x", hue="a", ax=g2.ax_marg_x, fill=True)
+        kdeplot(data=long_df, y="y", hue="a", ax=g2.ax_marg_y, fill=True)
+
+        assert_plots_equal(g1.ax_joint, g2.ax_joint)
+        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_reg(self):
+
+        g = ag.jointplot(x="x", y="y", data=self.data, kind="reg")
+        assert len(g.ax_joint.collections) == 2
+
+        x, y = g.ax_joint.collections[0].get_offsets().T
+        assert_array_equal(self.x, x)
+        assert_array_equal(self.y, y)
+
+        assert g.ax_marg_x.patches
+        assert g.ax_marg_y.patches
+
+        assert g.ax_marg_x.lines
+        assert g.ax_marg_y.lines
+
+    def test_resid(self):
+
+        g = ag.jointplot(x="x", y="y", data=self.data, kind="resid")
+        assert g.ax_joint.collections
+        assert g.ax_joint.lines
+        assert not g.ax_marg_x.lines
+        assert not g.ax_marg_y.lines
+
+    def test_hist(self, long_df):
+
+        bins = 3, 6
+        g1 = ag.jointplot(data=long_df, x="x", y="y", kind="hist", bins=bins)
+
+        g2 = ag.JointGrid()
+        histplot(data=long_df, x="x", y="y", ax=g2.ax_joint, bins=bins)
+        histplot(data=long_df, x="x", ax=g2.ax_marg_x, bins=bins[0])
+        histplot(data=long_df, y="y", ax=g2.ax_marg_y, bins=bins[1])
+
+        assert_plots_equal(g1.ax_joint, g2.ax_joint)
+        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_hex(self):
+
+        g = ag.jointplot(x="x", y="y", data=self.data, kind="hex")
+        assert g.ax_joint.collections
+        assert g.ax_marg_x.patches
+        assert g.ax_marg_y.patches
+
+    def test_kde(self, long_df):
+
+        g1 = ag.jointplot(data=long_df, x="x", y="y", kind="kde")
+
+        g2 = ag.JointGrid()
+        kdeplot(data=long_df, x="x", y="y", ax=g2.ax_joint)
+        kdeplot(data=long_df, x="x", ax=g2.ax_marg_x)
+        kdeplot(data=long_df, y="y", ax=g2.ax_marg_y)
+
+        assert_plots_equal(g1.ax_joint, g2.ax_joint)
+        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_kde_hue(self, long_df):
+
+        g1 = ag.jointplot(data=long_df, x="x", y="y", hue="a", kind="kde")
+
+        g2 = ag.JointGrid()
+        kdeplot(data=long_df, x="x", y="y", hue="a", ax=g2.ax_joint)
+        kdeplot(data=long_df, x="x", hue="a", ax=g2.ax_marg_x)
+        kdeplot(data=long_df, y="y", hue="a", ax=g2.ax_marg_y)
+
+        assert_plots_equal(g1.ax_joint, g2.ax_joint)
+        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_color(self):
+
+        g = ag.jointplot(x="x", y="y", data=self.data, color="purple")
+
+        scatter_color = g.ax_joint.collections[0].get_facecolor()
+        assert_colors_equal(scatter_color, "purple")
+
+        hist_color = g.ax_marg_x.patches[0].get_facecolor()[:3]
+        assert_colors_equal(hist_color, "purple")
+
+    def test_palette(self, long_df):
+
+        kws = dict(data=long_df, hue="a", palette="Set2")
+
+        g1 = ag.jointplot(x="x", y="y", **kws)
+
+        g2 = ag.JointGrid()
+        scatterplot(x="x", y="y", ax=g2.ax_joint, **kws)
+        kdeplot(x="x", ax=g2.ax_marg_x, fill=True, **kws)
+        kdeplot(y="y", ax=g2.ax_marg_y, fill=True, **kws)
+
+        assert_plots_equal(g1.ax_joint, g2.ax_joint)
+        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
+        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
+
+    def test_hex_customise(self):
+
+        # test that default gridsize can be overridden
+        g = ag.jointplot(x="x", y="y", data=self.data, kind="hex",
+                         joint_kws=dict(gridsize=5))
+        assert len(g.ax_joint.collections) == 1
+        a = g.ax_joint.collections[0].get_array()
+        assert a.shape[0] == 28  # 28 hexagons expected for gridsize 5
+
+    def test_bad_kind(self):
+
+        with pytest.raises(ValueError):
+            ag.jointplot(x="x", y="y", data=self.data, kind="not_a_kind")
+
+    def test_unsupported_hue_kind(self):
+
+        for kind in ["reg", "resid", "hex"]:
+            with pytest.raises(ValueError):
+                ag.jointplot(x="x", y="y", hue="a", data=self.data, kind=kind)
+
+    def test_leaky_dict(self):
+        # Validate input dicts are unchanged by jointplot plotting function
+
+        for kwarg in ("joint_kws", "marginal_kws"):
+            for kind in ("hex", "kde", "resid", "reg", "scatter"):
+                empty_dict = {}
+                ag.jointplot(x="x", y="y", data=self.data, kind=kind,
+                             **{kwarg: empty_dict})
+                assert empty_dict == {}
+
+    def test_distplot_kwarg_warning(self, long_df):
+
+        with pytest.warns(UserWarning):
+            g = ag.jointplot(data=long_df, x="x", y="y", marginal_kws=dict(rug=True))
+        assert g.ax_marg_x.patches
+
+    def test_ax_warning(self, long_df):
+
+        ax = plt.gca()
+        with pytest.warns(UserWarning):
+            g = ag.jointplot(data=long_df, x="x", y="y", ax=ax)
+        assert g.ax_joint.collections
diff --git a/testbed/mwaskom__seaborn/tests/test_categorical.py b/testbed/mwaskom__seaborn/tests/test_categorical.py
new file mode 100644
index 0000000000000000000000000000000000000000..955d1f0babffd88b1ddd435528775803bb975dbf
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_categorical.py
@@ -0,0 +1,3485 @@
+import itertools
+from functools import partial
+import warnings
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from matplotlib.colors import rgb2hex, same_color, to_rgb, to_rgba
+
+import pytest
+from pytest import approx
+import numpy.testing as npt
+from numpy.testing import (
+    assert_array_equal,
+    assert_array_less,
+)
+
+from seaborn import categorical as cat
+from seaborn import palettes
+
+from seaborn.utils import _version_predates
+from seaborn._oldcore import categorical_order
+from seaborn.axisgrid import FacetGrid
+from seaborn.categorical import (
+    _CategoricalPlotterNew,
+    Beeswarm,
+    catplot,
+    pointplot,
+    stripplot,
+    swarmplot,
+)
+from seaborn.palettes import color_palette
+from seaborn.utils import _normal_quantile_func, _draw_figure
+from seaborn._compat import get_colormap
+from seaborn._testing import assert_plots_equal
+
+
+PLOT_FUNCS = [
+    catplot,
+    stripplot,
+    swarmplot,
+]
+
+
+class TestCategoricalPlotterNew:
+
+    @pytest.mark.parametrize(
+        "func,kwargs",
+        itertools.product(
+            PLOT_FUNCS,
+            [
+                {"x": "x", "y": "a"},
+                {"x": "a", "y": "y"},
+                {"x": "y"},
+                {"y": "x"},
+            ],
+        ),
+    )
+    def test_axis_labels(self, long_df, func, kwargs):
+
+        func(data=long_df, **kwargs)
+
+        ax = plt.gca()
+        for axis in "xy":
+            val = kwargs.get(axis, "")
+            label_func = getattr(ax, f"get_{axis}label")
+            assert label_func() == val
+
+    @pytest.mark.parametrize("func", PLOT_FUNCS)
+    def test_empty(self, func):
+
+        func()
+        ax = plt.gca()
+        assert not ax.collections
+        assert not ax.patches
+        assert not ax.lines
+
+        func(x=[], y=[])
+        ax = plt.gca()
+        assert not ax.collections
+        assert not ax.patches
+        assert not ax.lines
+
+    def test_redundant_hue_backcompat(self, long_df):
+
+        p = _CategoricalPlotterNew(
+            data=long_df,
+            variables={"x": "s", "y": "y"},
+        )
+
+        color = None
+        palette = dict(zip(long_df["s"].unique(), color_palette()))
+        hue_order = None
+
+        palette, _ = p._hue_backcompat(color, palette, hue_order, force_hue=True)
+
+        assert p.variables["hue"] == "s"
+        assert_array_equal(p.plot_data["hue"], p.plot_data["x"])
+        assert all(isinstance(k, str) for k in palette)
+
+
+class CategoricalFixture:
+    """Test boxplot (also base class for things like violinplots)."""
+    rs = np.random.RandomState(30)
+    n_total = 60
+    x = rs.randn(int(n_total / 3), 3)
+    x_df = pd.DataFrame(x, columns=pd.Series(list("XYZ"), name="big"))
+    y = pd.Series(rs.randn(n_total), name="y_data")
+    y_perm = y.reindex(rs.choice(y.index, y.size, replace=False))
+    g = pd.Series(np.repeat(list("abc"), int(n_total / 3)), name="small")
+    h = pd.Series(np.tile(list("mn"), int(n_total / 2)), name="medium")
+    u = pd.Series(np.tile(list("jkh"), int(n_total / 3)))
+    df = pd.DataFrame(dict(y=y, g=g, h=h, u=u))
+    x_df["W"] = g
+
+    def get_box_artists(self, ax):
+
+        if _version_predates(mpl, "3.5.0b0"):
+            return ax.artists
+        else:
+            # Exclude labeled patches, which are for the legend
+            return [p for p in ax.patches if not p.get_label()]
+
+
+class TestCategoricalPlotter(CategoricalFixture):
+
+    def test_wide_df_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test basic wide DataFrame
+        p.establish_variables(data=self.x_df)
+
+        # Check data attribute
+        for x, y, in zip(p.plot_data, self.x_df[["X", "Y", "Z"]].values.T):
+            npt.assert_array_equal(x, y)
+
+        # Check semantic attributes
+        assert p.orient == "v"
+        assert p.plot_hues is None
+        assert p.group_label == "big"
+        assert p.value_label is None
+
+        # Test wide dataframe with forced horizontal orientation
+        p.establish_variables(data=self.x_df, orient="horiz")
+        assert p.orient == "h"
+
+        # Test exception by trying to hue-group with a wide dataframe
+        with pytest.raises(ValueError):
+            p.establish_variables(hue="d", data=self.x_df)
+
+    def test_1d_input_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test basic vector data
+        x_1d_array = self.x.ravel()
+        p.establish_variables(data=x_1d_array)
+        assert len(p.plot_data) == 1
+        assert len(p.plot_data[0]) == self.n_total
+        assert p.group_label is None
+        assert p.value_label is None
+
+        # Test basic vector data in list form
+        x_1d_list = x_1d_array.tolist()
+        p.establish_variables(data=x_1d_list)
+        assert len(p.plot_data) == 1
+        assert len(p.plot_data[0]) == self.n_total
+        assert p.group_label is None
+        assert p.value_label is None
+
+        # Test an object array that looks 1D but isn't
+        x_notreally_1d = np.array([self.x.ravel(),
+                                   self.x.ravel()[:int(self.n_total / 2)]],
+                                  dtype=object)
+        p.establish_variables(data=x_notreally_1d)
+        assert len(p.plot_data) == 2
+        assert len(p.plot_data[0]) == self.n_total
+        assert len(p.plot_data[1]) == self.n_total / 2
+        assert p.group_label is None
+        assert p.value_label is None
+
+    def test_2d_input_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        x = self.x[:, 0]
+
+        # Test vector data that looks 2D but doesn't really have columns
+        p.establish_variables(data=x[:, np.newaxis])
+        assert len(p.plot_data) == 1
+        assert len(p.plot_data[0]) == self.x.shape[0]
+        assert p.group_label is None
+        assert p.value_label is None
+
+        # Test vector data that looks 2D but doesn't really have rows
+        p.establish_variables(data=x[np.newaxis, :])
+        assert len(p.plot_data) == 1
+        assert len(p.plot_data[0]) == self.x.shape[0]
+        assert p.group_label is None
+        assert p.value_label is None
+
+    def test_3d_input_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test that passing actually 3D data raises
+        x = np.zeros((5, 5, 5))
+        with pytest.raises(ValueError):
+            p.establish_variables(data=x)
+
+    def test_list_of_array_input_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test 2D input in list form
+        x_list = self.x.T.tolist()
+        p.establish_variables(data=x_list)
+        assert len(p.plot_data) == 3
+
+        lengths = [len(v_i) for v_i in p.plot_data]
+        assert lengths == [self.n_total / 3] * 3
+
+        assert p.group_label is None
+        assert p.value_label is None
+
+    def test_wide_array_input_data(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test 2D input in array form
+        p.establish_variables(data=self.x)
+        assert np.shape(p.plot_data) == (3, self.n_total / 3)
+        npt.assert_array_equal(p.plot_data, self.x.T)
+
+        assert p.group_label is None
+        assert p.value_label is None
+
+    def test_single_long_direct_inputs(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test passing a series to the x variable
+        p.establish_variables(x=self.y)
+        npt.assert_equal(p.plot_data, [self.y])
+        assert p.orient == "h"
+        assert p.value_label == "y_data"
+        assert p.group_label is None
+
+        # Test passing a series to the y variable
+        p.establish_variables(y=self.y)
+        npt.assert_equal(p.plot_data, [self.y])
+        assert p.orient == "v"
+        assert p.value_label == "y_data"
+        assert p.group_label is None
+
+        # Test passing an array to the y variable
+        p.establish_variables(y=self.y.values)
+        npt.assert_equal(p.plot_data, [self.y])
+        assert p.orient == "v"
+        assert p.group_label is None
+        assert p.value_label is None
+
+        # Test array and series with non-default index
+        x = pd.Series([1, 1, 1, 1], index=[0, 2, 4, 6])
+        y = np.array([1, 2, 3, 4])
+        p.establish_variables(x, y)
+        assert len(p.plot_data[0]) == 4
+
+    def test_single_long_indirect_inputs(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test referencing a DataFrame series in the x variable
+        p.establish_variables(x="y", data=self.df)
+        npt.assert_equal(p.plot_data, [self.y])
+        assert p.orient == "h"
+        assert p.value_label == "y"
+        assert p.group_label is None
+
+        # Test referencing a DataFrame series in the y variable
+        p.establish_variables(y="y", data=self.df)
+        npt.assert_equal(p.plot_data, [self.y])
+        assert p.orient == "v"
+        assert p.value_label == "y"
+        assert p.group_label is None
+
+    def test_longform_groupby(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test a vertically oriented grouped and nested plot
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert len(p.plot_data) == 3
+        assert len(p.plot_hues) == 3
+        assert p.orient == "v"
+        assert p.value_label == "y"
+        assert p.group_label == "g"
+        assert p.hue_title == "h"
+
+        for group, vals in zip(["a", "b", "c"], p.plot_data):
+            npt.assert_array_equal(vals, self.y[self.g == group])
+
+        for group, hues in zip(["a", "b", "c"], p.plot_hues):
+            npt.assert_array_equal(hues, self.h[self.g == group])
+
+        # Test a grouped and nested plot with direct array value data
+        p.establish_variables("g", self.y.values, "h", self.df)
+        assert p.value_label is None
+        assert p.group_label == "g"
+
+        for group, vals in zip(["a", "b", "c"], p.plot_data):
+            npt.assert_array_equal(vals, self.y[self.g == group])
+
+        # Test a grouped and nested plot with direct array hue data
+        p.establish_variables("g", "y", self.h.values, self.df)
+
+        for group, hues in zip(["a", "b", "c"], p.plot_hues):
+            npt.assert_array_equal(hues, self.h[self.g == group])
+
+        # Test categorical grouping data
+        df = self.df.copy()
+        df.g = df.g.astype("category")
+
+        # Test that horizontal orientation is automatically detected
+        p.establish_variables("y", "g", hue="h", data=df)
+        assert len(p.plot_data) == 3
+        assert len(p.plot_hues) == 3
+        assert p.orient == "h"
+        assert p.value_label == "y"
+        assert p.group_label == "g"
+        assert p.hue_title == "h"
+
+        for group, vals in zip(["a", "b", "c"], p.plot_data):
+            npt.assert_array_equal(vals, self.y[self.g == group])
+
+        for group, hues in zip(["a", "b", "c"], p.plot_hues):
+            npt.assert_array_equal(hues, self.h[self.g == group])
+
+        # Test grouped data that matches on index
+        p1 = cat._CategoricalPlotter()
+        p1.establish_variables(self.g, self.y, hue=self.h)
+        p2 = cat._CategoricalPlotter()
+        p2.establish_variables(self.g, self.y.iloc[::-1], self.h)
+        for i, (d1, d2) in enumerate(zip(p1.plot_data, p2.plot_data)):
+            assert np.array_equal(d1.sort_index(), d2.sort_index())
+
+    def test_input_validation(self):
+
+        p = cat._CategoricalPlotter()
+
+        kws = dict(x="g", y="y", hue="h", units="u", data=self.df)
+        for var in ["x", "y", "hue", "units"]:
+            input_kws = kws.copy()
+            input_kws[var] = "bad_input"
+            with pytest.raises(ValueError):
+                p.establish_variables(**input_kws)
+
+    def test_order(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test inferred order from a wide dataframe input
+        p.establish_variables(data=self.x_df)
+        assert p.group_names == ["X", "Y", "Z"]
+
+        # Test specified order with a wide dataframe input
+        p.establish_variables(data=self.x_df, order=["Y", "Z", "X"])
+        assert p.group_names == ["Y", "Z", "X"]
+
+        for group, vals in zip(["Y", "Z", "X"], p.plot_data):
+            npt.assert_array_equal(vals, self.x_df[group])
+
+        with pytest.raises(ValueError):
+            p.establish_variables(data=self.x, order=[1, 2, 0])
+
+        # Test inferred order from a grouped longform input
+        p.establish_variables("g", "y", data=self.df)
+        assert p.group_names == ["a", "b", "c"]
+
+        # Test specified order from a grouped longform input
+        p.establish_variables("g", "y", data=self.df, order=["b", "a", "c"])
+        assert p.group_names == ["b", "a", "c"]
+
+        for group, vals in zip(["b", "a", "c"], p.plot_data):
+            npt.assert_array_equal(vals, self.y[self.g == group])
+
+        # Test inferred order from a grouped input with categorical groups
+        df = self.df.copy()
+        df.g = df.g.astype("category")
+        df.g = df.g.cat.reorder_categories(["c", "b", "a"])
+        p.establish_variables("g", "y", data=df)
+        assert p.group_names == ["c", "b", "a"]
+
+        for group, vals in zip(["c", "b", "a"], p.plot_data):
+            npt.assert_array_equal(vals, self.y[self.g == group])
+
+        df.g = (df.g.cat.add_categories("d")
+                    .cat.reorder_categories(["c", "b", "d", "a"]))
+        p.establish_variables("g", "y", data=df)
+        assert p.group_names == ["c", "b", "d", "a"]
+
+    def test_hue_order(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test inferred hue order
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert p.hue_names == ["m", "n"]
+
+        # Test specified hue order
+        p.establish_variables("g", "y", hue="h", data=self.df,
+                              hue_order=["n", "m"])
+        assert p.hue_names == ["n", "m"]
+
+        # Test inferred hue order from a categorical hue input
+        df = self.df.copy()
+        df.h = df.h.astype("category")
+        df.h = df.h.cat.reorder_categories(["n", "m"])
+        p.establish_variables("g", "y", hue="h", data=df)
+        assert p.hue_names == ["n", "m"]
+
+        df.h = (df.h.cat.add_categories("o")
+                    .cat.reorder_categories(["o", "m", "n"]))
+        p.establish_variables("g", "y", hue="h", data=df)
+        assert p.hue_names == ["o", "m", "n"]
+
+    def test_plot_units(self):
+
+        p = cat._CategoricalPlotter()
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert p.plot_units is None
+
+        p.establish_variables("g", "y", hue="h", data=self.df, units="u")
+        for group, units in zip(["a", "b", "c"], p.plot_units):
+            npt.assert_array_equal(units, self.u[self.g == group])
+
+    def test_default_palettes(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test palette mapping the x position
+        p.establish_variables("g", "y", data=self.df)
+        p.establish_colors(None, None, 1)
+        assert p.colors == palettes.color_palette(n_colors=3)
+
+        # Test palette mapping the hue position
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        p.establish_colors(None, None, 1)
+        assert p.colors == palettes.color_palette(n_colors=2)
+
+    def test_default_palette_with_many_levels(self):
+
+        with palettes.color_palette(["blue", "red"], 2):
+            p = cat._CategoricalPlotter()
+            p.establish_variables("g", "y", data=self.df)
+            p.establish_colors(None, None, 1)
+            npt.assert_array_equal(p.colors,
+                                   palettes.husl_palette(3, l=.7))  # noqa
+
+    def test_specific_color(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test the same color for each x position
+        p.establish_variables("g", "y", data=self.df)
+        p.establish_colors("blue", None, 1)
+        blue_rgb = mpl.colors.colorConverter.to_rgb("blue")
+        assert p.colors == [blue_rgb] * 3
+
+        # Test a color-based blend for the hue mapping
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        p.establish_colors("#ff0022", None, 1)
+        rgba_array = np.array(palettes.light_palette("#ff0022", 2))
+        npt.assert_array_almost_equal(p.colors,
+                                      rgba_array[:, :3])
+
+    def test_specific_palette(self):
+
+        p = cat._CategoricalPlotter()
+
+        # Test palette mapping the x position
+        p.establish_variables("g", "y", data=self.df)
+        p.establish_colors(None, "dark", 1)
+        assert p.colors == palettes.color_palette("dark", 3)
+
+        # Test that non-None `color` and `hue` raises an error
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        p.establish_colors(None, "muted", 1)
+        assert p.colors == palettes.color_palette("muted", 2)
+
+        # Test that specified palette overrides specified color
+        p = cat._CategoricalPlotter()
+        p.establish_variables("g", "y", data=self.df)
+        p.establish_colors("blue", "deep", 1)
+        assert p.colors == palettes.color_palette("deep", 3)
+
+    def test_dict_as_palette(self):
+
+        p = cat._CategoricalPlotter()
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        pal = {"m": (0, 0, 1), "n": (1, 0, 0)}
+        p.establish_colors(None, pal, 1)
+        assert p.colors == [(0, 0, 1), (1, 0, 0)]
+
+    def test_palette_desaturation(self):
+
+        p = cat._CategoricalPlotter()
+        p.establish_variables("g", "y", data=self.df)
+        p.establish_colors((0, 0, 1), None, .5)
+        assert p.colors == [(.25, .25, .75)] * 3
+
+        p.establish_colors(None, [(0, 0, 1), (1, 0, 0), "w"], .5)
+        assert p.colors == [(.25, .25, .75), (.75, .25, .25), (1, 1, 1)]
+
+
+class TestCategoricalStatPlotter(CategoricalFixture):
+
+    def test_no_bootstrappig(self):
+
+        p = cat._CategoricalStatPlotter()
+        p.establish_variables("g", "y", data=self.df)
+        p.estimate_statistic("mean", None, 100, None)
+        npt.assert_array_equal(p.confint, np.array([]))
+
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        p.estimate_statistic(np.mean, None, 100, None)
+        npt.assert_array_equal(p.confint, np.array([[], [], []]))
+
+    def test_single_layer_stats(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y)
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+
+        assert p.statistic.shape == (3,)
+        assert p.confint.shape == (3, 2)
+
+        npt.assert_array_almost_equal(p.statistic,
+                                      y.groupby(g).mean())
+
+        for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):
+            sem = grp_y.std() / np.sqrt(len(grp_y))
+            mean = grp_y.mean()
+            half_ci = _normal_quantile_func(.975) * sem
+            ci_want = mean - half_ci, mean + half_ci
+            npt.assert_array_almost_equal(ci_want, ci, 2)
+
+    def test_single_layer_stats_with_units(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 90))
+        y = pd.Series(np.random.RandomState(0).randn(270))
+        u = pd.Series(np.repeat(np.tile(list("xyz"), 30), 3))
+        y[u == "x"] -= 3
+        y[u == "y"] += 3
+
+        p.establish_variables(g, y)
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+        stat1, ci1 = p.statistic, p.confint
+
+        p.establish_variables(g, y, units=u)
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+        stat2, ci2 = p.statistic, p.confint
+
+        npt.assert_array_equal(stat1, stat2)
+        ci1_size = ci1[:, 1] - ci1[:, 0]
+        ci2_size = ci2[:, 1] - ci2[:, 0]
+        npt.assert_array_less(ci1_size, ci2_size)
+
+    def test_single_layer_stats_with_missing_data(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y, order=list("abdc"))
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+
+        assert p.statistic.shape == (4,)
+        assert p.confint.shape == (4, 2)
+
+        rows = g == "b"
+        mean = y[rows].mean()
+        sem = y[rows].std() / np.sqrt(rows.sum())
+        half_ci = _normal_quantile_func(.975) * sem
+        ci = mean - half_ci, mean + half_ci
+        npt.assert_almost_equal(p.statistic[1], mean)
+        npt.assert_array_almost_equal(p.confint[1], ci, 2)
+
+        npt.assert_equal(p.statistic[2], np.nan)
+        npt.assert_array_equal(p.confint[2], (np.nan, np.nan))
+
+    def test_nested_stats(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        h = pd.Series(np.tile(list("xy"), 150))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y, h)
+        p.estimate_statistic("mean", ("ci", 95), 50000, None)
+
+        assert p.statistic.shape == (3, 2)
+        assert p.confint.shape == (3, 2, 2)
+
+        npt.assert_array_almost_equal(p.statistic,
+                                      y.groupby([g, h]).mean().unstack())
+
+        for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):
+            for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):
+                sem = hue_y.std() / np.sqrt(len(hue_y))
+                mean = hue_y.mean()
+                half_ci = _normal_quantile_func(.975) * sem
+                ci_want = mean - half_ci, mean + half_ci
+                npt.assert_array_almost_equal(ci_want, ci, 2)
+
+    def test_bootstrap_seed(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        h = pd.Series(np.tile(list("xy"), 150))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y, h)
+        p.estimate_statistic("mean", ("ci", 95), 1000, 0)
+        confint_1 = p.confint
+        p.estimate_statistic("mean", ("ci", 95), 1000, 0)
+        confint_2 = p.confint
+
+        npt.assert_array_equal(confint_1, confint_2)
+
+    def test_nested_stats_with_units(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 90))
+        h = pd.Series(np.tile(list("xy"), 135))
+        u = pd.Series(np.repeat(list("ijkijk"), 45))
+        y = pd.Series(np.random.RandomState(0).randn(270))
+        y[u == "i"] -= 3
+        y[u == "k"] += 3
+
+        p.establish_variables(g, y, h)
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+        stat1, ci1 = p.statistic, p.confint
+
+        p.establish_variables(g, y, h, units=u)
+        p.estimate_statistic("mean", ("ci", 95), 10000, None)
+        stat2, ci2 = p.statistic, p.confint
+
+        npt.assert_array_equal(stat1, stat2)
+        ci1_size = ci1[:, 0, 1] - ci1[:, 0, 0]
+        ci2_size = ci2[:, 0, 1] - ci2[:, 0, 0]
+        npt.assert_array_less(ci1_size, ci2_size)
+
+    def test_nested_stats_with_missing_data(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+        h = pd.Series(np.tile(list("xy"), 150))
+
+        p.establish_variables(g, y, h,
+                              order=list("abdc"),
+                              hue_order=list("zyx"))
+        p.estimate_statistic("mean", ("ci", 95), 50000, None)
+
+        assert p.statistic.shape == (4, 3)
+        assert p.confint.shape == (4, 3, 2)
+
+        rows = (g == "b") & (h == "x")
+        mean = y[rows].mean()
+        sem = y[rows].std() / np.sqrt(rows.sum())
+        half_ci = _normal_quantile_func(.975) * sem
+        ci = mean - half_ci, mean + half_ci
+        npt.assert_almost_equal(p.statistic[1, 2], mean)
+        npt.assert_array_almost_equal(p.confint[1, 2], ci, 2)
+
+        npt.assert_array_equal(p.statistic[:, 0], [np.nan] * 4)
+        npt.assert_array_equal(p.statistic[2], [np.nan] * 3)
+        npt.assert_array_equal(p.confint[:, 0],
+                               np.zeros((4, 2)) * np.nan)
+        npt.assert_array_equal(p.confint[2],
+                               np.zeros((3, 2)) * np.nan)
+
+    def test_sd_error_bars(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y)
+        p.estimate_statistic(np.mean, "sd", None, None)
+
+        assert p.statistic.shape == (3,)
+        assert p.confint.shape == (3, 2)
+
+        npt.assert_array_almost_equal(p.statistic,
+                                      y.groupby(g).mean())
+
+        for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):
+            mean = grp_y.mean()
+            half_ci = np.std(grp_y)
+            ci_want = mean - half_ci, mean + half_ci
+            npt.assert_array_almost_equal(ci_want, ci, 2)
+
+    def test_nested_sd_error_bars(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        g = pd.Series(np.repeat(list("abc"), 100))
+        h = pd.Series(np.tile(list("xy"), 150))
+        y = pd.Series(np.random.RandomState(0).randn(300))
+
+        p.establish_variables(g, y, h)
+        p.estimate_statistic(np.mean, "sd", None, None)
+
+        assert p.statistic.shape == (3, 2)
+        assert p.confint.shape == (3, 2, 2)
+
+        npt.assert_array_almost_equal(p.statistic,
+                                      y.groupby([g, h]).mean().unstack())
+
+        for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):
+            for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):
+                mean = hue_y.mean()
+                half_ci = np.std(hue_y)
+                ci_want = mean - half_ci, mean + half_ci
+                npt.assert_array_almost_equal(ci_want, ci, 2)
+
+    def test_draw_cis(self):
+
+        p = cat._CategoricalStatPlotter()
+
+        # Test vertical CIs
+        p.orient = "v"
+
+        f, ax = plt.subplots()
+        at_group = [0, 1]
+        confints = [(.5, 1.5), (.25, .8)]
+        colors = [".2", ".3"]
+        p.draw_confints(ax, at_group, confints, colors)
+
+        lines = ax.lines
+        for line, at, ci, c in zip(lines, at_group, confints, colors):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, [at, at])
+            npt.assert_array_equal(y, ci)
+            assert line.get_color() == c
+
+        plt.close("all")
+
+        # Test horizontal CIs
+        p.orient = "h"
+
+        f, ax = plt.subplots()
+        p.draw_confints(ax, at_group, confints, colors)
+
+        lines = ax.lines
+        for line, at, ci, c in zip(lines, at_group, confints, colors):
+            x, y = line.get_xydata().T
+            npt.assert_array_equal(x, ci)
+            npt.assert_array_equal(y, [at, at])
+            assert line.get_color() == c
+
+        plt.close("all")
+
+        # Test vertical CIs with endcaps
+        p.orient = "v"
+
+        f, ax = plt.subplots()
+        p.draw_confints(ax, at_group, confints, colors, capsize=0.3)
+        capline = ax.lines[len(ax.lines) - 1]
+        caplinestart = capline.get_xdata()[0]
+        caplineend = capline.get_xdata()[1]
+        caplinelength = abs(caplineend - caplinestart)
+        assert caplinelength == approx(0.3)
+        assert len(ax.lines) == 6
+
+        plt.close("all")
+
+        # Test horizontal CIs with endcaps
+        p.orient = "h"
+
+        f, ax = plt.subplots()
+        p.draw_confints(ax, at_group, confints, colors, capsize=0.3)
+        capline = ax.lines[len(ax.lines) - 1]
+        caplinestart = capline.get_ydata()[0]
+        caplineend = capline.get_ydata()[1]
+        caplinelength = abs(caplineend - caplinestart)
+        assert caplinelength == approx(0.3)
+        assert len(ax.lines) == 6
+
+        # Test extra keyword arguments
+        f, ax = plt.subplots()
+        p.draw_confints(ax, at_group, confints, colors, lw=4)
+        line = ax.lines[0]
+        assert line.get_linewidth() == 4
+
+        plt.close("all")
+
+        # Test errwidth is set appropriately
+        f, ax = plt.subplots()
+        p.draw_confints(ax, at_group, confints, colors, errwidth=2)
+        capline = ax.lines[len(ax.lines) - 1]
+        assert capline._linewidth == 2
+        assert len(ax.lines) == 2
+
+        plt.close("all")
+
+
+class TestBoxPlotter(CategoricalFixture):
+
+    default_kws = dict(x=None, y=None, hue=None, data=None,
+                       order=None, hue_order=None,
+                       orient=None, color=None, palette=None,
+                       saturation=.75, width=.8, dodge=True,
+                       fliersize=5, linewidth=None)
+
+    def test_nested_width(self):
+
+        kws = self.default_kws.copy()
+        p = cat._BoxPlotter(**kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert p.nested_width == .4 * .98
+
+        kws = self.default_kws.copy()
+        kws["width"] = .6
+        p = cat._BoxPlotter(**kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert p.nested_width == .3 * .98
+
+        kws = self.default_kws.copy()
+        kws["dodge"] = False
+        p = cat._BoxPlotter(**kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        assert p.nested_width == .8
+
+    def test_hue_offsets(self):
+
+        p = cat._BoxPlotter(**self.default_kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        npt.assert_array_equal(p.hue_offsets, [-.2, .2])
+
+        kws = self.default_kws.copy()
+        kws["width"] = .6
+        p = cat._BoxPlotter(**kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        npt.assert_array_equal(p.hue_offsets, [-.15, .15])
+
+        p = cat._BoxPlotter(**kws)
+        p.establish_variables("h", "y", "g", data=self.df)
+        npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])
+
+    def test_axes_data(self):
+
+        ax = cat.boxplot(x="g", y="y", data=self.df)
+        assert len(self.get_box_artists(ax)) == 3
+
+        plt.close("all")
+
+        ax = cat.boxplot(x="g", y="y", hue="h", data=self.df)
+        assert len(self.get_box_artists(ax)) == 6
+
+        plt.close("all")
+
+    def test_box_colors(self):
+
+        ax = cat.boxplot(x="g", y="y", data=self.df, saturation=1)
+        pal = palettes.color_palette(n_colors=3)
+        assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],
+                          pal)
+
+        plt.close("all")
+
+        ax = cat.boxplot(x="g", y="y", hue="h", data=self.df, saturation=1)
+        pal = palettes.color_palette(n_colors=2)
+        assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],
+                          pal * 3)
+
+        plt.close("all")
+
+    def test_draw_missing_boxes(self):
+
+        ax = cat.boxplot(x="g", y="y", data=self.df,
+                         order=["a", "b", "c", "d"])
+        assert len(self.get_box_artists(ax)) == 3
+
+    def test_missing_data(self):
+
+        x = ["a", "a", "b", "b", "c", "c", "d", "d"]
+        h = ["x", "y", "x", "y", "x", "y", "x", "y"]
+        y = self.rs.randn(8)
+        y[-2:] = np.nan
+
+        ax = cat.boxplot(x=x, y=y)
+        assert len(self.get_box_artists(ax)) == 3
+
+        plt.close("all")
+
+        y[-1] = 0
+        ax = cat.boxplot(x=x, y=y, hue=h)
+        assert len(self.get_box_artists(ax)) == 7
+
+        plt.close("all")
+
+    def test_unaligned_index(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        cat.boxplot(x=self.g, y=self.y, ax=ax1)
+        cat.boxplot(x=self.g, y=self.y_perm, ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert np.array_equal(l1.get_xydata(), l2.get_xydata())
+
+        f, (ax1, ax2) = plt.subplots(2)
+        hue_order = self.h.unique()
+        cat.boxplot(x=self.g, y=self.y, hue=self.h,
+                    hue_order=hue_order, ax=ax1)
+        cat.boxplot(x=self.g, y=self.y_perm, hue=self.h,
+                    hue_order=hue_order, ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert np.array_equal(l1.get_xydata(), l2.get_xydata())
+
+    def test_boxplots(self):
+
+        # Smoke test the high level boxplot options
+
+        cat.boxplot(x="y", data=self.df)
+        plt.close("all")
+
+        cat.boxplot(y="y", data=self.df)
+        plt.close("all")
+
+        cat.boxplot(x="g", y="y", data=self.df)
+        plt.close("all")
+
+        cat.boxplot(x="y", y="g", data=self.df, orient="h")
+        plt.close("all")
+
+        cat.boxplot(x="g", y="y", hue="h", data=self.df)
+        plt.close("all")
+
+        cat.boxplot(x="g", y="y", hue="h", order=list("nabc"), data=self.df)
+        plt.close("all")
+
+        cat.boxplot(x="g", y="y", hue="h", hue_order=list("omn"), data=self.df)
+        plt.close("all")
+
+        cat.boxplot(x="y", y="g", hue="h", data=self.df, orient="h")
+        plt.close("all")
+
+    def test_axes_annotation(self):
+
+        ax = cat.boxplot(x="g", y="y", data=self.df)
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        assert ax.get_xlim() == (-.5, 2.5)
+        npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],
+                               ["a", "b", "c"])
+
+        plt.close("all")
+
+        ax = cat.boxplot(x="g", y="y", hue="h", data=self.df)
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],
+                               ["a", "b", "c"])
+        npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],
+                               ["m", "n"])
+
+        plt.close("all")
+
+        ax = cat.boxplot(x="y", y="g", data=self.df, orient="h")
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        assert ax.get_ylim() == (2.5, -.5)
+        npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],
+                               ["a", "b", "c"])
+
+        plt.close("all")
+
+
+class TestViolinPlotter(CategoricalFixture):
+
+    default_kws = dict(x=None, y=None, hue=None, data=None,
+                       order=None, hue_order=None,
+                       bw="scott", cut=2, scale="area", scale_hue=True,
+                       gridsize=100, width=.8, inner="box", split=False,
+                       dodge=True, orient=None, linewidth=None,
+                       color=None, palette=None, saturation=.75)
+
+    def test_split_error(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(x="h", y="y", hue="g", data=self.df, split=True))
+
+        with pytest.raises(ValueError):
+            cat._ViolinPlotter(**kws)
+
+    def test_no_observations(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+
+        x = ["a", "a", "b"]
+        y = self.rs.randn(3)
+        y[-1] = np.nan
+        p.establish_variables(x, y)
+        p.estimate_densities("scott", 2, "area", True, 20)
+
+        assert len(p.support[0]) == 20
+        assert len(p.support[1]) == 0
+
+        assert len(p.density[0]) == 20
+        assert len(p.density[1]) == 1
+
+        assert p.density[1].item() == 1
+
+        p.estimate_densities("scott", 2, "count", True, 20)
+        assert p.density[1].item() == 0
+
+        x = ["a"] * 4 + ["b"] * 2
+        y = self.rs.randn(6)
+        h = ["m", "n"] * 2 + ["m"] * 2
+
+        p.establish_variables(x, y, hue=h)
+        p.estimate_densities("scott", 2, "area", True, 20)
+
+        assert len(p.support[1][0]) == 20
+        assert len(p.support[1][1]) == 0
+
+        assert len(p.density[1][0]) == 20
+        assert len(p.density[1][1]) == 1
+
+        assert p.density[1][1].item() == 1
+
+        p.estimate_densities("scott", 2, "count", False, 20)
+        assert p.density[1][1].item() == 0
+
+    def test_single_observation(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+
+        x = ["a", "a", "b"]
+        y = self.rs.randn(3)
+        p.establish_variables(x, y)
+        p.estimate_densities("scott", 2, "area", True, 20)
+
+        assert len(p.support[0]) == 20
+        assert len(p.support[1]) == 1
+
+        assert len(p.density[0]) == 20
+        assert len(p.density[1]) == 1
+
+        assert p.density[1].item() == 1
+
+        p.estimate_densities("scott", 2, "count", True, 20)
+        assert p.density[1].item() == .5
+
+        x = ["b"] * 4 + ["a"] * 3
+        y = self.rs.randn(7)
+        h = (["m", "n"] * 4)[:-1]
+
+        p.establish_variables(x, y, hue=h)
+        p.estimate_densities("scott", 2, "area", True, 20)
+
+        assert len(p.support[1][0]) == 20
+        assert len(p.support[1][1]) == 1
+
+        assert len(p.density[1][0]) == 20
+        assert len(p.density[1][1]) == 1
+
+        assert p.density[1][1].item() == 1
+
+        p.estimate_densities("scott", 2, "count", False, 20)
+        assert p.density[1][1].item() == .5
+
+    def test_dwidth(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(x="g", y="y", data=self.df))
+
+        p = cat._ViolinPlotter(**kws)
+        assert p.dwidth == .4
+
+        kws.update(dict(width=.4))
+        p = cat._ViolinPlotter(**kws)
+        assert p.dwidth == .2
+
+        kws.update(dict(hue="h", width=.8))
+        p = cat._ViolinPlotter(**kws)
+        assert p.dwidth == .2
+
+        kws.update(dict(split=True))
+        p = cat._ViolinPlotter(**kws)
+        assert p.dwidth == .4
+
+    def test_scale_area(self):
+
+        kws = self.default_kws.copy()
+        kws["scale"] = "area"
+        p = cat._ViolinPlotter(**kws)
+
+        # Test single layer of grouping
+        p.hue_names = None
+        density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]
+        max_before = np.array([d.max() for d in density])
+        p.scale_area(density, max_before, False)
+        max_after = np.array([d.max() for d in density])
+        assert max_after[0] == 1
+
+        before_ratio = max_before[1] / max_before[0]
+        after_ratio = max_after[1] / max_after[0]
+        assert before_ratio == after_ratio
+
+        # Test nested grouping scaling across all densities
+        p.hue_names = ["foo", "bar"]
+        density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],
+                   [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]
+
+        max_before = np.array([[r.max() for r in row] for row in density])
+        p.scale_area(density, max_before, False)
+        max_after = np.array([[r.max() for r in row] for row in density])
+        assert max_after[0, 0] == 1
+
+        before_ratio = max_before[1, 1] / max_before[0, 0]
+        after_ratio = max_after[1, 1] / max_after[0, 0]
+        assert before_ratio == after_ratio
+
+        # Test nested grouping scaling within hue
+        p.hue_names = ["foo", "bar"]
+        density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],
+                   [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]
+
+        max_before = np.array([[r.max() for r in row] for row in density])
+        p.scale_area(density, max_before, True)
+        max_after = np.array([[r.max() for r in row] for row in density])
+        assert max_after[0, 0] == 1
+        assert max_after[1, 0] == 1
+
+        before_ratio = max_before[1, 1] / max_before[1, 0]
+        after_ratio = max_after[1, 1] / max_after[1, 0]
+        assert before_ratio == after_ratio
+
+    def test_scale_width(self):
+
+        kws = self.default_kws.copy()
+        kws["scale"] = "width"
+        p = cat._ViolinPlotter(**kws)
+
+        # Test single layer of grouping
+        p.hue_names = None
+        density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]
+        p.scale_width(density)
+        max_after = np.array([d.max() for d in density])
+        npt.assert_array_equal(max_after, [1, 1])
+
+        # Test nested grouping
+        p.hue_names = ["foo", "bar"]
+        density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],
+                   [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]
+
+        p.scale_width(density)
+        max_after = np.array([[r.max() for r in row] for row in density])
+        npt.assert_array_equal(max_after, [[1, 1], [1, 1]])
+
+    def test_scale_count(self):
+
+        kws = self.default_kws.copy()
+        kws["scale"] = "count"
+        p = cat._ViolinPlotter(**kws)
+
+        # Test single layer of grouping
+        p.hue_names = None
+        density = [self.rs.uniform(0, .8, 20), self.rs.uniform(0, .2, 40)]
+        counts = np.array([20, 40])
+        p.scale_count(density, counts, False)
+        max_after = np.array([d.max() for d in density])
+        npt.assert_array_equal(max_after, [.5, 1])
+
+        # Test nested grouping scaling across all densities
+        p.hue_names = ["foo", "bar"]
+        density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],
+                   [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]
+
+        counts = np.array([[5, 40], [100, 50]])
+        p.scale_count(density, counts, False)
+        max_after = np.array([[r.max() for r in row] for row in density])
+        npt.assert_array_equal(max_after, [[.05, .4], [1, .5]])
+
+        # Test nested grouping scaling within hue
+        p.hue_names = ["foo", "bar"]
+        density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],
+                   [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]
+
+        counts = np.array([[5, 40], [100, 50]])
+        p.scale_count(density, counts, True)
+        max_after = np.array([[r.max() for r in row] for row in density])
+        npt.assert_array_equal(max_after, [[.125, 1], [1, .5]])
+
+    def test_bad_scale(self):
+
+        kws = self.default_kws.copy()
+        kws["scale"] = "not_a_scale_type"
+        with pytest.raises(ValueError):
+            cat._ViolinPlotter(**kws)
+
+    def test_kde_fit(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+        data = self.y
+        data_std = data.std(ddof=1)
+
+        # Test reference rule bandwidth
+        kde, bw = p.fit_kde(data, "scott")
+        assert kde.factor == kde.scotts_factor()
+        assert bw == kde.scotts_factor() * data_std
+
+        # Test numeric scale factor
+        kde, bw = p.fit_kde(self.y, .2)
+        assert kde.factor == .2
+        assert bw == .2 * data_std
+
+    def test_draw_to_density(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+        # p.dwidth will be 1 for easier testing
+        p.width = 2
+
+        # Test vertical plots
+        support = np.array([.2, .6])
+        density = np.array([.1, .4])
+
+        # Test full vertical plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .5, support, density, False)
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [.99 * -.4, .99 * .4])
+        npt.assert_array_equal(y, [.5, .5])
+        plt.close("all")
+
+        # Test left vertical plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .5, support, density, "left")
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [.99 * -.4, 0])
+        npt.assert_array_equal(y, [.5, .5])
+        plt.close("all")
+
+        # Test right vertical plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .5, support, density, "right")
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [0, .99 * .4])
+        npt.assert_array_equal(y, [.5, .5])
+        plt.close("all")
+
+        # Switch orientation to test horizontal plots
+        p.orient = "h"
+        support = np.array([.2, .5])
+        density = np.array([.3, .7])
+
+        # Test full horizontal plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .6, support, density, False)
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [.6, .6])
+        npt.assert_array_equal(y, [.99 * -.7, .99 * .7])
+        plt.close("all")
+
+        # Test left horizontal plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .6, support, density, "left")
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [.6, .6])
+        npt.assert_array_equal(y, [.99 * -.7, 0])
+        plt.close("all")
+
+        # Test right horizontal plot
+        _, ax = plt.subplots()
+        p.draw_to_density(ax, 0, .6, support, density, "right")
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [.6, .6])
+        npt.assert_array_equal(y, [0, .99 * .7])
+        plt.close("all")
+
+    def test_draw_single_observations(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+        p.width = 2
+
+        # Test vertical plot
+        _, ax = plt.subplots()
+        p.draw_single_observation(ax, 1, 1.5, 1)
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [0, 2])
+        npt.assert_array_equal(y, [1.5, 1.5])
+        plt.close("all")
+
+        # Test horizontal plot
+        p.orient = "h"
+        _, ax = plt.subplots()
+        p.draw_single_observation(ax, 2, 2.2, .5)
+        x, y = ax.lines[0].get_xydata().T
+        npt.assert_array_equal(x, [2.2, 2.2])
+        npt.assert_array_equal(y, [1.5, 2.5])
+        plt.close("all")
+
+    def test_draw_box_lines(self):
+
+        # Test vertical plot
+        kws = self.default_kws.copy()
+        kws.update(dict(y="y", data=self.df, inner=None))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_box_lines(ax, self.y, 0)
+        assert len(ax.lines) == 2
+
+        q25, q50, q75 = np.percentile(self.y, [25, 50, 75])
+        _, y = ax.lines[1].get_xydata().T
+        npt.assert_array_equal(y, [q25, q75])
+
+        _, y = ax.collections[0].get_offsets().T
+        assert y == q50
+
+        plt.close("all")
+
+        # Test horizontal plot
+        kws = self.default_kws.copy()
+        kws.update(dict(x="y", data=self.df, inner=None))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_box_lines(ax, self.y, 0)
+        assert len(ax.lines) == 2
+
+        q25, q50, q75 = np.percentile(self.y, [25, 50, 75])
+        x, _ = ax.lines[1].get_xydata().T
+        npt.assert_array_equal(x, [q25, q75])
+
+        x, _ = ax.collections[0].get_offsets().T
+        assert x == q50
+
+        plt.close("all")
+
+    def test_draw_quartiles(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(y="y", data=self.df, inner=None))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_quartiles(ax, self.y, p.support[0], p.density[0], 0)
+        for val, line in zip(np.percentile(self.y, [25, 50, 75]), ax.lines):
+            _, y = line.get_xydata().T
+            npt.assert_array_equal(y, [val, val])
+
+    def test_draw_points(self):
+
+        p = cat._ViolinPlotter(**self.default_kws)
+
+        # Test vertical plot
+        _, ax = plt.subplots()
+        p.draw_points(ax, self.y, 0)
+        x, y = ax.collections[0].get_offsets().T
+        npt.assert_array_equal(x, np.zeros_like(self.y))
+        npt.assert_array_equal(y, self.y)
+        plt.close("all")
+
+        # Test horizontal plot
+        p.orient = "h"
+        _, ax = plt.subplots()
+        p.draw_points(ax, self.y, 0)
+        x, y = ax.collections[0].get_offsets().T
+        npt.assert_array_equal(x, self.y)
+        npt.assert_array_equal(y, np.zeros_like(self.y))
+        plt.close("all")
+
+    def test_draw_sticks(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(y="y", data=self.df, inner=None))
+        p = cat._ViolinPlotter(**kws)
+
+        # Test vertical plot
+        _, ax = plt.subplots()
+        p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)
+        for val, line in zip(self.y, ax.lines):
+            _, y = line.get_xydata().T
+            npt.assert_array_equal(y, [val, val])
+        plt.close("all")
+
+        # Test horizontal plot
+        p.orient = "h"
+        _, ax = plt.subplots()
+        p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)
+        for val, line in zip(self.y, ax.lines):
+            x, _ = line.get_xydata().T
+            npt.assert_array_equal(x, [val, val])
+        plt.close("all")
+
+    def test_validate_inner(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(inner="bad_inner"))
+        with pytest.raises(ValueError):
+            cat._ViolinPlotter(**kws)
+
+    def test_draw_violinplots(self):
+
+        kws = self.default_kws.copy()
+
+        # Test single vertical violin
+        kws.update(dict(y="y", data=self.df, inner=None,
+                        saturation=1, color=(1, 0, 0, 1)))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 1
+        npt.assert_array_equal(ax.collections[0].get_facecolors(),
+                               [(1, 0, 0, 1)])
+        plt.close("all")
+
+        # Test single horizontal violin
+        kws.update(dict(x="y", y=None, color=(0, 1, 0, 1)))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 1
+        npt.assert_array_equal(ax.collections[0].get_facecolors(),
+                               [(0, 1, 0, 1)])
+        plt.close("all")
+
+        # Test multiple vertical violins
+        kws.update(dict(x="g", y="y", color=None,))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 3
+        for violin, color in zip(ax.collections, palettes.color_palette()):
+            npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)
+        plt.close("all")
+
+        # Test multiple violins with hue nesting
+        kws.update(dict(hue="h"))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 6
+        for violin, color in zip(ax.collections,
+                                 palettes.color_palette(n_colors=2) * 3):
+            npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)
+        plt.close("all")
+
+        # Test multiple split violins
+        kws.update(dict(split=True, palette="muted"))
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 6
+        for violin, color in zip(ax.collections,
+                                 palettes.color_palette("muted",
+                                                        n_colors=2) * 3):
+            npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)
+        plt.close("all")
+
+    def test_draw_violinplots_no_observations(self):
+
+        kws = self.default_kws.copy()
+        kws["inner"] = None
+
+        # Test single layer of grouping
+        x = ["a", "a", "b"]
+        y = self.rs.randn(3)
+        y[-1] = np.nan
+        kws.update(x=x, y=y)
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == 0
+        plt.close("all")
+
+        # Test nested hue grouping
+        x = ["a"] * 4 + ["b"] * 2
+        y = self.rs.randn(6)
+        h = ["m", "n"] * 2 + ["m"] * 2
+        kws.update(x=x, y=y, hue=h)
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 3
+        assert len(ax.lines) == 0
+        plt.close("all")
+
+    def test_draw_violinplots_single_observations(self):
+
+        kws = self.default_kws.copy()
+        kws["inner"] = None
+
+        # Test single layer of grouping
+        x = ["a", "a", "b"]
+        y = self.rs.randn(3)
+        kws.update(x=x, y=y)
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == 1
+        plt.close("all")
+
+        # Test nested hue grouping
+        x = ["b"] * 4 + ["a"] * 3
+        y = self.rs.randn(7)
+        h = (["m", "n"] * 4)[:-1]
+        kws.update(x=x, y=y, hue=h)
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 3
+        assert len(ax.lines) == 1
+        plt.close("all")
+
+        # Test nested hue grouping with split
+        kws["split"] = True
+        p = cat._ViolinPlotter(**kws)
+
+        _, ax = plt.subplots()
+        p.draw_violins(ax)
+        assert len(ax.collections) == 3
+        assert len(ax.lines) == 1
+        plt.close("all")
+
+    def test_violinplots(self):
+
+        # Smoke test the high level violinplot options
+
+        cat.violinplot(x="y", data=self.df)
+        plt.close("all")
+
+        cat.violinplot(y="y", data=self.df)
+        plt.close("all")
+
+        cat.violinplot(x="g", y="y", data=self.df)
+        plt.close("all")
+
+        cat.violinplot(x="y", y="g", data=self.df, orient="h")
+        plt.close("all")
+
+        cat.violinplot(x="g", y="y", hue="h", data=self.df)
+        plt.close("all")
+
+        order = list("nabc")
+        cat.violinplot(x="g", y="y", hue="h", order=order, data=self.df)
+        plt.close("all")
+
+        order = list("omn")
+        cat.violinplot(x="g", y="y", hue="h", hue_order=order, data=self.df)
+        plt.close("all")
+
+        cat.violinplot(x="y", y="g", hue="h", data=self.df, orient="h")
+        plt.close("all")
+
+        for inner in ["box", "quart", "point", "stick", None]:
+            cat.violinplot(x="g", y="y", data=self.df, inner=inner)
+            plt.close("all")
+
+            cat.violinplot(x="g", y="y", hue="h", data=self.df, inner=inner)
+            plt.close("all")
+
+            cat.violinplot(x="g", y="y", hue="h", data=self.df,
+                           inner=inner, split=True)
+            plt.close("all")
+
+    def test_split_one_each(self, rng):
+
+        x = np.repeat([0, 1], 5)
+        y = rng.normal(0, 1, 10)
+        ax = cat.violinplot(x=x, y=y, hue=x, split=True, inner="box")
+        assert len(ax.lines) == 4
+
+
+# ====================================================================================
+# ====================================================================================
+
+
+class SharedAxesLevelTests:
+
+    def test_color(self, long_df):
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C0")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", ax=ax)
+        self.func(data=long_df, x="a", y="y", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C1")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", color="C2", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C2")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", color="C3", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C3")
+
+    def test_two_calls(self):
+
+        ax = plt.figure().subplots()
+        self.func(x=["a", "b", "c"], y=[1, 2, 3], ax=ax)
+        self.func(x=["e", "f"], y=[4, 5], ax=ax)
+        assert ax.get_xlim() == (-.5, 4.5)
+
+
+class SharedScatterTests(SharedAxesLevelTests):
+    """Tests functionality common to stripplot and swarmplot."""
+
+    def get_last_color(self, ax):
+
+        colors = ax.collections[-1].get_facecolors()
+        unique_colors = np.unique(colors, axis=0)
+        assert len(unique_colors) == 1
+        return to_rgba(unique_colors.squeeze())
+
+    # ------------------------------------------------------------------------------
+
+    def test_color(self, long_df):
+
+        super().test_color(long_df)
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", facecolor="C4", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C4")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="a", y="y", fc="C5", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C5")
+
+    def test_supplied_color_array(self, long_df):
+
+        cmap = get_colormap("Blues")
+        norm = mpl.colors.Normalize()
+        colors = cmap(norm(long_df["y"].to_numpy()))
+
+        keys = ["c", "fc", "facecolor", "facecolors"]
+
+        for key in keys:
+
+            ax = plt.figure().subplots()
+            self.func(x=long_df["y"], **{key: colors})
+            _draw_figure(ax.figure)
+            assert_array_equal(ax.collections[0].get_facecolors(), colors)
+
+        ax = plt.figure().subplots()
+        self.func(x=long_df["y"], c=long_df["y"], cmap=cmap)
+        _draw_figure(ax.figure)
+        assert_array_equal(ax.collections[0].get_facecolors(), colors)
+
+    @pytest.mark.parametrize(
+        "orient,data_type",
+        itertools.product(["h", "v"], ["dataframe", "dict"]),
+    )
+    def test_wide(self, wide_df, orient, data_type):
+
+        if data_type == "dict":
+            wide_df = {k: v.to_numpy() for k, v in wide_df.items()}
+
+        ax = self.func(data=wide_df, orient=orient)
+        _draw_figure(ax.figure)
+        palette = color_palette()
+
+        cat_idx = 0 if orient == "v" else 1
+        val_idx = int(not cat_idx)
+
+        axis_objs = ax.xaxis, ax.yaxis
+        cat_axis = axis_objs[cat_idx]
+
+        for i, label in enumerate(cat_axis.get_majorticklabels()):
+
+            key = label.get_text()
+            points = ax.collections[i]
+            point_pos = points.get_offsets().T
+            val_pos = point_pos[val_idx]
+            cat_pos = point_pos[cat_idx]
+
+            assert_array_equal(cat_pos.round(), i)
+            assert_array_equal(val_pos, wide_df[key])
+
+            for point_color in points.get_facecolors():
+                assert tuple(point_color) == to_rgba(palette[i])
+
+    @pytest.mark.parametrize("orient", ["h", "v"])
+    def test_flat(self, flat_series, orient):
+
+        ax = self.func(data=flat_series, orient=orient)
+        _draw_figure(ax.figure)
+
+        cat_idx = ["v", "h"].index(orient)
+        val_idx = int(not cat_idx)
+
+        points = ax.collections[0]
+        pos = points.get_offsets().T
+
+        assert_array_equal(pos[cat_idx].round(), np.zeros(len(flat_series)))
+        assert_array_equal(pos[val_idx], flat_series)
+
+    @pytest.mark.parametrize(
+        "variables,orient",
+        [
+            # Order matters for assigning to x/y
+            ({"cat": "a", "val": "y", "hue": None}, None),
+            ({"val": "y", "cat": "a", "hue": None}, None),
+            ({"cat": "a", "val": "y", "hue": "a"}, None),
+            ({"val": "y", "cat": "a", "hue": "a"}, None),
+            ({"cat": "a", "val": "y", "hue": "b"}, None),
+            ({"val": "y", "cat": "a", "hue": "x"}, None),
+            ({"cat": "s", "val": "y", "hue": None}, None),
+            ({"val": "y", "cat": "s", "hue": None}, "h"),
+            ({"cat": "a", "val": "b", "hue": None}, None),
+            ({"val": "a", "cat": "b", "hue": None}, "h"),
+            ({"cat": "a", "val": "t", "hue": None}, None),
+            ({"val": "t", "cat": "a", "hue": None}, None),
+            ({"cat": "d", "val": "y", "hue": None}, None),
+            ({"val": "y", "cat": "d", "hue": None}, None),
+            ({"cat": "a_cat", "val": "y", "hue": None}, None),
+            ({"val": "y", "cat": "s_cat", "hue": None}, None),
+        ],
+    )
+    def test_positions(self, long_df, variables, orient):
+
+        cat_var = variables["cat"]
+        val_var = variables["val"]
+        hue_var = variables["hue"]
+        var_names = list(variables.values())
+        x_var, y_var, *_ = var_names
+
+        ax = self.func(
+            data=long_df, x=x_var, y=y_var, hue=hue_var, orient=orient,
+        )
+
+        _draw_figure(ax.figure)
+
+        cat_idx = var_names.index(cat_var)
+        val_idx = var_names.index(val_var)
+
+        axis_objs = ax.xaxis, ax.yaxis
+        cat_axis = axis_objs[cat_idx]
+        val_axis = axis_objs[val_idx]
+
+        cat_data = long_df[cat_var]
+        cat_levels = categorical_order(cat_data)
+
+        for i, label in enumerate(cat_levels):
+
+            vals = long_df.loc[cat_data == label, val_var]
+
+            points = ax.collections[i].get_offsets().T
+            cat_pos = points[var_names.index(cat_var)]
+            val_pos = points[var_names.index(val_var)]
+
+            assert_array_equal(val_pos, val_axis.convert_units(vals))
+            assert_array_equal(cat_pos.round(), i)
+            assert 0 <= np.ptp(cat_pos) <= .8
+
+            label = pd.Index([label]).astype(str)[0]
+            assert cat_axis.get_majorticklabels()[i].get_text() == label
+
+    @pytest.mark.parametrize(
+        "variables",
+        [
+            # Order matters for assigning to x/y
+            {"cat": "a", "val": "y", "hue": "b"},
+            {"val": "y", "cat": "a", "hue": "c"},
+            {"cat": "a", "val": "y", "hue": "f"},
+        ],
+    )
+    def test_positions_dodged(self, long_df, variables):
+
+        cat_var = variables["cat"]
+        val_var = variables["val"]
+        hue_var = variables["hue"]
+        var_names = list(variables.values())
+        x_var, y_var, *_ = var_names
+
+        ax = self.func(
+            data=long_df, x=x_var, y=y_var, hue=hue_var, dodge=True,
+        )
+
+        cat_vals = categorical_order(long_df[cat_var])
+        hue_vals = categorical_order(long_df[hue_var])
+
+        n_hue = len(hue_vals)
+        offsets = np.linspace(0, .8, n_hue + 1)[:-1]
+        offsets -= offsets.mean()
+        nest_width = .8 / n_hue
+
+        for i, cat_val in enumerate(cat_vals):
+            for j, hue_val in enumerate(hue_vals):
+                rows = (long_df[cat_var] == cat_val) & (long_df[hue_var] == hue_val)
+                vals = long_df.loc[rows, val_var]
+
+                points = ax.collections[n_hue * i + j].get_offsets().T
+                cat_pos = points[var_names.index(cat_var)]
+                val_pos = points[var_names.index(val_var)]
+
+                if pd.api.types.is_datetime64_any_dtype(vals):
+                    vals = mpl.dates.date2num(vals)
+
+                assert_array_equal(val_pos, vals)
+
+                assert_array_equal(cat_pos.round(), i)
+                assert_array_equal((cat_pos - (i + offsets[j])).round() / nest_width, 0)
+                assert 0 <= np.ptp(cat_pos) <= nest_width
+
+    @pytest.mark.parametrize("cat_var", ["a", "s", "d"])
+    def test_positions_unfixed(self, long_df, cat_var):
+
+        long_df = long_df.sort_values(cat_var)
+
+        kws = dict(size=.001)
+        if "stripplot" in str(self.func):  # can't use __name__ with partial
+            kws["jitter"] = False
+
+        ax = self.func(data=long_df, x=cat_var, y="y", native_scale=True, **kws)
+
+        for i, (cat_level, cat_data) in enumerate(long_df.groupby(cat_var)):
+
+            points = ax.collections[i].get_offsets().T
+            cat_pos = points[0]
+            val_pos = points[1]
+
+            assert_array_equal(val_pos, cat_data["y"])
+
+            comp_level = np.squeeze(ax.xaxis.convert_units(cat_level)).item()
+            assert_array_equal(cat_pos.round(), comp_level)
+
+    @pytest.mark.parametrize(
+        "x_type,order",
+        [
+            (str, None),
+            (str, ["a", "b", "c"]),
+            (str, ["c", "a"]),
+            (str, ["a", "b", "c", "d"]),
+            (int, None),
+            (int, [3, 1, 2]),
+            (int, [3, 1]),
+            (int, [1, 2, 3, 4]),
+            (int, ["3", "1", "2"]),
+        ]
+    )
+    def test_order(self, x_type, order):
+
+        if x_type is str:
+            x = ["b", "a", "c"]
+        else:
+            x = [2, 1, 3]
+        y = [1, 2, 3]
+
+        ax = self.func(x=x, y=y, order=order)
+        _draw_figure(ax.figure)
+
+        if order is None:
+            order = x
+            if x_type is int:
+                order = np.sort(order)
+
+        assert len(ax.collections) == len(order)
+        tick_labels = ax.xaxis.get_majorticklabels()
+
+        assert ax.get_xlim()[1] == (len(order) - .5)
+
+        for i, points in enumerate(ax.collections):
+            cat = order[i]
+            assert tick_labels[i].get_text() == str(cat)
+
+            positions = points.get_offsets()
+            if x_type(cat) in x:
+                val = y[x.index(x_type(cat))]
+                assert positions[0, 1] == val
+            else:
+                assert not positions.size
+
+    @pytest.mark.parametrize("hue_var", ["a", "b"])
+    def test_hue_categorical(self, long_df, hue_var):
+
+        cat_var = "b"
+
+        hue_levels = categorical_order(long_df[hue_var])
+        cat_levels = categorical_order(long_df[cat_var])
+
+        pal_name = "muted"
+        palette = dict(zip(hue_levels, color_palette(pal_name)))
+        ax = self.func(data=long_df, x=cat_var, y="y", hue=hue_var, palette=pal_name)
+
+        for i, level in enumerate(cat_levels):
+
+            sub_df = long_df[long_df[cat_var] == level]
+            point_hues = sub_df[hue_var]
+
+            points = ax.collections[i]
+            point_colors = points.get_facecolors()
+
+            assert len(point_hues) == len(point_colors)
+
+            for hue, color in zip(point_hues, point_colors):
+                assert tuple(color) == to_rgba(palette[hue])
+
+    @pytest.mark.parametrize("hue_var", ["a", "b"])
+    def test_hue_dodged(self, long_df, hue_var):
+
+        ax = self.func(data=long_df, x="y", y="a", hue=hue_var, dodge=True)
+        colors = color_palette(n_colors=long_df[hue_var].nunique())
+        collections = iter(ax.collections)
+
+        # Slightly awkward logic to handle challenges of how the artists work.
+        # e.g. there are empty scatter collections but the because facecolors
+        # for the empty collections will return the default scatter color
+        while colors:
+            points = next(collections)
+            if points.get_offsets().any():
+                face_color = tuple(points.get_facecolors()[0])
+                expected_color = to_rgba(colors.pop(0))
+                assert face_color == expected_color
+
+    @pytest.mark.parametrize(
+        "val_var,val_col,hue_col",
+        list(itertools.product(["x", "y"], ["b", "y", "t"], [None, "a"])),
+    )
+    def test_single(self, long_df, val_var, val_col, hue_col):
+
+        var_kws = {val_var: val_col, "hue": hue_col}
+        ax = self.func(data=long_df, **var_kws)
+        _draw_figure(ax.figure)
+
+        axis_vars = ["x", "y"]
+        val_idx = axis_vars.index(val_var)
+        cat_idx = int(not val_idx)
+        cat_var = axis_vars[cat_idx]
+
+        cat_axis = getattr(ax, f"{cat_var}axis")
+        val_axis = getattr(ax, f"{val_var}axis")
+
+        points = ax.collections[0]
+        point_pos = points.get_offsets().T
+        cat_pos = point_pos[cat_idx]
+        val_pos = point_pos[val_idx]
+
+        assert_array_equal(cat_pos.round(), 0)
+        assert cat_pos.max() <= .4
+        assert cat_pos.min() >= -.4
+
+        num_vals = val_axis.convert_units(long_df[val_col])
+        assert_array_equal(val_pos, num_vals)
+
+        if hue_col is not None:
+            palette = dict(zip(
+                categorical_order(long_df[hue_col]), color_palette()
+            ))
+
+        facecolors = points.get_facecolors()
+        for i, color in enumerate(facecolors):
+            if hue_col is None:
+                assert tuple(color) == to_rgba("C0")
+            else:
+                hue_level = long_df.loc[i, hue_col]
+                expected_color = palette[hue_level]
+                assert tuple(color) == to_rgba(expected_color)
+
+        ticklabels = cat_axis.get_majorticklabels()
+        assert len(ticklabels) == 1
+        assert not ticklabels[0].get_text()
+
+    def test_attributes(self, long_df):
+
+        kwargs = dict(
+            size=2,
+            linewidth=1,
+            edgecolor="C2",
+        )
+
+        ax = self.func(x=long_df["y"], **kwargs)
+        points, = ax.collections
+
+        assert points.get_sizes().item() == kwargs["size"] ** 2
+        assert points.get_linewidths().item() == kwargs["linewidth"]
+        assert tuple(points.get_edgecolors().squeeze()) == to_rgba(kwargs["edgecolor"])
+
+    def test_three_points(self):
+
+        x = np.arange(3)
+        ax = self.func(x=x)
+        for point_color in ax.collections[0].get_facecolor():
+            assert tuple(point_color) == to_rgba("C0")
+
+    def test_legend_categorical(self, long_df):
+
+        ax = self.func(data=long_df, x="y", y="a", hue="b")
+        legend_texts = [t.get_text() for t in ax.legend_.texts]
+        expected = categorical_order(long_df["b"])
+        assert legend_texts == expected
+
+    def test_legend_numeric(self, long_df):
+
+        ax = self.func(data=long_df, x="y", y="a", hue="z")
+        vals = [float(t.get_text()) for t in ax.legend_.texts]
+        assert (vals[1] - vals[0]) == pytest.approx(vals[2] - vals[1])
+
+    def test_legend_disabled(self, long_df):
+
+        ax = self.func(data=long_df, x="y", y="a", hue="b", legend=False)
+        assert ax.legend_ is None
+
+    def test_palette_from_color_deprecation(self, long_df):
+
+        color = (.9, .4, .5)
+        hex_color = mpl.colors.to_hex(color)
+
+        hue_var = "a"
+        n_hue = long_df[hue_var].nunique()
+        palette = color_palette(f"dark:{hex_color}", n_hue)
+
+        with pytest.warns(FutureWarning, match="Setting a gradient palette"):
+            ax = self.func(data=long_df, x="z", hue=hue_var, color=color)
+
+        points = ax.collections[0]
+        for point_color in points.get_facecolors():
+            assert to_rgb(point_color) in palette
+
+    def test_palette_with_hue_deprecation(self, long_df):
+        palette = "Blues"
+        with pytest.warns(FutureWarning, match="Passing `palette` without"):
+            ax = self.func(data=long_df, x="a", y=long_df["y"], palette=palette)
+        strips = ax.collections
+        colors = color_palette(palette, len(strips))
+        for strip, color in zip(strips, colors):
+            assert same_color(strip.get_facecolor()[0], color)
+
+    def test_log_scale(self):
+
+        x = [1, 10, 100, 1000]
+
+        ax = plt.figure().subplots()
+        ax.set_xscale("log")
+        self.func(x=x)
+        vals = ax.collections[0].get_offsets()[:, 0]
+        assert_array_equal(x, vals)
+
+        y = [1, 2, 3, 4]
+
+        ax = plt.figure().subplots()
+        ax.set_xscale("log")
+        self.func(x=x, y=y, native_scale=True)
+        for i, point in enumerate(ax.collections):
+            val = point.get_offsets()[0, 0]
+            assert val == pytest.approx(x[i])
+
+        x = y = np.ones(100)
+
+        ax = plt.figure().subplots()
+        ax.set_yscale("log")
+        self.func(x=x, y=y, orient="h", native_scale=True)
+        cat_points = ax.collections[0].get_offsets().copy()[:, 1]
+        assert np.ptp(np.log10(cat_points)) <= .8
+
+    @pytest.mark.parametrize(
+        "kwargs",
+        [
+            dict(data="wide"),
+            dict(data="wide", orient="h"),
+            dict(data="long", x="x", color="C3"),
+            dict(data="long", y="y", hue="a", jitter=False),
+            dict(data="long", x="a", y="y", hue="z", edgecolor="w", linewidth=.5),
+            dict(data="long", x="a_cat", y="y", hue="z"),
+            dict(data="long", x="y", y="s", hue="c", orient="h", dodge=True),
+            dict(data="long", x="s", y="y", hue="c", native_scale=True),
+        ]
+    )
+    def test_vs_catplot(self, long_df, wide_df, kwargs):
+
+        kwargs = kwargs.copy()
+        if kwargs["data"] == "long":
+            kwargs["data"] = long_df
+        elif kwargs["data"] == "wide":
+            kwargs["data"] = wide_df
+
+        try:
+            name = self.func.__name__[:-4]
+        except AttributeError:
+            name = self.func.func.__name__[:-4]
+        if name == "swarm":
+            kwargs.pop("jitter", None)
+
+        np.random.seed(0)  # for jitter
+        ax = self.func(**kwargs)
+
+        np.random.seed(0)
+        g = catplot(**kwargs, kind=name)
+
+        assert_plots_equal(ax, g.ax)
+
+    def test_empty_palette(self):
+        self.func(x=[], y=[], hue=[], palette=[])
+
+
+class TestStripPlot(SharedScatterTests):
+
+    func = staticmethod(stripplot)
+
+    def test_jitter_unfixed(self, long_df):
+
+        ax1, ax2 = plt.figure().subplots(2)
+        kws = dict(data=long_df, x="y", orient="h", native_scale=True)
+
+        np.random.seed(0)
+        stripplot(**kws, y="s", ax=ax1)
+
+        np.random.seed(0)
+        stripplot(**kws, y=long_df["s"] * 2, ax=ax2)
+
+        p1 = ax1.collections[0].get_offsets()[1]
+        p2 = ax2.collections[0].get_offsets()[1]
+
+        assert p2.std() > p1.std()
+
+    @pytest.mark.parametrize(
+        "orient,jitter",
+        itertools.product(["v", "h"], [True, .1]),
+    )
+    def test_jitter(self, long_df, orient, jitter):
+
+        cat_var, val_var = "a", "y"
+        if orient == "v":
+            x_var, y_var = cat_var, val_var
+            cat_idx, val_idx = 0, 1
+        else:
+            x_var, y_var = val_var, cat_var
+            cat_idx, val_idx = 1, 0
+
+        cat_vals = categorical_order(long_df[cat_var])
+
+        ax = stripplot(
+            data=long_df, x=x_var, y=y_var, jitter=jitter,
+        )
+
+        if jitter is True:
+            jitter_range = .4
+        else:
+            jitter_range = 2 * jitter
+
+        for i, level in enumerate(cat_vals):
+
+            vals = long_df.loc[long_df[cat_var] == level, val_var]
+            points = ax.collections[i].get_offsets().T
+            cat_points = points[cat_idx]
+            val_points = points[val_idx]
+
+            assert_array_equal(val_points, vals)
+            assert np.std(cat_points) > 0
+            assert np.ptp(cat_points) <= jitter_range
+
+
+class TestSwarmPlot(SharedScatterTests):
+
+    func = staticmethod(partial(swarmplot, warn_thresh=1))
+
+
+class TestBarPlotter(CategoricalFixture):
+
+    default_kws = dict(
+        data=None, x=None, y=None, hue=None, units=None,
+        estimator="mean", errorbar=("ci", 95), n_boot=100, seed=None,
+        order=None, hue_order=None,
+        orient=None, color=None, palette=None,
+        saturation=.75, width=0.8,
+        errcolor=".26", errwidth=None,
+        capsize=None, dodge=True
+    )
+
+    def test_nested_width(self):
+
+        ax = cat.barplot(data=self.df, x="g", y="y", hue="h")
+        for bar in ax.patches:
+            assert bar.get_width() == pytest.approx(.8 / 2)
+        ax.clear()
+
+        ax = cat.barplot(data=self.df, x="g", y="y", hue="g", width=.5)
+        for bar in ax.patches:
+            assert bar.get_width() == pytest.approx(.5 / 3)
+        ax.clear()
+
+        ax = cat.barplot(data=self.df, x="g", y="y", hue="g", dodge=False)
+        for bar in ax.patches:
+            assert bar.get_width() == pytest.approx(.8)
+        ax.clear()
+
+    def test_draw_vertical_bars(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        assert len(ax.patches) == len(p.plot_data)
+        assert len(ax.lines) == len(p.plot_data)
+
+        for bar, color in zip(ax.patches, p.colors):
+            assert bar.get_facecolor()[:-1] == color
+
+        positions = np.arange(len(p.plot_data)) - p.width / 2
+        for bar, pos, stat in zip(ax.patches, positions, p.statistic):
+            assert bar.get_x() == pos
+            assert bar.get_width() == p.width
+            assert bar.get_y() == 0
+            assert bar.get_height() == stat
+
+    def test_draw_horizontal_bars(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="y", y="g", orient="h", data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        assert len(ax.patches) == len(p.plot_data)
+        assert len(ax.lines) == len(p.plot_data)
+
+        for bar, color in zip(ax.patches, p.colors):
+            assert bar.get_facecolor()[:-1] == color
+
+        positions = np.arange(len(p.plot_data)) - p.width / 2
+        for bar, pos, stat in zip(ax.patches, positions, p.statistic):
+            assert bar.get_y() == pos
+            assert bar.get_height() == p.width
+            assert bar.get_x() == 0
+            assert bar.get_width() == stat
+
+    def test_draw_nested_vertical_bars(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", hue="h", data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        n_groups, n_hues = len(p.plot_data), len(p.hue_names)
+        assert len(ax.patches) == n_groups * n_hues
+        assert len(ax.lines) == n_groups * n_hues
+
+        for bar in ax.patches[:n_groups]:
+            assert bar.get_facecolor()[:-1] == p.colors[0]
+        for bar in ax.patches[n_groups:]:
+            assert bar.get_facecolor()[:-1] == p.colors[1]
+
+        positions = np.arange(len(p.plot_data))
+        for bar, pos in zip(ax.patches[:n_groups], positions):
+            assert bar.get_x() == approx(pos - p.width / 2)
+            assert bar.get_width() == approx(p.nested_width)
+
+        for bar, stat in zip(ax.patches, p.statistic.T.flat):
+            assert bar.get_y() == approx(0)
+            assert bar.get_height() == approx(stat)
+
+    def test_draw_nested_horizontal_bars(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="y", y="g", hue="h", orient="h", data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        n_groups, n_hues = len(p.plot_data), len(p.hue_names)
+        assert len(ax.patches) == n_groups * n_hues
+        assert len(ax.lines) == n_groups * n_hues
+
+        for bar in ax.patches[:n_groups]:
+            assert bar.get_facecolor()[:-1] == p.colors[0]
+        for bar in ax.patches[n_groups:]:
+            assert bar.get_facecolor()[:-1] == p.colors[1]
+
+        positions = np.arange(len(p.plot_data))
+        for bar, pos in zip(ax.patches[:n_groups], positions):
+            assert bar.get_y() == approx(pos - p.width / 2)
+            assert bar.get_height() == approx(p.nested_width)
+
+        for bar, stat in zip(ax.patches, p.statistic.T.flat):
+            assert bar.get_x() == approx(0)
+            assert bar.get_width() == approx(stat)
+
+    def test_draw_missing_bars(self):
+
+        kws = self.default_kws.copy()
+
+        order = list("abcd")
+        kws.update(x="g", y="y", order=order, data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        assert len(ax.patches) == len(order)
+        assert len(ax.lines) == len(order)
+
+        plt.close("all")
+
+        hue_order = list("mno")
+        kws.update(x="g", y="y", hue="h", hue_order=hue_order, data=self.df)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        assert len(ax.patches) == len(p.plot_data) * len(hue_order)
+        assert len(ax.lines) == len(p.plot_data) * len(hue_order)
+
+        plt.close("all")
+
+    def test_unaligned_index(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        cat.barplot(x=self.g, y=self.y, errorbar="sd", ax=ax1)
+        cat.barplot(x=self.g, y=self.y_perm, errorbar="sd", ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert approx(l1.get_xydata()) == l2.get_xydata()
+        for p1, p2 in zip(ax1.patches, ax2.patches):
+            assert approx(p1.get_xy()) == p2.get_xy()
+            assert approx(p1.get_height()) == p2.get_height()
+            assert approx(p1.get_width()) == p2.get_width()
+
+        f, (ax1, ax2) = plt.subplots(2)
+        hue_order = self.h.unique()
+        cat.barplot(x=self.g, y=self.y, hue=self.h,
+                    hue_order=hue_order, errorbar="sd", ax=ax1)
+        cat.barplot(x=self.g, y=self.y_perm, hue=self.h,
+                    hue_order=hue_order, errorbar="sd", ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert approx(l1.get_xydata()) == l2.get_xydata()
+        for p1, p2 in zip(ax1.patches, ax2.patches):
+            assert approx(p1.get_xy()) == p2.get_xy()
+            assert approx(p1.get_height()) == p2.get_height()
+            assert approx(p1.get_width()) == p2.get_width()
+
+    def test_barplot_colors(self):
+
+        # Test unnested palette colors
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", data=self.df,
+                   saturation=1, palette="muted")
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        palette = palettes.color_palette("muted", len(self.g.unique()))
+        for patch, pal_color in zip(ax.patches, palette):
+            assert patch.get_facecolor()[:-1] == pal_color
+
+        plt.close("all")
+
+        # Test single color
+        color = (.2, .2, .3, 1)
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", data=self.df,
+                   saturation=1, color=color)
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        for patch in ax.patches:
+            assert patch.get_facecolor() == color
+
+        plt.close("all")
+
+        # Test nested palette colors
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", hue="h", data=self.df,
+                   saturation=1, palette="Set2")
+        p = cat._BarPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_bars(ax, {})
+
+        palette = palettes.color_palette("Set2", len(self.h.unique()))
+        for patch in ax.patches[:len(self.g.unique())]:
+            assert patch.get_facecolor()[:-1] == palette[0]
+        for patch in ax.patches[len(self.g.unique()):]:
+            assert patch.get_facecolor()[:-1] == palette[1]
+
+        plt.close("all")
+
+    def test_simple_barplots(self):
+
+        ax = cat.barplot(x="g", y="y", data=self.df)
+        assert len(ax.patches) == len(self.g.unique())
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        plt.close("all")
+
+        ax = cat.barplot(x="y", y="g", orient="h", data=self.df)
+        assert len(ax.patches) == len(self.g.unique())
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        plt.close("all")
+
+        ax = cat.barplot(x="g", y="y", hue="h", data=self.df)
+        assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        plt.close("all")
+
+        ax = cat.barplot(x="y", y="g", hue="h", orient="h", data=self.df)
+        assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        plt.close("all")
+
+    def test_errorbar(self, long_df):
+
+        ax = cat.barplot(data=long_df, x="a", y="y", errorbar=("sd", 2))
+        order = categorical_order(long_df["a"])
+
+        for i, line in enumerate(ax.lines):
+            sub_df = long_df.loc[long_df["a"] == order[i], "y"]
+            mean = sub_df.mean()
+            sd = sub_df.std()
+            expected = mean - 2 * sd, mean + 2 * sd
+            assert_array_equal(line.get_ydata(), expected)
+
+
+class TestPointPlotter(CategoricalFixture):
+
+    default_kws = dict(
+        x=None, y=None, hue=None, data=None,
+        estimator="mean", errorbar=("ci", 95),
+        n_boot=100, units=None, seed=None,
+        order=None, hue_order=None,
+        markers="o", linestyles="-", dodge=0,
+        join=True, scale=1, orient=None,
+        color=None, palette=None,
+        errwidth=None, capsize=None, label=None,
+
+    )
+
+    def test_different_defualt_colors(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(x="g", y="y", data=self.df))
+        p = cat._PointPlotter(**kws)
+        color = palettes.color_palette()[0]
+        npt.assert_array_equal(p.colors, [color, color, color])
+
+    def test_hue_offsets(self):
+
+        kws = self.default_kws.copy()
+        kws.update(dict(x="g", y="y", hue="h", data=self.df))
+
+        p = cat._PointPlotter(**kws)
+        npt.assert_array_equal(p.hue_offsets, [0, 0])
+
+        kws.update(dict(dodge=.5))
+
+        p = cat._PointPlotter(**kws)
+        npt.assert_array_equal(p.hue_offsets, [-.25, .25])
+
+        kws.update(dict(x="h", hue="g", dodge=0))
+
+        p = cat._PointPlotter(**kws)
+        npt.assert_array_equal(p.hue_offsets, [0, 0, 0])
+
+        kws.update(dict(dodge=.3))
+
+        p = cat._PointPlotter(**kws)
+        npt.assert_array_equal(p.hue_offsets, [-.15, 0, .15])
+
+    def test_draw_vertical_points(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", data=self.df)
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == len(p.plot_data) + 1
+        points = ax.collections[0]
+        assert len(points.get_offsets()) == len(p.plot_data)
+
+        x, y = points.get_offsets().T
+        npt.assert_array_equal(x, np.arange(len(p.plot_data)))
+        npt.assert_array_equal(y, p.statistic)
+
+        for got_color, want_color in zip(points.get_facecolors(),
+                                         p.colors):
+            npt.assert_array_equal(got_color[:-1], want_color)
+
+    def test_draw_horizontal_points(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="y", y="g", orient="h", data=self.df)
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == len(p.plot_data) + 1
+        points = ax.collections[0]
+        assert len(points.get_offsets()) == len(p.plot_data)
+
+        x, y = points.get_offsets().T
+        npt.assert_array_equal(x, p.statistic)
+        npt.assert_array_equal(y, np.arange(len(p.plot_data)))
+
+        for got_color, want_color in zip(points.get_facecolors(),
+                                         p.colors):
+            npt.assert_array_equal(got_color[:-1], want_color)
+
+    def test_draw_vertical_nested_points(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", hue="h", data=self.df)
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        assert len(ax.collections) == 2
+        assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)
+
+        for points, numbers, color in zip(ax.collections,
+                                          p.statistic.T,
+                                          p.colors):
+
+            assert len(points.get_offsets()) == len(p.plot_data)
+
+            x, y = points.get_offsets().T
+            npt.assert_array_equal(x, np.arange(len(p.plot_data)))
+            npt.assert_array_equal(y, numbers)
+
+            for got_color in points.get_facecolors():
+                npt.assert_array_equal(got_color[:-1], color)
+
+    def test_draw_horizontal_nested_points(self):
+
+        kws = self.default_kws.copy()
+        kws.update(x="y", y="g", hue="h", orient="h", data=self.df)
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        assert len(ax.collections) == 2
+        assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)
+
+        for points, numbers, color in zip(ax.collections,
+                                          p.statistic.T,
+                                          p.colors):
+
+            assert len(points.get_offsets()) == len(p.plot_data)
+
+            x, y = points.get_offsets().T
+            npt.assert_array_equal(x, numbers)
+            npt.assert_array_equal(y, np.arange(len(p.plot_data)))
+
+            for got_color in points.get_facecolors():
+                npt.assert_array_equal(got_color[:-1], color)
+
+    def test_draw_missing_points(self):
+
+        kws = self.default_kws.copy()
+        df = self.df.copy()
+
+        kws.update(x="g", y="y", hue="h", hue_order=["x", "y"], data=df)
+        p = cat._PointPlotter(**kws)
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        df.loc[df["h"] == "m", "y"] = np.nan
+        kws.update(x="g", y="y", hue="h", data=df)
+        p = cat._PointPlotter(**kws)
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+    def test_unaligned_index(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        cat.pointplot(x=self.g, y=self.y, errorbar="sd", ax=ax1)
+        cat.pointplot(x=self.g, y=self.y_perm, errorbar="sd", ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert approx(l1.get_xydata()) == l2.get_xydata()
+        for p1, p2 in zip(ax1.collections, ax2.collections):
+            assert approx(p1.get_offsets()) == p2.get_offsets()
+
+        f, (ax1, ax2) = plt.subplots(2)
+        hue_order = self.h.unique()
+        cat.pointplot(x=self.g, y=self.y, hue=self.h,
+                      hue_order=hue_order, errorbar="sd", ax=ax1)
+        cat.pointplot(x=self.g, y=self.y_perm, hue=self.h,
+                      hue_order=hue_order, errorbar="sd", ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert approx(l1.get_xydata()) == l2.get_xydata()
+        for p1, p2 in zip(ax1.collections, ax2.collections):
+            assert approx(p1.get_offsets()) == p2.get_offsets()
+
+    def test_pointplot_colors(self):
+
+        # Test a single-color unnested plot
+        color = (.2, .2, .3, 1)
+        kws = self.default_kws.copy()
+        kws.update(x="g", y="y", data=self.df, color=color)
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        for line in ax.lines:
+            assert line.get_color() == color[:-1]
+
+        for got_color in ax.collections[0].get_facecolors():
+            npt.assert_array_equal(rgb2hex(got_color), rgb2hex(color))
+
+        plt.close("all")
+
+        # Test a multi-color unnested plot
+        palette = palettes.color_palette("Set1", 3)
+        kws.update(x="g", y="y", data=self.df, palette="Set1")
+        p = cat._PointPlotter(**kws)
+
+        assert not p.join
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        for line, pal_color in zip(ax.lines, palette):
+            npt.assert_array_equal(line.get_color(), pal_color)
+
+        for point_color, pal_color in zip(ax.collections[0].get_facecolors(),
+                                          palette):
+            npt.assert_array_equal(rgb2hex(point_color), rgb2hex(pal_color))
+
+        plt.close("all")
+
+        # Test a multi-colored nested plot
+        palette = palettes.color_palette("dark", 2)
+        kws.update(x="g", y="y", hue="h", data=self.df, palette="dark")
+        p = cat._PointPlotter(**kws)
+
+        f, ax = plt.subplots()
+        p.draw_points(ax)
+
+        for line in ax.lines[:(len(p.plot_data) + 1)]:
+            assert line.get_color() == palette[0]
+        for line in ax.lines[(len(p.plot_data) + 1):]:
+            assert line.get_color() == palette[1]
+
+        for i, pal_color in enumerate(palette):
+            for point_color in ax.collections[i].get_facecolors():
+                npt.assert_array_equal(point_color[:-1], pal_color)
+
+        plt.close("all")
+
+    def test_simple_pointplots(self):
+
+        ax = cat.pointplot(x="g", y="y", data=self.df)
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == len(self.g.unique()) + 1
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        plt.close("all")
+
+        ax = cat.pointplot(x="y", y="g", orient="h", data=self.df)
+        assert len(ax.collections) == 1
+        assert len(ax.lines) == len(self.g.unique()) + 1
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        plt.close("all")
+
+        ax = cat.pointplot(x="g", y="y", hue="h", data=self.df)
+        assert len(ax.collections) == len(self.h.unique())
+        assert len(ax.lines) == (
+            len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())
+        )
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        plt.close("all")
+
+        ax = cat.pointplot(x="y", y="g", hue="h", orient="h", data=self.df)
+        assert len(ax.collections) == len(self.h.unique())
+        assert len(ax.lines) == (
+            len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())
+        )
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        plt.close("all")
+
+    def test_errorbar(self, long_df):
+
+        ax = cat.pointplot(
+            data=long_df, x="a", y="y", errorbar=("sd", 2), join=False
+        )
+        order = categorical_order(long_df["a"])
+
+        for i, line in enumerate(ax.lines):
+            sub_df = long_df.loc[long_df["a"] == order[i], "y"]
+            mean = sub_df.mean()
+            sd = sub_df.std()
+            expected = mean - 2 * sd, mean + 2 * sd
+            assert_array_equal(line.get_ydata(), expected)
+
+    def test_on_facetgrid(self, long_df):
+
+        g = FacetGrid(long_df, hue="a")
+        g.map(pointplot, "a", "y")
+        g.add_legend()
+
+        order = categorical_order(long_df["a"])
+        legend_texts = [t.get_text() for t in g.legend.texts]
+        assert legend_texts == order
+
+
+class TestCountPlot(CategoricalFixture):
+
+    def test_plot_elements(self):
+
+        ax = cat.countplot(x="g", data=self.df)
+        assert len(ax.patches) == self.g.unique().size
+        for p in ax.patches:
+            assert p.get_y() == 0
+            assert p.get_height() == self.g.size / self.g.unique().size
+        plt.close("all")
+
+        ax = cat.countplot(y="g", data=self.df)
+        assert len(ax.patches) == self.g.unique().size
+        for p in ax.patches:
+            assert p.get_x() == 0
+            assert p.get_width() == self.g.size / self.g.unique().size
+        plt.close("all")
+
+        ax = cat.countplot(x="g", hue="h", data=self.df)
+        assert len(ax.patches) == self.g.unique().size * self.h.unique().size
+        plt.close("all")
+
+        ax = cat.countplot(y="g", hue="h", data=self.df)
+        assert len(ax.patches) == self.g.unique().size * self.h.unique().size
+        plt.close("all")
+
+    def test_input_error(self):
+
+        with pytest.raises(ValueError):
+            cat.countplot(x="g", y="h", data=self.df)
+
+
+class TestCatPlot(CategoricalFixture):
+
+    def test_facet_organization(self):
+
+        g = cat.catplot(x="g", y="y", data=self.df)
+        assert g.axes.shape == (1, 1)
+
+        g = cat.catplot(x="g", y="y", col="h", data=self.df)
+        assert g.axes.shape == (1, 2)
+
+        g = cat.catplot(x="g", y="y", row="h", data=self.df)
+        assert g.axes.shape == (2, 1)
+
+        g = cat.catplot(x="g", y="y", col="u", row="h", data=self.df)
+        assert g.axes.shape == (2, 3)
+
+    def test_plot_elements(self):
+
+        g = cat.catplot(x="g", y="y", data=self.df, kind="point")
+        assert len(g.ax.collections) == 1
+        want_lines = self.g.unique().size + 1
+        assert len(g.ax.lines) == want_lines
+
+        g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="point")
+        want_collections = self.h.unique().size
+        assert len(g.ax.collections) == want_collections
+        want_lines = (self.g.unique().size + 1) * self.h.unique().size
+        assert len(g.ax.lines) == want_lines
+
+        g = cat.catplot(x="g", y="y", data=self.df, kind="bar")
+        want_elements = self.g.unique().size
+        assert len(g.ax.patches) == want_elements
+        assert len(g.ax.lines) == want_elements
+
+        g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="bar")
+        want_elements = self.g.unique().size * self.h.unique().size
+        assert len(g.ax.patches) == want_elements
+        assert len(g.ax.lines) == want_elements
+
+        g = cat.catplot(x="g", data=self.df, kind="count")
+        want_elements = self.g.unique().size
+        assert len(g.ax.patches) == want_elements
+        assert len(g.ax.lines) == 0
+
+        g = cat.catplot(x="g", hue="h", data=self.df, kind="count")
+        want_elements = self.g.unique().size * self.h.unique().size
+        assert len(g.ax.patches) == want_elements
+        assert len(g.ax.lines) == 0
+
+        g = cat.catplot(y="y", data=self.df, kind="box")
+        want_artists = 1
+        assert len(self.get_box_artists(g.ax)) == want_artists
+
+        g = cat.catplot(x="g", y="y", data=self.df, kind="box")
+        want_artists = self.g.unique().size
+        assert len(self.get_box_artists(g.ax)) == want_artists
+
+        g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="box")
+        want_artists = self.g.unique().size * self.h.unique().size
+        assert len(self.get_box_artists(g.ax)) == want_artists
+
+        g = cat.catplot(x="g", y="y", data=self.df,
+                        kind="violin", inner=None)
+        want_elements = self.g.unique().size
+        assert len(g.ax.collections) == want_elements
+
+        g = cat.catplot(x="g", y="y", hue="h", data=self.df,
+                        kind="violin", inner=None)
+        want_elements = self.g.unique().size * self.h.unique().size
+        assert len(g.ax.collections) == want_elements
+
+        g = cat.catplot(x="g", y="y", data=self.df, kind="strip")
+        want_elements = self.g.unique().size
+        assert len(g.ax.collections) == want_elements
+        for strip in g.ax.collections:
+            assert same_color(strip.get_facecolors(), "C0")
+
+        g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="strip")
+        want_elements = self.g.unique().size + self.h.unique().size
+        assert len(g.ax.collections) == want_elements
+
+    def test_bad_plot_kind_error(self):
+
+        with pytest.raises(ValueError):
+            cat.catplot(x="g", y="y", data=self.df, kind="not_a_kind")
+
+    def test_count_x_and_y(self):
+
+        with pytest.raises(ValueError):
+            cat.catplot(x="g", y="y", data=self.df, kind="count")
+
+    def test_plot_colors(self):
+
+        ax = cat.barplot(x="g", y="y", data=self.df)
+        g = cat.catplot(x="g", y="y", data=self.df, kind="bar")
+        for p1, p2 in zip(ax.patches, g.ax.patches):
+            assert p1.get_facecolor() == p2.get_facecolor()
+        plt.close("all")
+
+        ax = cat.barplot(x="g", y="y", data=self.df, color="purple")
+        g = cat.catplot(x="g", y="y", data=self.df,
+                        kind="bar", color="purple")
+        for p1, p2 in zip(ax.patches, g.ax.patches):
+            assert p1.get_facecolor() == p2.get_facecolor()
+        plt.close("all")
+
+        ax = cat.barplot(x="g", y="y", data=self.df, palette="Set2", hue="h")
+        g = cat.catplot(x="g", y="y", data=self.df,
+                        kind="bar", palette="Set2", hue="h")
+        for p1, p2 in zip(ax.patches, g.ax.patches):
+            assert p1.get_facecolor() == p2.get_facecolor()
+        plt.close("all")
+
+        ax = cat.pointplot(x="g", y="y", data=self.df)
+        g = cat.catplot(x="g", y="y", data=self.df)
+        for l1, l2 in zip(ax.lines, g.ax.lines):
+            assert l1.get_color() == l2.get_color()
+        plt.close("all")
+
+        ax = cat.pointplot(x="g", y="y", data=self.df, color="purple")
+        g = cat.catplot(x="g", y="y", data=self.df, color="purple")
+        for l1, l2 in zip(ax.lines, g.ax.lines):
+            assert l1.get_color() == l2.get_color()
+        plt.close("all")
+
+        ax = cat.pointplot(x="g", y="y", data=self.df, palette="Set2", hue="h")
+        g = cat.catplot(x="g", y="y", data=self.df, palette="Set2", hue="h")
+        for l1, l2 in zip(ax.lines, g.ax.lines):
+            assert l1.get_color() == l2.get_color()
+        plt.close("all")
+
+    def test_ax_kwarg_removal(self):
+
+        f, ax = plt.subplots()
+        with pytest.warns(UserWarning, match="catplot is a figure-level"):
+            g = cat.catplot(x="g", y="y", data=self.df, ax=ax)
+        assert len(ax.collections) == 0
+        assert len(g.ax.collections) > 0
+
+    def test_share_xy(self):
+
+        # Test default behavior works
+        g = cat.catplot(x="g", y="y", col="g", data=self.df, sharex=True)
+        for ax in g.axes.flat:
+            assert len(ax.collections) == len(self.df.g.unique())
+
+        g = cat.catplot(x="y", y="g", col="g", data=self.df, sharey=True)
+        for ax in g.axes.flat:
+            assert len(ax.collections) == len(self.df.g.unique())
+
+        # Test unsharing workscol
+        with pytest.warns(UserWarning):
+            g = cat.catplot(
+                x="g", y="y", col="g", data=self.df, sharex=False, kind="bar",
+            )
+            for ax in g.axes.flat:
+                assert len(ax.patches) == 1
+
+        with pytest.warns(UserWarning):
+            g = cat.catplot(
+                x="y", y="g", col="g", data=self.df, sharey=False, kind="bar",
+            )
+            for ax in g.axes.flat:
+                assert len(ax.patches) == 1
+
+        # Make sure no warning is raised if color is provided on unshared plot
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            g = cat.catplot(
+                x="g", y="y", col="g", data=self.df, sharex=False, color="b"
+            )
+        for ax in g.axes.flat:
+            assert ax.get_xlim() == (-.5, .5)
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            g = cat.catplot(
+                x="y", y="g", col="g", data=self.df, sharey=False, color="r"
+            )
+        for ax in g.axes.flat:
+            assert ax.get_ylim() == (.5, -.5)
+
+        # Make sure order is used if given, regardless of sharex value
+        order = self.df.g.unique()
+        g = cat.catplot(x="g", y="y", col="g", data=self.df, sharex=False, order=order)
+        for ax in g.axes.flat:
+            assert len(ax.collections) == len(self.df.g.unique())
+
+        g = cat.catplot(x="y", y="g", col="g", data=self.df, sharey=False, order=order)
+        for ax in g.axes.flat:
+            assert len(ax.collections) == len(self.df.g.unique())
+
+    @pytest.mark.parametrize("var", ["col", "row"])
+    def test_array_faceter(self, long_df, var):
+
+        g1 = catplot(data=long_df, x="y", **{var: "a"})
+        g2 = catplot(data=long_df, x="y", **{var: long_df["a"].to_numpy()})
+
+        for ax1, ax2 in zip(g1.axes.flat, g2.axes.flat):
+            assert_plots_equal(ax1, ax2)
+
+
+class TestBoxenPlotter(CategoricalFixture):
+
+    default_kws = dict(x=None, y=None, hue=None, data=None,
+                       order=None, hue_order=None,
+                       orient=None, color=None, palette=None,
+                       saturation=.75, width=.8, dodge=True,
+                       k_depth='tukey', linewidth=None,
+                       scale='exponential', outlier_prop=0.007,
+                       trust_alpha=0.05, showfliers=True)
+
+    def ispatch(self, c):
+
+        return isinstance(c, mpl.collections.PatchCollection)
+
+    def ispath(self, c):
+
+        return isinstance(c, mpl.collections.PathCollection)
+
+    def edge_calc(self, n, data):
+
+        q = np.asanyarray([0.5 ** n, 1 - 0.5 ** n]) * 100
+        q = list(np.unique(q))
+        return np.percentile(data, q)
+
+    def test_box_ends_finite(self):
+
+        p = cat._LVPlotter(**self.default_kws)
+        p.establish_variables("g", "y", data=self.df)
+        box_ends = []
+        k_vals = []
+        for s in p.plot_data:
+            b, k = p._lv_box_ends(s)
+            box_ends.append(b)
+            k_vals.append(k)
+
+        # Check that all the box ends are finite and are within
+        # the bounds of the data
+        b_e = map(lambda a: np.all(np.isfinite(a)), box_ends)
+        assert np.sum(list(b_e)) == len(box_ends)
+
+        def within(t):
+            a, d = t
+            return ((np.ravel(a) <= d.max())
+                    & (np.ravel(a) >= d.min())).all()
+
+        b_w = map(within, zip(box_ends, p.plot_data))
+        assert np.sum(list(b_w)) == len(box_ends)
+
+        k_f = map(lambda k: (k > 0.) & np.isfinite(k), k_vals)
+        assert np.sum(list(k_f)) == len(k_vals)
+
+    def test_box_ends_correct_tukey(self):
+
+        n = 100
+        linear_data = np.arange(n)
+        expected_k = max(int(np.log2(n)) - 3, 1)
+        expected_edges = [self.edge_calc(i, linear_data)
+                          for i in range(expected_k + 1, 1, -1)]
+
+        p = cat._LVPlotter(**self.default_kws)
+        calc_edges, calc_k = p._lv_box_ends(linear_data)
+
+        npt.assert_array_equal(expected_edges, calc_edges)
+        assert expected_k == calc_k
+
+    def test_box_ends_correct_proportion(self):
+
+        n = 100
+        linear_data = np.arange(n)
+        expected_k = int(np.log2(n)) - int(np.log2(n * 0.007)) + 1
+        expected_edges = [self.edge_calc(i, linear_data)
+                          for i in range(expected_k + 1, 1, -1)]
+
+        kws = self.default_kws.copy()
+        kws["k_depth"] = "proportion"
+        p = cat._LVPlotter(**kws)
+        calc_edges, calc_k = p._lv_box_ends(linear_data)
+
+        npt.assert_array_equal(expected_edges, calc_edges)
+        assert expected_k == calc_k
+
+    @pytest.mark.parametrize(
+        "n,exp_k",
+        [(491, 6), (492, 7), (983, 7), (984, 8), (1966, 8), (1967, 9)],
+    )
+    def test_box_ends_correct_trustworthy(self, n, exp_k):
+
+        linear_data = np.arange(n)
+        kws = self.default_kws.copy()
+        kws["k_depth"] = "trustworthy"
+        p = cat._LVPlotter(**kws)
+        _, calc_k = p._lv_box_ends(linear_data)
+
+        assert exp_k == calc_k
+
+    def test_outliers(self):
+
+        n = 100
+        outlier_data = np.append(np.arange(n - 1), 2 * n)
+        expected_k = max(int(np.log2(n)) - 3, 1)
+        expected_edges = [self.edge_calc(i, outlier_data)
+                          for i in range(expected_k + 1, 1, -1)]
+
+        p = cat._LVPlotter(**self.default_kws)
+        calc_edges, calc_k = p._lv_box_ends(outlier_data)
+
+        npt.assert_array_equal(calc_edges, expected_edges)
+        assert calc_k == expected_k
+
+        out_calc = p._lv_outliers(outlier_data, calc_k)
+        out_exp = p._lv_outliers(outlier_data, expected_k)
+
+        npt.assert_equal(out_calc, out_exp)
+
+    def test_showfliers(self):
+
+        ax = cat.boxenplot(x="g", y="y", data=self.df, k_depth="proportion",
+                           showfliers=True)
+        ax_collections = list(filter(self.ispath, ax.collections))
+        for c in ax_collections:
+            assert len(c.get_offsets()) == 2
+
+        # Test that all data points are in the plot
+        assert ax.get_ylim()[0] < self.df["y"].min()
+        assert ax.get_ylim()[1] > self.df["y"].max()
+
+        plt.close("all")
+
+        ax = cat.boxenplot(x="g", y="y", data=self.df, showfliers=False)
+        assert len(list(filter(self.ispath, ax.collections))) == 0
+
+        plt.close("all")
+
+    def test_invalid_depths(self):
+
+        kws = self.default_kws.copy()
+
+        # Make sure illegal depth raises
+        kws["k_depth"] = "nosuchdepth"
+        with pytest.raises(ValueError):
+            cat._LVPlotter(**kws)
+
+        # Make sure illegal outlier_prop raises
+        kws["k_depth"] = "proportion"
+        for p in (-13, 37):
+            kws["outlier_prop"] = p
+            with pytest.raises(ValueError):
+                cat._LVPlotter(**kws)
+
+        kws["k_depth"] = "trustworthy"
+        for alpha in (-13, 37):
+            kws["trust_alpha"] = alpha
+            with pytest.raises(ValueError):
+                cat._LVPlotter(**kws)
+
+    @pytest.mark.parametrize("power", [1, 3, 7, 11, 13, 17])
+    def test_valid_depths(self, power):
+
+        x = np.random.standard_t(10, 2 ** power)
+
+        valid_depths = ["proportion", "tukey", "trustworthy", "full"]
+        kws = self.default_kws.copy()
+
+        for depth in valid_depths + [4]:
+            kws["k_depth"] = depth
+            box_ends, k = cat._LVPlotter(**kws)._lv_box_ends(x)
+
+            if depth == "full":
+                assert k == int(np.log2(len(x))) + 1
+
+    def test_valid_scales(self):
+
+        valid_scales = ["linear", "exponential", "area"]
+        kws = self.default_kws.copy()
+
+        for scale in valid_scales + ["unknown_scale"]:
+            kws["scale"] = scale
+            if scale not in valid_scales:
+                with pytest.raises(ValueError):
+                    cat._LVPlotter(**kws)
+            else:
+                cat._LVPlotter(**kws)
+
+    def test_hue_offsets(self):
+
+        p = cat._LVPlotter(**self.default_kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        npt.assert_array_equal(p.hue_offsets, [-.2, .2])
+
+        kws = self.default_kws.copy()
+        kws["width"] = .6
+        p = cat._LVPlotter(**kws)
+        p.establish_variables("g", "y", hue="h", data=self.df)
+        npt.assert_array_equal(p.hue_offsets, [-.15, .15])
+
+        p = cat._LVPlotter(**kws)
+        p.establish_variables("h", "y", "g", data=self.df)
+        npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])
+
+    def test_axes_data(self):
+
+        ax = cat.boxenplot(x="g", y="y", data=self.df)
+        patches = filter(self.ispatch, ax.collections)
+        assert len(list(patches)) == 3
+
+        plt.close("all")
+
+        ax = cat.boxenplot(x="g", y="y", hue="h", data=self.df)
+        patches = filter(self.ispatch, ax.collections)
+        assert len(list(patches)) == 6
+
+        plt.close("all")
+
+    def test_box_colors(self):
+
+        pal = palettes.color_palette()
+
+        ax = cat.boxenplot(
+            x="g", y="y", data=self.df, saturation=1, showfliers=False
+        )
+        ax.figure.canvas.draw()
+        for i, box in enumerate(ax.collections):
+            assert same_color(box.get_facecolor()[0], pal[i])
+
+        plt.close("all")
+
+        ax = cat.boxenplot(
+            x="g", y="y", hue="h", data=self.df, saturation=1, showfliers=False
+        )
+        ax.figure.canvas.draw()
+        for i, box in enumerate(ax.collections):
+            assert same_color(box.get_facecolor()[0], pal[i % 2])
+
+        plt.close("all")
+
+    def test_draw_missing_boxes(self):
+
+        ax = cat.boxenplot(x="g", y="y", data=self.df,
+                           order=["a", "b", "c", "d"])
+
+        patches = filter(self.ispatch, ax.collections)
+        assert len(list(patches)) == 3
+        plt.close("all")
+
+    def test_unaligned_index(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        cat.boxenplot(x=self.g, y=self.y, ax=ax1)
+        cat.boxenplot(x=self.g, y=self.y_perm, ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert np.array_equal(l1.get_xydata(), l2.get_xydata())
+
+        f, (ax1, ax2) = plt.subplots(2)
+        hue_order = self.h.unique()
+        cat.boxenplot(x=self.g, y=self.y, hue=self.h,
+                      hue_order=hue_order, ax=ax1)
+        cat.boxenplot(x=self.g, y=self.y_perm, hue=self.h,
+                      hue_order=hue_order, ax=ax2)
+        for l1, l2 in zip(ax1.lines, ax2.lines):
+            assert np.array_equal(l1.get_xydata(), l2.get_xydata())
+
+    def test_missing_data(self):
+
+        x = ["a", "a", "b", "b", "c", "c", "d", "d"]
+        h = ["x", "y", "x", "y", "x", "y", "x", "y"]
+        y = self.rs.randn(8)
+        y[-2:] = np.nan
+
+        ax = cat.boxenplot(x=x, y=y)
+        assert len(ax.lines) == 3
+
+        plt.close("all")
+
+        y[-1] = 0
+        ax = cat.boxenplot(x=x, y=y, hue=h)
+        assert len(ax.lines) == 7
+
+        plt.close("all")
+
+    def test_boxenplots(self):
+
+        # Smoke test the high level boxenplot options
+
+        cat.boxenplot(x="y", data=self.df)
+        plt.close("all")
+
+        cat.boxenplot(y="y", data=self.df)
+        plt.close("all")
+
+        cat.boxenplot(x="g", y="y", data=self.df)
+        plt.close("all")
+
+        cat.boxenplot(x="y", y="g", data=self.df, orient="h")
+        plt.close("all")
+
+        cat.boxenplot(x="g", y="y", hue="h", data=self.df)
+        plt.close("all")
+
+        for scale in ("linear", "area", "exponential"):
+            cat.boxenplot(x="g", y="y", hue="h", scale=scale, data=self.df)
+            plt.close("all")
+
+        for depth in ("proportion", "tukey", "trustworthy"):
+            cat.boxenplot(x="g", y="y", hue="h", k_depth=depth, data=self.df)
+            plt.close("all")
+
+        order = list("nabc")
+        cat.boxenplot(x="g", y="y", hue="h", order=order, data=self.df)
+        plt.close("all")
+
+        order = list("omn")
+        cat.boxenplot(x="g", y="y", hue="h", hue_order=order, data=self.df)
+        plt.close("all")
+
+        cat.boxenplot(x="y", y="g", hue="h", data=self.df, orient="h")
+        plt.close("all")
+
+        cat.boxenplot(x="y", y="g", hue="h", data=self.df, orient="h",
+                      palette="Set2")
+        plt.close("all")
+
+        cat.boxenplot(x="y", y="g", hue="h", data=self.df,
+                      orient="h", color="b")
+        plt.close("all")
+
+    def test_axes_annotation(self):
+
+        ax = cat.boxenplot(x="g", y="y", data=self.df)
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        assert ax.get_xlim() == (-.5, 2.5)
+        npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],
+                               ["a", "b", "c"])
+
+        plt.close("all")
+
+        ax = cat.boxenplot(x="g", y="y", hue="h", data=self.df)
+        assert ax.get_xlabel() == "g"
+        assert ax.get_ylabel() == "y"
+        npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],
+                               ["a", "b", "c"])
+        npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],
+                               ["m", "n"])
+
+        plt.close("all")
+
+        ax = cat.boxenplot(x="y", y="g", data=self.df, orient="h")
+        assert ax.get_xlabel() == "y"
+        assert ax.get_ylabel() == "g"
+        assert ax.get_ylim() == (2.5, -.5)
+        npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])
+        npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],
+                               ["a", "b", "c"])
+
+        plt.close("all")
+
+    @pytest.mark.parametrize("size", ["large", "medium", "small", 22, 12])
+    def test_legend_titlesize(self, size):
+
+        rc_ctx = {"legend.title_fontsize": size}
+        exp = mpl.font_manager.FontProperties(size=size).get_size()
+
+        with plt.rc_context(rc=rc_ctx):
+            ax = cat.boxenplot(x="g", y="y", hue="h", data=self.df)
+            obs = ax.get_legend().get_title().get_fontproperties().get_size()
+            assert obs == exp
+
+        plt.close("all")
+
+    @pytest.mark.skipif(
+        _version_predates(pd, "1.2"),
+        reason="Test requires pandas>=1.2")
+    def test_Float64_input(self):
+        data = pd.DataFrame(
+            {"x": np.random.choice(["a", "b"], 20), "y": np.random.random(20)}
+        )
+        data['y'] = data['y'].astype(pd.Float64Dtype())
+        _ = cat.boxenplot(x="x", y="y", data=data)
+
+        plt.close("all")
+
+    def test_line_kws(self):
+        line_kws = {'linewidth': 5, 'color': 'purple',
+                    'linestyle': '-.'}
+
+        ax = cat.boxenplot(data=self.df, y='y', line_kws=line_kws)
+
+        median_line = ax.lines[0]
+
+        assert median_line.get_linewidth() == line_kws['linewidth']
+        assert median_line.get_linestyle() == line_kws['linestyle']
+        assert median_line.get_color() == line_kws['color']
+
+        plt.close("all")
+
+    def test_flier_kws(self):
+        flier_kws = {
+            'marker': 'v',
+            'color': np.array([[1, 0, 0, 1]]),
+            's': 5,
+        }
+
+        ax = cat.boxenplot(data=self.df, y='y', x='g', flier_kws=flier_kws)
+
+        outliers_scatter = ax.findobj(mpl.collections.PathCollection)[0]
+
+        # The number of vertices for a triangle is 3, the length of Path
+        # collection objects is defined as n + 1 vertices.
+        assert len(outliers_scatter.get_paths()[0]) == 4
+        assert len(outliers_scatter.get_paths()[-1]) == 4
+
+        assert (outliers_scatter.get_facecolor() == flier_kws['color']).all()
+
+        assert np.unique(outliers_scatter.get_sizes()) == flier_kws['s']
+
+        plt.close("all")
+
+    def test_box_kws(self):
+
+        box_kws = {'linewidth': 5, 'edgecolor': np.array([[0, 1, 0, 1]])}
+
+        ax = cat.boxenplot(data=self.df, y='y', x='g',
+                           box_kws=box_kws)
+
+        boxes = ax.findobj(mpl.collections.PatchCollection)[0]
+
+        # The number of vertices for a triangle is 3, the length of Path
+        # collection objects is defined as n + 1 vertices.
+        assert len(boxes.get_paths()[0]) == 5
+        assert len(boxes.get_paths()[-1]) == 5
+
+        assert np.unique(boxes.get_linewidth() == box_kws['linewidth'])
+
+        plt.close("all")
+
+
+class TestBeeswarm:
+
+    def test_could_overlap(self):
+
+        p = Beeswarm()
+        neighbors = p.could_overlap(
+            (1, 1, .5),
+            [(0, 0, .5),
+             (1, .1, .2),
+             (.5, .5, .5)]
+        )
+        assert_array_equal(neighbors, [(.5, .5, .5)])
+
+    def test_position_candidates(self):
+
+        p = Beeswarm()
+        xy_i = (0, 1, .5)
+        neighbors = [(0, 1, .5), (0, 1.5, .5)]
+        candidates = p.position_candidates(xy_i, neighbors)
+        dx1 = 1.05
+        dx2 = np.sqrt(1 - .5 ** 2) * 1.05
+        assert_array_equal(
+            candidates,
+            [(0, 1, .5), (-dx1, 1, .5), (dx1, 1, .5), (dx2, 1, .5), (-dx2, 1, .5)]
+        )
+
+    def test_find_first_non_overlapping_candidate(self):
+
+        p = Beeswarm()
+        candidates = [(.5, 1, .5), (1, 1, .5), (1.5, 1, .5)]
+        neighbors = np.array([(0, 1, .5)])
+
+        first = p.first_non_overlapping_candidate(candidates, neighbors)
+        assert_array_equal(first, (1, 1, .5))
+
+    def test_beeswarm(self, long_df):
+
+        p = Beeswarm()
+        data = long_df["y"]
+        d = data.diff().mean() * 1.5
+        x = np.zeros(data.size)
+        y = np.sort(data)
+        r = np.full_like(y, d)
+        orig_xyr = np.c_[x, y, r]
+        swarm = p.beeswarm(orig_xyr)[:, :2]
+        dmat = np.sqrt(np.sum(np.square(swarm[:, np.newaxis] - swarm), axis=-1))
+        triu = dmat[np.triu_indices_from(dmat, 1)]
+        assert_array_less(d, triu)
+        assert_array_equal(y, swarm[:, 1])
+
+    def test_add_gutters(self):
+
+        p = Beeswarm(width=1)
+
+        points = np.zeros(10)
+        assert_array_equal(points, p.add_gutters(points, 0))
+
+        points = np.array([0, -1, .4, .8])
+        msg = r"50.0% of the points cannot be placed.+$"
+        with pytest.warns(UserWarning, match=msg):
+            new_points = p.add_gutters(points, 0)
+        assert_array_equal(new_points, np.array([0, -.5, .4, .5]))
diff --git a/testbed/mwaskom__seaborn/tests/test_core.py b/testbed/mwaskom__seaborn/tests/test_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..798a8d61fa4dbadb8dba77f8a81b1e3d1a0f06a5
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_core.py
@@ -0,0 +1,1556 @@
+import itertools
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+
+import pytest
+from numpy.testing import assert_array_equal
+from pandas.testing import assert_frame_equal
+
+from seaborn.axisgrid import FacetGrid
+from seaborn._compat import get_colormap
+from seaborn._oldcore import (
+    SemanticMapping,
+    HueMapping,
+    SizeMapping,
+    StyleMapping,
+    VectorPlotter,
+    variable_type,
+    infer_orient,
+    unique_dashes,
+    unique_markers,
+    categorical_order,
+)
+
+from seaborn.palettes import color_palette
+
+
+try:
+    from pandas import NA as PD_NA
+except ImportError:
+    PD_NA = None
+
+
+@pytest.fixture(params=[
+    dict(x="x", y="y"),
+    dict(x="t", y="y"),
+    dict(x="a", y="y"),
+    dict(x="x", y="y", hue="y"),
+    dict(x="x", y="y", hue="a"),
+    dict(x="x", y="y", size="a"),
+    dict(x="x", y="y", style="a"),
+    dict(x="x", y="y", hue="s"),
+    dict(x="x", y="y", size="s"),
+    dict(x="x", y="y", style="s"),
+    dict(x="x", y="y", hue="a", style="a"),
+    dict(x="x", y="y", hue="a", size="b", style="b"),
+])
+def long_variables(request):
+    return request.param
+
+
+class TestSemanticMapping:
+
+    def test_call_lookup(self):
+
+        m = SemanticMapping(VectorPlotter())
+        lookup_table = dict(zip("abc", (1, 2, 3)))
+        m.lookup_table = lookup_table
+        for key, val in lookup_table.items():
+            assert m(key) == val
+
+
+class TestHueMapping:
+
+    def test_init_from_map(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a")
+        )
+        palette = "Set2"
+        p = HueMapping.map(p_orig, palette=palette)
+        assert p is p_orig
+        assert isinstance(p._hue_map, HueMapping)
+        assert p._hue_map.palette == palette
+
+    def test_plotter_default_init(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+        assert isinstance(p._hue_map, HueMapping)
+        assert p._hue_map.map_type is None
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+        )
+        assert isinstance(p._hue_map, HueMapping)
+        assert p._hue_map.map_type == p.var_types["hue"]
+
+    def test_plotter_reinit(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+        )
+        palette = "muted"
+        hue_order = ["b", "a", "c"]
+        p = p_orig.map_hue(palette=palette, order=hue_order)
+        assert p is p_orig
+        assert p._hue_map.palette == palette
+        assert p._hue_map.levels == hue_order
+
+    def test_hue_map_null(self, flat_series, null_series):
+
+        p = VectorPlotter(variables=dict(x=flat_series, hue=null_series))
+        m = HueMapping(p)
+        assert m.levels is None
+        assert m.map_type is None
+        assert m.palette is None
+        assert m.cmap is None
+        assert m.norm is None
+        assert m.lookup_table is None
+
+    def test_hue_map_categorical(self, wide_df, long_df):
+
+        p = VectorPlotter(data=wide_df)
+        m = HueMapping(p)
+        assert m.levels == wide_df.columns.to_list()
+        assert m.map_type == "categorical"
+        assert m.cmap is None
+
+        # Test named palette
+        palette = "Blues"
+        expected_colors = color_palette(palette, wide_df.shape[1])
+        expected_lookup_table = dict(zip(wide_df.columns, expected_colors))
+        m = HueMapping(p, palette=palette)
+        assert m.palette == "Blues"
+        assert m.lookup_table == expected_lookup_table
+
+        # Test list palette
+        palette = color_palette("Reds", wide_df.shape[1])
+        expected_lookup_table = dict(zip(wide_df.columns, palette))
+        m = HueMapping(p, palette=palette)
+        assert m.palette == palette
+        assert m.lookup_table == expected_lookup_table
+
+        # Test dict palette
+        colors = color_palette("Set1", 8)
+        palette = dict(zip(wide_df.columns, colors))
+        m = HueMapping(p, palette=palette)
+        assert m.palette == palette
+        assert m.lookup_table == palette
+
+        # Test dict with missing keys
+        palette = dict(zip(wide_df.columns[:-1], colors))
+        with pytest.raises(ValueError):
+            HueMapping(p, palette=palette)
+
+        # Test list with wrong number of colors
+        palette = colors[:-1]
+        with pytest.warns(UserWarning):
+            HueMapping(p, palette=palette)
+
+        # Test hue order
+        hue_order = ["a", "c", "d"]
+        m = HueMapping(p, order=hue_order)
+        assert m.levels == hue_order
+
+        # Test long data
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="y", hue="a"))
+        m = HueMapping(p)
+        assert m.levels == categorical_order(long_df["a"])
+        assert m.map_type == "categorical"
+        assert m.cmap is None
+
+        # Test default palette
+        m = HueMapping(p)
+        hue_levels = categorical_order(long_df["a"])
+        expected_colors = color_palette(n_colors=len(hue_levels))
+        expected_lookup_table = dict(zip(hue_levels, expected_colors))
+        assert m.lookup_table == expected_lookup_table
+
+        # Test missing data
+        m = HueMapping(p)
+        assert m(np.nan) == (0, 0, 0, 0)
+
+        # Test default palette with many levels
+        x = y = np.arange(26)
+        hue = pd.Series(list("abcdefghijklmnopqrstuvwxyz"))
+        p = VectorPlotter(variables=dict(x=x, y=y, hue=hue))
+        m = HueMapping(p)
+        expected_colors = color_palette("husl", n_colors=len(hue))
+        expected_lookup_table = dict(zip(hue, expected_colors))
+        assert m.lookup_table == expected_lookup_table
+
+        # Test binary data
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="y", hue="c"))
+        m = HueMapping(p)
+        assert m.levels == [0, 1]
+        assert m.map_type == "categorical"
+
+        for val in [0, 1]:
+            p = VectorPlotter(
+                data=long_df[long_df["c"] == val],
+                variables=dict(x="x", y="y", hue="c"),
+            )
+            m = HueMapping(p)
+            assert m.levels == [val]
+            assert m.map_type == "categorical"
+
+        # Test Timestamp data
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="y", hue="t"))
+        m = HueMapping(p)
+        assert m.levels == [pd.Timestamp(t) for t in long_df["t"].unique()]
+        assert m.map_type == "datetime"
+
+        # Test explicit categories
+        p = VectorPlotter(data=long_df, variables=dict(x="x", hue="a_cat"))
+        m = HueMapping(p)
+        assert m.levels == long_df["a_cat"].cat.categories.to_list()
+        assert m.map_type == "categorical"
+
+        # Test numeric data with category type
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="s_cat")
+        )
+        m = HueMapping(p)
+        assert m.levels == categorical_order(long_df["s_cat"])
+        assert m.map_type == "categorical"
+        assert m.cmap is None
+
+        # Test categorical palette specified for numeric data
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="s")
+        )
+        palette = "deep"
+        levels = categorical_order(long_df["s"])
+        expected_colors = color_palette(palette, n_colors=len(levels))
+        expected_lookup_table = dict(zip(levels, expected_colors))
+        m = HueMapping(p, palette=palette)
+        assert m.lookup_table == expected_lookup_table
+        assert m.map_type == "categorical"
+
+    def test_hue_map_numeric(self, long_df):
+
+        vals = np.concatenate([np.linspace(0, 1, 256), [-.1, 1.1, np.nan]])
+
+        # Test default colormap
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="s")
+        )
+        hue_levels = list(np.sort(long_df["s"].unique()))
+        m = HueMapping(p)
+        assert m.levels == hue_levels
+        assert m.map_type == "numeric"
+        assert m.cmap.name == "seaborn_cubehelix"
+
+        # Test named colormap
+        palette = "Purples"
+        m = HueMapping(p, palette=palette)
+        assert_array_equal(m.cmap(vals), get_colormap(palette)(vals))
+
+        # Test colormap object
+        palette = get_colormap("Greens")
+        m = HueMapping(p, palette=palette)
+        assert_array_equal(m.cmap(vals), palette(vals))
+
+        # Test cubehelix shorthand
+        palette = "ch:2,0,light=.2"
+        m = HueMapping(p, palette=palette)
+        assert isinstance(m.cmap, mpl.colors.ListedColormap)
+
+        # Test specified hue limits
+        hue_norm = 1, 4
+        m = HueMapping(p, norm=hue_norm)
+        assert isinstance(m.norm, mpl.colors.Normalize)
+        assert m.norm.vmin == hue_norm[0]
+        assert m.norm.vmax == hue_norm[1]
+
+        # Test Normalize object
+        hue_norm = mpl.colors.PowerNorm(2, vmin=1, vmax=10)
+        m = HueMapping(p, norm=hue_norm)
+        assert m.norm is hue_norm
+
+        # Test default colormap values
+        hmin, hmax = p.plot_data["hue"].min(), p.plot_data["hue"].max()
+        m = HueMapping(p)
+        assert m.lookup_table[hmin] == pytest.approx(m.cmap(0.0))
+        assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))
+
+        # Test specified colormap values
+        hue_norm = hmin - 1, hmax - 1
+        m = HueMapping(p, norm=hue_norm)
+        norm_min = (hmin - hue_norm[0]) / (hue_norm[1] - hue_norm[0])
+        assert m.lookup_table[hmin] == pytest.approx(m.cmap(norm_min))
+        assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))
+
+        # Test list of colors
+        hue_levels = list(np.sort(long_df["s"].unique()))
+        palette = color_palette("Blues", len(hue_levels))
+        m = HueMapping(p, palette=palette)
+        assert m.lookup_table == dict(zip(hue_levels, palette))
+
+        palette = color_palette("Blues", len(hue_levels) + 1)
+        with pytest.warns(UserWarning):
+            HueMapping(p, palette=palette)
+
+        # Test dictionary of colors
+        palette = dict(zip(hue_levels, color_palette("Reds")))
+        m = HueMapping(p, palette=palette)
+        assert m.lookup_table == palette
+
+        palette.pop(hue_levels[0])
+        with pytest.raises(ValueError):
+            HueMapping(p, palette=palette)
+
+        # Test invalid palette
+        with pytest.raises(ValueError):
+            HueMapping(p, palette="not a valid palette")
+
+        # Test bad norm argument
+        with pytest.raises(ValueError):
+            HueMapping(p, norm="not a norm")
+
+    def test_hue_map_without_hue_dataa(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="y"))
+        with pytest.warns(UserWarning, match="Ignoring `palette`"):
+            HueMapping(p, palette="viridis")
+
+
+class TestSizeMapping:
+
+    def test_init_from_map(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="a")
+        )
+        sizes = 1, 6
+        p = SizeMapping.map(p_orig, sizes=sizes)
+        assert p is p_orig
+        assert isinstance(p._size_map, SizeMapping)
+        assert min(p._size_map.lookup_table.values()) == sizes[0]
+        assert max(p._size_map.lookup_table.values()) == sizes[1]
+
+    def test_plotter_default_init(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+        assert isinstance(p._size_map, SizeMapping)
+        assert p._size_map.map_type is None
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="a"),
+        )
+        assert isinstance(p._size_map, SizeMapping)
+        assert p._size_map.map_type == p.var_types["size"]
+
+    def test_plotter_reinit(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="a"),
+        )
+        sizes = [1, 4, 2]
+        size_order = ["b", "a", "c"]
+        p = p_orig.map_size(sizes=sizes, order=size_order)
+        assert p is p_orig
+        assert p._size_map.lookup_table == dict(zip(size_order, sizes))
+        assert p._size_map.levels == size_order
+
+    def test_size_map_null(self, flat_series, null_series):
+
+        p = VectorPlotter(variables=dict(x=flat_series, size=null_series))
+        m = HueMapping(p)
+        assert m.levels is None
+        assert m.map_type is None
+        assert m.norm is None
+        assert m.lookup_table is None
+
+    def test_map_size_numeric(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="s"),
+        )
+
+        # Test default range of keys in the lookup table values
+        m = SizeMapping(p)
+        size_values = m.lookup_table.values()
+        value_range = min(size_values), max(size_values)
+        assert value_range == p._default_size_range
+
+        # Test specified range of size values
+        sizes = 1, 5
+        m = SizeMapping(p, sizes=sizes)
+        size_values = m.lookup_table.values()
+        assert min(size_values), max(size_values) == sizes
+
+        # Test size values with normalization range
+        norm = 1, 10
+        m = SizeMapping(p, sizes=sizes, norm=norm)
+        normalize = mpl.colors.Normalize(*norm, clip=True)
+        for key, val in m.lookup_table.items():
+            assert val == sizes[0] + (sizes[1] - sizes[0]) * normalize(key)
+
+        # Test size values with normalization object
+        norm = mpl.colors.LogNorm(1, 10, clip=False)
+        m = SizeMapping(p, sizes=sizes, norm=norm)
+        assert m.norm.clip
+        for key, val in m.lookup_table.items():
+            assert val == sizes[0] + (sizes[1] - sizes[0]) * norm(key)
+
+        # Test bad sizes argument
+        with pytest.raises(ValueError):
+            SizeMapping(p, sizes="bad_sizes")
+
+        # Test bad sizes argument
+        with pytest.raises(ValueError):
+            SizeMapping(p, sizes=(1, 2, 3))
+
+        # Test bad norm argument
+        with pytest.raises(ValueError):
+            SizeMapping(p, norm="bad_norm")
+
+    def test_map_size_categorical(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="a"),
+        )
+
+        # Test specified size order
+        levels = p.plot_data["size"].unique()
+        sizes = [1, 4, 6]
+        order = [levels[1], levels[2], levels[0]]
+        m = SizeMapping(p, sizes=sizes, order=order)
+        assert m.lookup_table == dict(zip(order, sizes))
+
+        # Test list of sizes
+        order = categorical_order(p.plot_data["size"])
+        sizes = list(np.random.rand(len(levels)))
+        m = SizeMapping(p, sizes=sizes)
+        assert m.lookup_table == dict(zip(order, sizes))
+
+        # Test dict of sizes
+        sizes = dict(zip(levels, np.random.rand(len(levels))))
+        m = SizeMapping(p, sizes=sizes)
+        assert m.lookup_table == sizes
+
+        # Test specified size range
+        sizes = (2, 5)
+        m = SizeMapping(p, sizes=sizes)
+        values = np.linspace(*sizes, len(m.levels))[::-1]
+        assert m.lookup_table == dict(zip(m.levels, values))
+
+        # Test explicit categories
+        p = VectorPlotter(data=long_df, variables=dict(x="x", size="a_cat"))
+        m = SizeMapping(p)
+        assert m.levels == long_df["a_cat"].cat.categories.to_list()
+        assert m.map_type == "categorical"
+
+        # Test sizes list with wrong length
+        sizes = list(np.random.rand(len(levels) + 1))
+        with pytest.warns(UserWarning):
+            SizeMapping(p, sizes=sizes)
+
+        # Test sizes dict with missing levels
+        sizes = dict(zip(levels, np.random.rand(len(levels) - 1)))
+        with pytest.raises(ValueError):
+            SizeMapping(p, sizes=sizes)
+
+        # Test bad sizes argument
+        with pytest.raises(ValueError):
+            SizeMapping(p, sizes="bad_size")
+
+
+class TestStyleMapping:
+
+    def test_init_from_map(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", style="a")
+        )
+        markers = ["s", "p", "h"]
+        p = StyleMapping.map(p_orig, markers=markers)
+        assert p is p_orig
+        assert isinstance(p._style_map, StyleMapping)
+        assert p._style_map(p._style_map.levels, "marker") == markers
+
+    def test_plotter_default_init(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+        assert isinstance(p._style_map, StyleMapping)
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", style="a"),
+        )
+        assert isinstance(p._style_map, StyleMapping)
+
+    def test_plotter_reinit(self, long_df):
+
+        p_orig = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", style="a"),
+        )
+        markers = ["s", "p", "h"]
+        style_order = ["b", "a", "c"]
+        p = p_orig.map_style(markers=markers, order=style_order)
+        assert p is p_orig
+        assert p._style_map.levels == style_order
+        assert p._style_map(style_order, "marker") == markers
+
+    def test_style_map_null(self, flat_series, null_series):
+
+        p = VectorPlotter(variables=dict(x=flat_series, style=null_series))
+        m = HueMapping(p)
+        assert m.levels is None
+        assert m.map_type is None
+        assert m.lookup_table is None
+
+    def test_map_style(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", style="a"),
+        )
+
+        # Test defaults
+        m = StyleMapping(p, markers=True, dashes=True)
+
+        n = len(m.levels)
+        for key, dashes in zip(m.levels, unique_dashes(n)):
+            assert m(key, "dashes") == dashes
+
+        actual_marker_paths = {
+            k: mpl.markers.MarkerStyle(m(k, "marker")).get_path()
+            for k in m.levels
+        }
+        expected_marker_paths = {
+            k: mpl.markers.MarkerStyle(m).get_path()
+            for k, m in zip(m.levels, unique_markers(n))
+        }
+        assert actual_marker_paths == expected_marker_paths
+
+        # Test lists
+        markers, dashes = ["o", "s", "d"], [(1, 0), (1, 1), (2, 1, 3, 1)]
+        m = StyleMapping(p, markers=markers, dashes=dashes)
+        for key, mark, dash in zip(m.levels, markers, dashes):
+            assert m(key, "marker") == mark
+            assert m(key, "dashes") == dash
+
+        # Test dicts
+        markers = dict(zip(p.plot_data["style"].unique(), markers))
+        dashes = dict(zip(p.plot_data["style"].unique(), dashes))
+        m = StyleMapping(p, markers=markers, dashes=dashes)
+        for key in m.levels:
+            assert m(key, "marker") == markers[key]
+            assert m(key, "dashes") == dashes[key]
+
+        # Test explicit categories
+        p = VectorPlotter(data=long_df, variables=dict(x="x", style="a_cat"))
+        m = StyleMapping(p)
+        assert m.levels == long_df["a_cat"].cat.categories.to_list()
+
+        # Test style order with defaults
+        order = p.plot_data["style"].unique()[[1, 2, 0]]
+        m = StyleMapping(p, markers=True, dashes=True, order=order)
+        n = len(order)
+        for key, mark, dash in zip(order, unique_markers(n), unique_dashes(n)):
+            assert m(key, "dashes") == dash
+            assert m(key, "marker") == mark
+            obj = mpl.markers.MarkerStyle(mark)
+            path = obj.get_path().transformed(obj.get_transform())
+            assert_array_equal(m(key, "path").vertices, path.vertices)
+
+        # Test too many levels with style lists
+        with pytest.warns(UserWarning):
+            StyleMapping(p, markers=["o", "s"], dashes=False)
+
+        with pytest.warns(UserWarning):
+            StyleMapping(p, markers=False, dashes=[(2, 1)])
+
+        # Test missing keys with style dicts
+        markers, dashes = {"a": "o", "b": "s"}, False
+        with pytest.raises(ValueError):
+            StyleMapping(p, markers=markers, dashes=dashes)
+
+        markers, dashes = False, {"a": (1, 0), "b": (2, 1)}
+        with pytest.raises(ValueError):
+            StyleMapping(p, markers=markers, dashes=dashes)
+
+        # Test mixture of filled and unfilled markers
+        markers, dashes = ["o", "x", "s"], None
+        with pytest.raises(ValueError):
+            StyleMapping(p, markers=markers, dashes=dashes)
+
+
+class TestVectorPlotter:
+
+    def test_flat_variables(self, flat_data):
+
+        p = VectorPlotter()
+        p.assign_variables(data=flat_data)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y"]
+        assert len(p.plot_data) == len(flat_data)
+
+        try:
+            expected_x = flat_data.index
+            expected_x_name = flat_data.index.name
+        except AttributeError:
+            expected_x = np.arange(len(flat_data))
+            expected_x_name = None
+
+        x = p.plot_data["x"]
+        assert_array_equal(x, expected_x)
+
+        expected_y = flat_data
+        expected_y_name = getattr(flat_data, "name", None)
+
+        y = p.plot_data["y"]
+        assert_array_equal(y, expected_y)
+
+        assert p.variables["x"] == expected_x_name
+        assert p.variables["y"] == expected_y_name
+
+    def test_long_df(self, long_df, long_variables):
+
+        p = VectorPlotter()
+        p.assign_variables(data=long_df, variables=long_variables)
+        assert p.input_format == "long"
+        assert p.variables == long_variables
+
+        for key, val in long_variables.items():
+            assert_array_equal(p.plot_data[key], long_df[val])
+
+    def test_long_df_with_index(self, long_df, long_variables):
+
+        p = VectorPlotter()
+        p.assign_variables(
+            data=long_df.set_index("a"),
+            variables=long_variables,
+        )
+        assert p.input_format == "long"
+        assert p.variables == long_variables
+
+        for key, val in long_variables.items():
+            assert_array_equal(p.plot_data[key], long_df[val])
+
+    def test_long_df_with_multiindex(self, long_df, long_variables):
+
+        p = VectorPlotter()
+        p.assign_variables(
+            data=long_df.set_index(["a", "x"]),
+            variables=long_variables,
+        )
+        assert p.input_format == "long"
+        assert p.variables == long_variables
+
+        for key, val in long_variables.items():
+            assert_array_equal(p.plot_data[key], long_df[val])
+
+    def test_long_dict(self, long_dict, long_variables):
+
+        p = VectorPlotter()
+        p.assign_variables(
+            data=long_dict,
+            variables=long_variables,
+        )
+        assert p.input_format == "long"
+        assert p.variables == long_variables
+
+        for key, val in long_variables.items():
+            assert_array_equal(p.plot_data[key], pd.Series(long_dict[val]))
+
+    @pytest.mark.parametrize(
+        "vector_type",
+        ["series", "numpy", "list"],
+    )
+    def test_long_vectors(self, long_df, long_variables, vector_type):
+
+        variables = {key: long_df[val] for key, val in long_variables.items()}
+        if vector_type == "numpy":
+            variables = {key: val.to_numpy() for key, val in variables.items()}
+        elif vector_type == "list":
+            variables = {key: val.to_list() for key, val in variables.items()}
+
+        p = VectorPlotter()
+        p.assign_variables(variables=variables)
+        assert p.input_format == "long"
+
+        assert list(p.variables) == list(long_variables)
+        if vector_type == "series":
+            assert p.variables == long_variables
+
+        for key, val in long_variables.items():
+            assert_array_equal(p.plot_data[key], long_df[val])
+
+    def test_long_undefined_variables(self, long_df):
+
+        p = VectorPlotter()
+
+        with pytest.raises(ValueError):
+            p.assign_variables(
+                data=long_df, variables=dict(x="not_in_df"),
+            )
+
+        with pytest.raises(ValueError):
+            p.assign_variables(
+                data=long_df, variables=dict(x="x", y="not_in_df"),
+            )
+
+        with pytest.raises(ValueError):
+            p.assign_variables(
+                data=long_df, variables=dict(x="x", y="y", hue="not_in_df"),
+            )
+
+    @pytest.mark.parametrize(
+        "arg", [[], np.array([]), pd.DataFrame()],
+    )
+    def test_empty_data_input(self, arg):
+
+        p = VectorPlotter()
+        p.assign_variables(data=arg)
+        assert not p.variables
+
+        if not isinstance(arg, pd.DataFrame):
+            p = VectorPlotter()
+            p.assign_variables(variables=dict(x=arg, y=arg))
+            assert not p.variables
+
+    def test_units(self, repeated_df):
+
+        p = VectorPlotter()
+        p.assign_variables(
+            data=repeated_df,
+            variables=dict(x="x", y="y", units="u"),
+        )
+        assert_array_equal(p.plot_data["units"], repeated_df["u"])
+
+    @pytest.mark.parametrize("name", [3, 4.5])
+    def test_long_numeric_name(self, long_df, name):
+
+        long_df[name] = long_df["x"]
+        p = VectorPlotter()
+        p.assign_variables(data=long_df, variables={"x": name})
+        assert_array_equal(p.plot_data["x"], long_df[name])
+        assert p.variables["x"] == name
+
+    def test_long_hierarchical_index(self, rng):
+
+        cols = pd.MultiIndex.from_product([["a"], ["x", "y"]])
+        data = rng.uniform(size=(50, 2))
+        df = pd.DataFrame(data, columns=cols)
+
+        name = ("a", "y")
+        var = "y"
+
+        p = VectorPlotter()
+        p.assign_variables(data=df, variables={var: name})
+        assert_array_equal(p.plot_data[var], df[name])
+        assert p.variables[var] == name
+
+    def test_long_scalar_and_data(self, long_df):
+
+        val = 22
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": val})
+        assert (p.plot_data["y"] == val).all()
+        assert p.variables["y"] is None
+
+    def test_wide_semantic_error(self, wide_df):
+
+        err = "The following variable cannot be assigned with wide-form data: `hue`"
+        with pytest.raises(ValueError, match=err):
+            VectorPlotter(data=wide_df, variables={"hue": "a"})
+
+    def test_long_unknown_error(self, long_df):
+
+        err = "Could not interpret value `what` for parameter `hue`"
+        with pytest.raises(ValueError, match=err):
+            VectorPlotter(data=long_df, variables={"x": "x", "hue": "what"})
+
+    def test_long_unmatched_size_error(self, long_df, flat_array):
+
+        err = "Length of ndarray vectors must match length of `data`"
+        with pytest.raises(ValueError, match=err):
+            VectorPlotter(data=long_df, variables={"x": "x", "hue": flat_array})
+
+    def test_wide_categorical_columns(self, wide_df):
+
+        wide_df.columns = pd.CategoricalIndex(wide_df.columns)
+        p = VectorPlotter(data=wide_df)
+        assert_array_equal(p.plot_data["hue"].unique(), ["a", "b", "c"])
+
+    def test_iter_data_quantitites(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+        out = p.iter_data("hue")
+        assert len(list(out)) == 1
+
+        var = "a"
+        n_subsets = len(long_df[var].unique())
+
+        semantics = ["hue", "size", "style"]
+        for semantic in semantics:
+
+            p = VectorPlotter(
+                data=long_df,
+                variables={"x": "x", "y": "y", semantic: var},
+            )
+            out = p.iter_data(semantics)
+            assert len(list(out)) == n_subsets
+
+        var = "a"
+        n_subsets = len(long_df[var].unique())
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var, style=var),
+        )
+        out = p.iter_data(semantics)
+        assert len(list(out)) == n_subsets
+
+        # --
+
+        out = p.iter_data(semantics, reverse=True)
+        assert len(list(out)) == n_subsets
+
+        # --
+
+        var1, var2 = "a", "s"
+
+        n_subsets = len(long_df[var1].unique())
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, style=var2),
+        )
+        out = p.iter_data(["hue"])
+        assert len(list(out)) == n_subsets
+
+        n_subsets = len(set(list(map(tuple, long_df[[var1, var2]].values))))
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, style=var2),
+        )
+        out = p.iter_data(semantics)
+        assert len(list(out)) == n_subsets
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, size=var2, style=var1),
+        )
+        out = p.iter_data(semantics)
+        assert len(list(out)) == n_subsets
+
+        # --
+
+        var1, var2, var3 = "a", "s", "b"
+        cols = [var1, var2, var3]
+        n_subsets = len(set(list(map(tuple, long_df[cols].values))))
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, size=var2, style=var3),
+        )
+        out = p.iter_data(semantics)
+        assert len(list(out)) == n_subsets
+
+    def test_iter_data_keys(self, long_df):
+
+        semantics = ["hue", "size", "style"]
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+        for sub_vars, _ in p.iter_data("hue"):
+            assert sub_vars == {}
+
+        # --
+
+        var = "a"
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var),
+        )
+        for sub_vars, _ in p.iter_data("hue"):
+            assert list(sub_vars) == ["hue"]
+            assert sub_vars["hue"] in long_df[var].values
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size=var),
+        )
+        for sub_vars, _ in p.iter_data("size"):
+            assert list(sub_vars) == ["size"]
+            assert sub_vars["size"] in long_df[var].values
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var, style=var),
+        )
+        for sub_vars, _ in p.iter_data(semantics):
+            assert list(sub_vars) == ["hue", "style"]
+            assert sub_vars["hue"] in long_df[var].values
+            assert sub_vars["style"] in long_df[var].values
+            assert sub_vars["hue"] == sub_vars["style"]
+
+        var1, var2 = "a", "s"
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, size=var2),
+        )
+        for sub_vars, _ in p.iter_data(semantics):
+            assert list(sub_vars) == ["hue", "size"]
+            assert sub_vars["hue"] in long_df[var1].values
+            assert sub_vars["size"] in long_df[var2].values
+
+        semantics = ["hue", "col", "row"]
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=var1, col=var2),
+        )
+        for sub_vars, _ in p.iter_data("hue"):
+            assert list(sub_vars) == ["hue", "col"]
+            assert sub_vars["hue"] in long_df[var1].values
+            assert sub_vars["col"] in long_df[var2].values
+
+    def test_iter_data_values(self, long_df):
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+
+        p.sort = True
+        _, sub_data = next(p.iter_data("hue"))
+        assert_frame_equal(sub_data, p.plot_data)
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+        )
+
+        for sub_vars, sub_data in p.iter_data("hue"):
+            rows = p.plot_data["hue"] == sub_vars["hue"]
+            assert_frame_equal(sub_data, p.plot_data[rows])
+
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", size="s"),
+        )
+        for sub_vars, sub_data in p.iter_data(["hue", "size"]):
+            rows = p.plot_data["hue"] == sub_vars["hue"]
+            rows &= p.plot_data["size"] == sub_vars["size"]
+            assert_frame_equal(sub_data, p.plot_data[rows])
+
+    def test_iter_data_reverse(self, long_df):
+
+        reversed_order = categorical_order(long_df["a"])[::-1]
+        p = VectorPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a")
+        )
+        iterator = p.iter_data("hue", reverse=True)
+        for i, (sub_vars, _) in enumerate(iterator):
+            assert sub_vars["hue"] == reversed_order[i]
+
+    def test_iter_data_dropna(self, missing_df):
+
+        p = VectorPlotter(
+            data=missing_df,
+            variables=dict(x="x", y="y", hue="a")
+        )
+        for _, sub_df in p.iter_data("hue"):
+            assert not sub_df.isna().any().any()
+
+        some_missing = False
+        for _, sub_df in p.iter_data("hue", dropna=False):
+            some_missing |= sub_df.isna().any().any()
+        assert some_missing
+
+    def test_axis_labels(self, long_df):
+
+        f, ax = plt.subplots()
+
+        p = VectorPlotter(data=long_df, variables=dict(x="a"))
+
+        p._add_axis_labels(ax)
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == ""
+        ax.clear()
+
+        p = VectorPlotter(data=long_df, variables=dict(y="a"))
+        p._add_axis_labels(ax)
+        assert ax.get_xlabel() == ""
+        assert ax.get_ylabel() == "a"
+        ax.clear()
+
+        p = VectorPlotter(data=long_df, variables=dict(x="a"))
+
+        p._add_axis_labels(ax, default_y="default")
+        assert ax.get_xlabel() == "a"
+        assert ax.get_ylabel() == "default"
+        ax.clear()
+
+        p = VectorPlotter(data=long_df, variables=dict(y="a"))
+        p._add_axis_labels(ax, default_x="default", default_y="default")
+        assert ax.get_xlabel() == "default"
+        assert ax.get_ylabel() == "a"
+        ax.clear()
+
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="a"))
+        ax.set(xlabel="existing", ylabel="also existing")
+        p._add_axis_labels(ax)
+        assert ax.get_xlabel() == "existing"
+        assert ax.get_ylabel() == "also existing"
+
+        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
+        p = VectorPlotter(data=long_df, variables=dict(x="x", y="y"))
+
+        p._add_axis_labels(ax1)
+        p._add_axis_labels(ax2)
+
+        assert ax1.get_xlabel() == "x"
+        assert ax1.get_ylabel() == "y"
+        assert ax1.yaxis.label.get_visible()
+
+        assert ax2.get_xlabel() == "x"
+        assert ax2.get_ylabel() == "y"
+        assert not ax2.yaxis.label.get_visible()
+
+    @pytest.mark.parametrize(
+        "variables",
+        [
+            dict(x="x", y="y"),
+            dict(x="x"),
+            dict(y="y"),
+            dict(x="t", y="y"),
+            dict(x="x", y="a"),
+        ]
+    )
+    def test_attach_basics(self, long_df, variables):
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables=variables)
+        p._attach(ax)
+        assert p.ax is ax
+
+    def test_attach_disallowed(self, long_df):
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "a"})
+
+        with pytest.raises(TypeError):
+            p._attach(ax, allowed_types="numeric")
+
+        with pytest.raises(TypeError):
+            p._attach(ax, allowed_types=["datetime", "numeric"])
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x"})
+
+        with pytest.raises(TypeError):
+            p._attach(ax, allowed_types="categorical")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "t"})
+
+        with pytest.raises(TypeError):
+            p._attach(ax, allowed_types=["numeric", "categorical"])
+
+    def test_attach_log_scale(self, long_df):
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x"})
+        p._attach(ax, log_scale=True)
+        assert ax.xaxis.get_scale() == "log"
+        assert ax.yaxis.get_scale() == "linear"
+        assert p._log_scaled("x")
+        assert not p._log_scaled("y")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x"})
+        p._attach(ax, log_scale=2)
+        assert ax.xaxis.get_scale() == "log"
+        assert ax.yaxis.get_scale() == "linear"
+        assert p._log_scaled("x")
+        assert not p._log_scaled("y")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"y": "y"})
+        p._attach(ax, log_scale=True)
+        assert ax.xaxis.get_scale() == "linear"
+        assert ax.yaxis.get_scale() == "log"
+        assert not p._log_scaled("x")
+        assert p._log_scaled("y")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y"})
+        p._attach(ax, log_scale=True)
+        assert ax.xaxis.get_scale() == "log"
+        assert ax.yaxis.get_scale() == "log"
+        assert p._log_scaled("x")
+        assert p._log_scaled("y")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y"})
+        p._attach(ax, log_scale=(True, False))
+        assert ax.xaxis.get_scale() == "log"
+        assert ax.yaxis.get_scale() == "linear"
+        assert p._log_scaled("x")
+        assert not p._log_scaled("y")
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y"})
+        p._attach(ax, log_scale=(False, 2))
+        assert ax.xaxis.get_scale() == "linear"
+        assert ax.yaxis.get_scale() == "log"
+        assert not p._log_scaled("x")
+        assert p._log_scaled("y")
+
+    def test_attach_converters(self, long_df):
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "t"})
+        p._attach(ax)
+        assert ax.xaxis.converter is None
+        assert "Date" in ax.yaxis.converter.__class__.__name__
+
+        _, ax = plt.subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "a", "y": "y"})
+        p._attach(ax)
+        assert "CategoryConverter" in ax.xaxis.converter.__class__.__name__
+        assert ax.yaxis.converter is None
+
+    def test_attach_facets(self, long_df):
+
+        g = FacetGrid(long_df, col="a")
+        p = VectorPlotter(data=long_df, variables={"x": "x", "col": "a"})
+        p._attach(g)
+        assert p.ax is None
+        assert p.facets == g
+
+    def test_attach_shared_axes(self, long_df):
+
+        g = FacetGrid(long_df)
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y"})
+        p._attach(g)
+        assert p.converters["x"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a")
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y", "col": "a"})
+        p._attach(g)
+        assert p.converters["x"].nunique() == 1
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", sharex=False)
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y", "col": "a"})
+        p._attach(g)
+        assert p.converters["x"].nunique() == p.plot_data["col"].nunique()
+        assert p.converters["x"].groupby(p.plot_data["col"]).nunique().max() == 1
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", sharex=False, col_wrap=2)
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "y", "col": "a"})
+        p._attach(g)
+        assert p.converters["x"].nunique() == p.plot_data["col"].nunique()
+        assert p.converters["x"].groupby(p.plot_data["col"]).nunique().max() == 1
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", row="b")
+        p = VectorPlotter(
+            data=long_df, variables={"x": "x", "y": "y", "col": "a", "row": "b"},
+        )
+        p._attach(g)
+        assert p.converters["x"].nunique() == 1
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", row="b", sharex=False)
+        p = VectorPlotter(
+            data=long_df, variables={"x": "x", "y": "y", "col": "a", "row": "b"},
+        )
+        p._attach(g)
+        assert p.converters["x"].nunique() == len(g.axes.flat)
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", row="b", sharex="col")
+        p = VectorPlotter(
+            data=long_df, variables={"x": "x", "y": "y", "col": "a", "row": "b"},
+        )
+        p._attach(g)
+        assert p.converters["x"].nunique() == p.plot_data["col"].nunique()
+        assert p.converters["x"].groupby(p.plot_data["col"]).nunique().max() == 1
+        assert p.converters["y"].nunique() == 1
+
+        g = FacetGrid(long_df, col="a", row="b", sharey="row")
+        p = VectorPlotter(
+            data=long_df, variables={"x": "x", "y": "y", "col": "a", "row": "b"},
+        )
+        p._attach(g)
+        assert p.converters["x"].nunique() == 1
+        assert p.converters["y"].nunique() == p.plot_data["row"].nunique()
+        assert p.converters["y"].groupby(p.plot_data["row"]).nunique().max() == 1
+
+    def test_get_axes_single(self, long_df):
+
+        ax = plt.figure().subplots()
+        p = VectorPlotter(data=long_df, variables={"x": "x", "hue": "a"})
+        p._attach(ax)
+        assert p._get_axes({"hue": "a"}) is ax
+
+    def test_get_axes_facets(self, long_df):
+
+        g = FacetGrid(long_df, col="a")
+        p = VectorPlotter(data=long_df, variables={"x": "x", "col": "a"})
+        p._attach(g)
+        assert p._get_axes({"col": "b"}) is g.axes_dict["b"]
+
+        g = FacetGrid(long_df, col="a", row="c")
+        p = VectorPlotter(
+            data=long_df, variables={"x": "x", "col": "a", "row": "c"}
+        )
+        p._attach(g)
+        assert p._get_axes({"row": 1, "col": "b"}) is g.axes_dict[(1, "b")]
+
+    def test_comp_data(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"x": "x", "y": "t"})
+
+        # We have disabled this check for now, while it remains part of
+        # the internal API, because it will require updating a number of tests
+        # with pytest.raises(AttributeError):
+        #     p.comp_data
+
+        _, ax = plt.subplots()
+        p._attach(ax)
+
+        assert_array_equal(p.comp_data["x"], p.plot_data["x"])
+        assert_array_equal(
+            p.comp_data["y"], ax.yaxis.convert_units(p.plot_data["y"])
+        )
+
+        p = VectorPlotter(data=long_df, variables={"x": "a"})
+
+        _, ax = plt.subplots()
+        p._attach(ax)
+
+        assert_array_equal(
+            p.comp_data["x"], ax.xaxis.convert_units(p.plot_data["x"])
+        )
+
+    def test_comp_data_log(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"x": "z", "y": "y"})
+        _, ax = plt.subplots()
+        p._attach(ax, log_scale=(True, False))
+
+        assert_array_equal(
+            p.comp_data["x"], np.log10(p.plot_data["x"])
+        )
+        assert_array_equal(p.comp_data["y"], p.plot_data["y"])
+
+    def test_comp_data_category_order(self):
+
+        s = (pd.Series(["a", "b", "c", "a"], dtype="category")
+             .cat.set_categories(["b", "c", "a"], ordered=True))
+
+        p = VectorPlotter(variables={"x": s})
+        _, ax = plt.subplots()
+        p._attach(ax)
+        assert_array_equal(
+            p.comp_data["x"],
+            [2, 0, 1, 2],
+        )
+
+    @pytest.fixture(
+        params=itertools.product(
+            [None, np.nan, PD_NA],
+            ["numeric", "category", "datetime"]
+        )
+    )
+    @pytest.mark.parametrize(
+        "NA,var_type",
+    )
+    def comp_data_missing_fixture(self, request):
+
+        # This fixture holds the logic for parameterizing
+        # the following test (test_comp_data_missing)
+
+        NA, var_type = request.param
+
+        if NA is None:
+            pytest.skip("No pandas.NA available")
+
+        comp_data = [0, 1, np.nan, 2, np.nan, 1]
+        if var_type == "numeric":
+            orig_data = [0, 1, NA, 2, np.inf, 1]
+        elif var_type == "category":
+            orig_data = ["a", "b", NA, "c", NA, "b"]
+        elif var_type == "datetime":
+            # Use 1-based numbers to avoid issue on matplotlib<3.2
+            # Could simplify the test a bit when we roll off that version
+            comp_data = [1, 2, np.nan, 3, np.nan, 2]
+            numbers = [1, 2, 3, 2]
+
+            orig_data = mpl.dates.num2date(numbers)
+            orig_data.insert(2, NA)
+            orig_data.insert(4, np.inf)
+
+        return orig_data, comp_data
+
+    def test_comp_data_missing(self, comp_data_missing_fixture):
+
+        orig_data, comp_data = comp_data_missing_fixture
+        p = VectorPlotter(variables={"x": orig_data})
+        ax = plt.figure().subplots()
+        p._attach(ax)
+        assert_array_equal(p.comp_data["x"], comp_data)
+
+    def test_comp_data_duplicate_index(self):
+
+        x = pd.Series([1, 2, 3, 4, 5], [1, 1, 1, 2, 2])
+        p = VectorPlotter(variables={"x": x})
+        ax = plt.figure().subplots()
+        p._attach(ax)
+        assert_array_equal(p.comp_data["x"], x)
+
+    def test_var_order(self, long_df):
+
+        order = ["c", "b", "a"]
+        for var in ["hue", "size", "style"]:
+            p = VectorPlotter(data=long_df, variables={"x": "x", var: "a"})
+
+            mapper = getattr(p, f"map_{var}")
+            mapper(order=order)
+
+            assert p.var_levels[var] == order
+
+    def test_scale_native(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"x": "x"})
+        with pytest.raises(NotImplementedError):
+            p.scale_native("x")
+
+    def test_scale_numeric(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"y": "y"})
+        with pytest.raises(NotImplementedError):
+            p.scale_numeric("y")
+
+    def test_scale_datetime(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"x": "t"})
+        with pytest.raises(NotImplementedError):
+            p.scale_datetime("x")
+
+    def test_scale_categorical(self, long_df):
+
+        p = VectorPlotter(data=long_df, variables={"x": "x"})
+        p.scale_categorical("y")
+        assert p.variables["y"] is None
+        assert p.var_types["y"] == "categorical"
+        assert (p.plot_data["y"] == "").all()
+
+        p = VectorPlotter(data=long_df, variables={"x": "s"})
+        p.scale_categorical("x")
+        assert p.var_types["x"] == "categorical"
+        assert hasattr(p.plot_data["x"], "str")
+        assert not p._var_ordered["x"]
+        assert p.plot_data["x"].is_monotonic_increasing
+        assert_array_equal(p.var_levels["x"], p.plot_data["x"].unique())
+
+        p = VectorPlotter(data=long_df, variables={"x": "a"})
+        p.scale_categorical("x")
+        assert not p._var_ordered["x"]
+        assert_array_equal(p.var_levels["x"], categorical_order(long_df["a"]))
+
+        p = VectorPlotter(data=long_df, variables={"x": "a_cat"})
+        p.scale_categorical("x")
+        assert p._var_ordered["x"]
+        assert_array_equal(p.var_levels["x"], categorical_order(long_df["a_cat"]))
+
+        p = VectorPlotter(data=long_df, variables={"x": "a"})
+        order = np.roll(long_df["a"].unique(), 1)
+        p.scale_categorical("x", order=order)
+        assert p._var_ordered["x"]
+        assert_array_equal(p.var_levels["x"], order)
+
+        p = VectorPlotter(data=long_df, variables={"x": "s"})
+        p.scale_categorical("x", formatter=lambda x: f"{x:%}")
+        assert p.plot_data["x"].str.endswith("%").all()
+        assert all(s.endswith("%") for s in p.var_levels["x"])
+
+
+class TestCoreFunc:
+
+    def test_unique_dashes(self):
+
+        n = 24
+        dashes = unique_dashes(n)
+
+        assert len(dashes) == n
+        assert len(set(dashes)) == n
+        assert dashes[0] == ""
+        for spec in dashes[1:]:
+            assert isinstance(spec, tuple)
+            assert not len(spec) % 2
+
+    def test_unique_markers(self):
+
+        n = 24
+        markers = unique_markers(n)
+
+        assert len(markers) == n
+        assert len(set(markers)) == n
+        for m in markers:
+            assert mpl.markers.MarkerStyle(m).is_filled()
+
+    def test_variable_type(self):
+
+        s = pd.Series([1., 2., 3.])
+        assert variable_type(s) == "numeric"
+        assert variable_type(s.astype(int)) == "numeric"
+        assert variable_type(s.astype(object)) == "numeric"
+        assert variable_type(s.to_numpy()) == "numeric"
+        assert variable_type(s.to_list()) == "numeric"
+
+        s = pd.Series([1, 2, 3, np.nan], dtype=object)
+        assert variable_type(s) == "numeric"
+
+        s = pd.Series([np.nan, np.nan])
+        # s = pd.Series([pd.NA, pd.NA])
+        assert variable_type(s) == "numeric"
+
+        s = pd.Series(["1", "2", "3"])
+        assert variable_type(s) == "categorical"
+        assert variable_type(s.to_numpy()) == "categorical"
+        assert variable_type(s.to_list()) == "categorical"
+
+        s = pd.Series([True, False, False])
+        assert variable_type(s) == "numeric"
+        assert variable_type(s, boolean_type="categorical") == "categorical"
+        s_cat = s.astype("category")
+        assert variable_type(s_cat, boolean_type="categorical") == "categorical"
+        assert variable_type(s_cat, boolean_type="numeric") == "categorical"
+
+        s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])
+        assert variable_type(s) == "datetime"
+        assert variable_type(s.astype(object)) == "datetime"
+        assert variable_type(s.to_numpy()) == "datetime"
+        assert variable_type(s.to_list()) == "datetime"
+
+    def test_infer_orient(self):
+
+        nums = pd.Series(np.arange(6))
+        cats = pd.Series(["a", "b"] * 3)
+        dates = pd.date_range("1999-09-22", "2006-05-14", 6)
+
+        assert infer_orient(cats, nums) == "v"
+        assert infer_orient(nums, cats) == "h"
+
+        assert infer_orient(cats, dates, require_numeric=False) == "v"
+        assert infer_orient(dates, cats, require_numeric=False) == "h"
+
+        assert infer_orient(nums, None) == "h"
+        with pytest.warns(UserWarning, match="Vertical .+ `x`"):
+            assert infer_orient(nums, None, "v") == "h"
+
+        assert infer_orient(None, nums) == "v"
+        with pytest.warns(UserWarning, match="Horizontal .+ `y`"):
+            assert infer_orient(None, nums, "h") == "v"
+
+        infer_orient(cats, None, require_numeric=False) == "h"
+        with pytest.raises(TypeError, match="Horizontal .+ `x`"):
+            infer_orient(cats, None)
+
+        infer_orient(cats, None, require_numeric=False) == "v"
+        with pytest.raises(TypeError, match="Vertical .+ `y`"):
+            infer_orient(None, cats)
+
+        assert infer_orient(nums, nums, "vert") == "v"
+        assert infer_orient(nums, nums, "hori") == "h"
+
+        assert infer_orient(cats, cats, "h", require_numeric=False) == "h"
+        assert infer_orient(cats, cats, "v", require_numeric=False) == "v"
+        assert infer_orient(cats, cats, require_numeric=False) == "v"
+
+        with pytest.raises(TypeError, match="Vertical .+ `y`"):
+            infer_orient(cats, cats, "v")
+        with pytest.raises(TypeError, match="Horizontal .+ `x`"):
+            infer_orient(cats, cats, "h")
+        with pytest.raises(TypeError, match="Neither"):
+            infer_orient(cats, cats)
+
+        with pytest.raises(ValueError, match="`orient` must start with"):
+            infer_orient(cats, nums, orient="bad value")
+
+    def test_categorical_order(self):
+
+        x = ["a", "c", "c", "b", "a", "d"]
+        y = [3, 2, 5, 1, 4]
+        order = ["a", "b", "c", "d"]
+
+        out = categorical_order(x)
+        assert out == ["a", "c", "b", "d"]
+
+        out = categorical_order(x, order)
+        assert out == order
+
+        out = categorical_order(x, ["b", "a"])
+        assert out == ["b", "a"]
+
+        out = categorical_order(np.array(x))
+        assert out == ["a", "c", "b", "d"]
+
+        out = categorical_order(pd.Series(x))
+        assert out == ["a", "c", "b", "d"]
+
+        out = categorical_order(y)
+        assert out == [1, 2, 3, 4, 5]
+
+        out = categorical_order(np.array(y))
+        assert out == [1, 2, 3, 4, 5]
+
+        out = categorical_order(pd.Series(y))
+        assert out == [1, 2, 3, 4, 5]
+
+        x = pd.Categorical(x, order)
+        out = categorical_order(x)
+        assert out == list(x.categories)
+
+        x = pd.Series(x)
+        out = categorical_order(x)
+        assert out == list(x.cat.categories)
+
+        out = categorical_order(x, ["b", "a"])
+        assert out == ["b", "a"]
+
+        x = ["a", np.nan, "c", "c", "b", "a", "d"]
+        out = categorical_order(x)
+        assert out == ["a", "c", "b", "d"]
diff --git a/testbed/mwaskom__seaborn/tests/test_decorators.py b/testbed/mwaskom__seaborn/tests/test_decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..a119afeedda1bf079d6b1638b6fbdfe78acc09a5
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_decorators.py
@@ -0,0 +1,25 @@
+import inspect
+from seaborn._decorators import share_init_params_with_map
+
+
+def test_share_init_params_with_map():
+
+    @share_init_params_with_map
+    class Thingie:
+
+        def map(cls, *args, **kwargs):
+            return cls(*args, **kwargs)
+
+        def __init__(self, a, b=1):
+            """Make a new thingie."""
+            self.a = a
+            self.b = b
+
+    thingie = Thingie.map(1, b=2)
+    assert thingie.a == 1
+    assert thingie.b == 2
+
+    assert "a" in inspect.signature(Thingie.map).parameters
+    assert "b" in inspect.signature(Thingie.map).parameters
+
+    assert Thingie.map.__doc__ == Thingie.__init__.__doc__
diff --git a/testbed/mwaskom__seaborn/tests/test_distributions.py b/testbed/mwaskom__seaborn/tests/test_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e5f16a2c8b2257c2ba64434bc2575a709b27bc4
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_distributions.py
@@ -0,0 +1,2467 @@
+import itertools
+import warnings
+
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from matplotlib.colors import to_rgb, to_rgba
+
+import pytest
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn import distributions as dist
+from seaborn.palettes import (
+    color_palette,
+    light_palette,
+)
+from seaborn._oldcore import (
+    categorical_order,
+)
+from seaborn._statistics import (
+    KDE,
+    Histogram,
+    _no_scipy,
+)
+from seaborn.distributions import (
+    _DistributionPlotter,
+    displot,
+    distplot,
+    histplot,
+    ecdfplot,
+    kdeplot,
+    rugplot,
+)
+from seaborn.utils import _version_predates
+from seaborn.axisgrid import FacetGrid
+from seaborn._testing import (
+    assert_plots_equal,
+    assert_legends_equal,
+    assert_colors_equal,
+)
+
+
+def get_contour_coords(c):
+    """Provide compatability for change in contour artist type in mpl3.5."""
+    # See https://github.com/matplotlib/matplotlib/issues/20906
+    if isinstance(c, mpl.collections.LineCollection):
+        return c.get_segments()
+    elif isinstance(c, mpl.collections.PathCollection):
+        return [p.vertices[:np.argmax(p.codes) + 1] for p in c.get_paths()]
+
+
+def get_contour_color(c):
+    """Provide compatability for change in contour artist type in mpl3.5."""
+    # See https://github.com/matplotlib/matplotlib/issues/20906
+    if isinstance(c, mpl.collections.LineCollection):
+        return c.get_color()
+    elif isinstance(c, mpl.collections.PathCollection):
+        if c.get_facecolor().size:
+            return c.get_facecolor()
+        else:
+            return c.get_edgecolor()
+
+
+class TestDistPlot:
+
+    rs = np.random.RandomState(0)
+    x = rs.randn(100)
+
+    def test_hist_bins(self):
+
+        fd_edges = np.histogram_bin_edges(self.x, "fd")
+        with pytest.warns(UserWarning):
+            ax = distplot(self.x)
+        for edge, bar in zip(fd_edges, ax.patches):
+            assert pytest.approx(edge) == bar.get_x()
+
+        plt.close(ax.figure)
+        n = 25
+        n_edges = np.histogram_bin_edges(self.x, n)
+        with pytest.warns(UserWarning):
+            ax = distplot(self.x, bins=n)
+        for edge, bar in zip(n_edges, ax.patches):
+            assert pytest.approx(edge) == bar.get_x()
+
+    def test_elements(self):
+
+        with pytest.warns(UserWarning):
+
+            n = 10
+            ax = distplot(self.x, bins=n,
+                          hist=True, kde=False, rug=False, fit=None)
+            assert len(ax.patches) == 10
+            assert len(ax.lines) == 0
+            assert len(ax.collections) == 0
+
+            plt.close(ax.figure)
+            ax = distplot(self.x,
+                          hist=False, kde=True, rug=False, fit=None)
+            assert len(ax.patches) == 0
+            assert len(ax.lines) == 1
+            assert len(ax.collections) == 0
+
+            plt.close(ax.figure)
+            ax = distplot(self.x,
+                          hist=False, kde=False, rug=True, fit=None)
+            assert len(ax.patches) == 0
+            assert len(ax.lines) == 0
+            assert len(ax.collections) == 1
+
+            class Norm:
+                """Dummy object that looks like a scipy RV"""
+                def fit(self, x):
+                    return ()
+
+                def pdf(self, x, *params):
+                    return np.zeros_like(x)
+
+            plt.close(ax.figure)
+            ax = distplot(
+                self.x, hist=False, kde=False, rug=False, fit=Norm())
+            assert len(ax.patches) == 0
+            assert len(ax.lines) == 1
+            assert len(ax.collections) == 0
+
+    def test_distplot_with_nans(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        x_null = np.append(self.x, [np.nan])
+
+        with pytest.warns(UserWarning):
+            distplot(self.x, ax=ax1)
+            distplot(x_null, ax=ax2)
+
+        line1 = ax1.lines[0]
+        line2 = ax2.lines[0]
+        assert np.array_equal(line1.get_xydata(), line2.get_xydata())
+
+        for bar1, bar2 in zip(ax1.patches, ax2.patches):
+            assert bar1.get_xy() == bar2.get_xy()
+            assert bar1.get_height() == bar2.get_height()
+
+
+class SharedAxesLevelTests:
+
+    def test_color(self, long_df, **kwargs):
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="y", ax=ax, **kwargs)
+        assert_colors_equal(self.get_last_color(ax, **kwargs), "C0", check_alpha=False)
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="y", ax=ax, **kwargs)
+        self.func(data=long_df, x="y", ax=ax, **kwargs)
+        assert_colors_equal(self.get_last_color(ax, **kwargs), "C1", check_alpha=False)
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="y", color="C2", ax=ax, **kwargs)
+        assert_colors_equal(self.get_last_color(ax, **kwargs), "C2", check_alpha=False)
+
+
+class TestRugPlot(SharedAxesLevelTests):
+
+    func = staticmethod(rugplot)
+
+    def get_last_color(self, ax, **kwargs):
+
+        return ax.collections[-1].get_color()
+
+    def assert_rug_equal(self, a, b):
+
+        assert_array_equal(a.get_segments(), b.get_segments())
+
+    @pytest.mark.parametrize("variable", ["x", "y"])
+    def test_long_data(self, long_df, variable):
+
+        vector = long_df[variable]
+        vectors = [
+            variable, vector, np.asarray(vector), vector.to_list(),
+        ]
+
+        f, ax = plt.subplots()
+        for vector in vectors:
+            rugplot(data=long_df, **{variable: vector})
+
+        for a, b in itertools.product(ax.collections, ax.collections):
+            self.assert_rug_equal(a, b)
+
+    def test_bivariate_data(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        rugplot(data=long_df, x="x", y="y", ax=ax1)
+        rugplot(data=long_df, x="x", ax=ax2)
+        rugplot(data=long_df, y="y", ax=ax2)
+
+        self.assert_rug_equal(ax1.collections[0], ax2.collections[0])
+        self.assert_rug_equal(ax1.collections[1], ax2.collections[1])
+
+    def test_wide_vs_long_data(self, wide_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        rugplot(data=wide_df, ax=ax1)
+        for col in wide_df:
+            rugplot(data=wide_df, x=col, ax=ax2)
+
+        wide_segments = np.sort(
+            np.array(ax1.collections[0].get_segments())
+        )
+        long_segments = np.sort(
+            np.concatenate([c.get_segments() for c in ax2.collections])
+        )
+
+        assert_array_equal(wide_segments, long_segments)
+
+    def test_flat_vector(self, long_df):
+
+        f, ax = plt.subplots()
+        rugplot(data=long_df["x"])
+        rugplot(x=long_df["x"])
+        self.assert_rug_equal(*ax.collections)
+
+    def test_datetime_data(self, long_df):
+
+        ax = rugplot(data=long_df["t"])
+        vals = np.stack(ax.collections[0].get_segments())[:, 0, 0]
+        assert_array_equal(vals, mpl.dates.date2num(long_df["t"]))
+
+    def test_empty_data(self):
+
+        ax = rugplot(x=[])
+        assert not ax.collections
+
+    def test_a_deprecation(self, flat_series):
+
+        f, ax = plt.subplots()
+
+        with pytest.warns(UserWarning):
+            rugplot(a=flat_series)
+        rugplot(x=flat_series)
+
+        self.assert_rug_equal(*ax.collections)
+
+    @pytest.mark.parametrize("variable", ["x", "y"])
+    def test_axis_deprecation(self, flat_series, variable):
+
+        f, ax = plt.subplots()
+
+        with pytest.warns(UserWarning):
+            rugplot(flat_series, axis=variable)
+        rugplot(**{variable: flat_series})
+
+        self.assert_rug_equal(*ax.collections)
+
+    def test_vertical_deprecation(self, flat_series):
+
+        f, ax = plt.subplots()
+
+        with pytest.warns(UserWarning):
+            rugplot(flat_series, vertical=True)
+        rugplot(y=flat_series)
+
+        self.assert_rug_equal(*ax.collections)
+
+    def test_rug_data(self, flat_array):
+
+        height = .05
+        ax = rugplot(x=flat_array, height=height)
+        segments = np.stack(ax.collections[0].get_segments())
+
+        n = flat_array.size
+        assert_array_equal(segments[:, 0, 1], np.zeros(n))
+        assert_array_equal(segments[:, 1, 1], np.full(n, height))
+        assert_array_equal(segments[:, 1, 0], flat_array)
+
+    def test_rug_colors(self, long_df):
+
+        ax = rugplot(data=long_df, x="x", hue="a")
+
+        order = categorical_order(long_df["a"])
+        palette = color_palette()
+
+        expected_colors = np.ones((len(long_df), 4))
+        for i, val in enumerate(long_df["a"]):
+            expected_colors[i, :3] = palette[order.index(val)]
+
+        assert_array_equal(ax.collections[0].get_color(), expected_colors)
+
+    def test_expand_margins(self, flat_array):
+
+        f, ax = plt.subplots()
+        x1, y1 = ax.margins()
+        rugplot(x=flat_array, expand_margins=False)
+        x2, y2 = ax.margins()
+        assert x1 == x2
+        assert y1 == y2
+
+        f, ax = plt.subplots()
+        x1, y1 = ax.margins()
+        height = .05
+        rugplot(x=flat_array, height=height)
+        x2, y2 = ax.margins()
+        assert x1 == x2
+        assert y1 + height * 2 == pytest.approx(y2)
+
+    def test_multiple_rugs(self):
+
+        values = np.linspace(start=0, stop=1, num=5)
+        ax = rugplot(x=values)
+        ylim = ax.get_ylim()
+
+        rugplot(x=values, ax=ax, expand_margins=False)
+
+        assert ylim == ax.get_ylim()
+
+    def test_matplotlib_kwargs(self, flat_series):
+
+        lw = 2
+        alpha = .2
+        ax = rugplot(y=flat_series, linewidth=lw, alpha=alpha)
+        rug = ax.collections[0]
+        assert np.all(rug.get_alpha() == alpha)
+        assert np.all(rug.get_linewidth() == lw)
+
+    def test_axis_labels(self, flat_series):
+
+        ax = rugplot(x=flat_series)
+        assert ax.get_xlabel() == flat_series.name
+        assert not ax.get_ylabel()
+
+    def test_log_scale(self, long_df):
+
+        ax1, ax2 = plt.figure().subplots(2)
+
+        ax2.set_xscale("log")
+
+        rugplot(data=long_df, x="z", ax=ax1)
+        rugplot(data=long_df, x="z", ax=ax2)
+
+        rug1 = np.stack(ax1.collections[0].get_segments())
+        rug2 = np.stack(ax2.collections[0].get_segments())
+
+        assert_array_almost_equal(rug1, rug2)
+
+
+class TestKDEPlotUnivariate(SharedAxesLevelTests):
+
+    func = staticmethod(kdeplot)
+
+    def get_last_color(self, ax, fill=True):
+
+        if fill:
+            return ax.collections[-1].get_facecolor()
+        else:
+            return ax.lines[-1].get_color()
+
+    @pytest.mark.parametrize("fill", [True, False])
+    def test_color(self, long_df, fill):
+
+        super().test_color(long_df, fill=fill)
+
+        if fill:
+
+            ax = plt.figure().subplots()
+            self.func(data=long_df, x="y", facecolor="C3", fill=True, ax=ax)
+            assert_colors_equal(self.get_last_color(ax), "C3", check_alpha=False)
+
+            ax = plt.figure().subplots()
+            self.func(data=long_df, x="y", fc="C4", fill=True, ax=ax)
+            assert_colors_equal(self.get_last_color(ax), "C4", check_alpha=False)
+
+    @pytest.mark.parametrize(
+        "variable", ["x", "y"],
+    )
+    def test_long_vectors(self, long_df, variable):
+
+        vector = long_df[variable]
+        vectors = [
+            variable, vector, vector.to_numpy(), vector.to_list(),
+        ]
+
+        f, ax = plt.subplots()
+        for vector in vectors:
+            kdeplot(data=long_df, **{variable: vector})
+
+        xdata = [l.get_xdata() for l in ax.lines]
+        for a, b in itertools.product(xdata, xdata):
+            assert_array_equal(a, b)
+
+        ydata = [l.get_ydata() for l in ax.lines]
+        for a, b in itertools.product(ydata, ydata):
+            assert_array_equal(a, b)
+
+    def test_wide_vs_long_data(self, wide_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        kdeplot(data=wide_df, ax=ax1, common_norm=False, common_grid=False)
+        for col in wide_df:
+            kdeplot(data=wide_df, x=col, ax=ax2)
+
+        for l1, l2 in zip(ax1.lines[::-1], ax2.lines):
+            assert_array_equal(l1.get_xydata(), l2.get_xydata())
+
+    def test_flat_vector(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df["x"])
+        kdeplot(x=long_df["x"])
+        assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())
+
+    def test_empty_data(self):
+
+        ax = kdeplot(x=[])
+        assert not ax.lines
+
+    def test_singular_data(self):
+
+        with pytest.warns(UserWarning):
+            ax = kdeplot(x=np.ones(10))
+        assert not ax.lines
+
+        with pytest.warns(UserWarning):
+            ax = kdeplot(x=[5])
+        assert not ax.lines
+
+        with pytest.warns(UserWarning):
+            # https://github.com/mwaskom/seaborn/issues/2762
+            ax = kdeplot(x=[1929245168.06679] * 18)
+        assert not ax.lines
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", UserWarning)
+            ax = kdeplot(x=[5], warn_singular=False)
+        assert not ax.lines
+
+    def test_variable_assignment(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, x="x", fill=True)
+        kdeplot(data=long_df, y="x", fill=True)
+
+        v0 = ax.collections[0].get_paths()[0].vertices
+        v1 = ax.collections[1].get_paths()[0].vertices[:, [1, 0]]
+
+        assert_array_equal(v0, v1)
+
+    def test_vertical_deprecation(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, y="x")
+
+        with pytest.warns(UserWarning):
+            kdeplot(data=long_df, x="x", vertical=True)
+
+        assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())
+
+    def test_bw_deprecation(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, x="x", bw_method="silverman")
+
+        with pytest.warns(UserWarning):
+            kdeplot(data=long_df, x="x", bw="silverman")
+
+        assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())
+
+    def test_kernel_deprecation(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, x="x")
+
+        with pytest.warns(UserWarning):
+            kdeplot(data=long_df, x="x", kernel="epi")
+
+        assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())
+
+    def test_shade_deprecation(self, long_df):
+
+        f, ax = plt.subplots()
+        with pytest.warns(FutureWarning):
+            kdeplot(data=long_df, x="x", shade=True)
+        kdeplot(data=long_df, x="x", fill=True)
+        fill1, fill2 = ax.collections
+        assert_array_equal(
+            fill1.get_paths()[0].vertices, fill2.get_paths()[0].vertices
+        )
+
+    @pytest.mark.parametrize("multiple", ["layer", "stack", "fill"])
+    def test_hue_colors(self, long_df, multiple):
+
+        ax = kdeplot(
+            data=long_df, x="x", hue="a",
+            multiple=multiple,
+            fill=True, legend=False
+        )
+
+        # Note that hue order is reversed in the plot
+        lines = ax.lines[::-1]
+        fills = ax.collections[::-1]
+
+        palette = color_palette()
+
+        for line, fill, color in zip(lines, fills, palette):
+            assert_colors_equal(line.get_color(), color)
+            assert_colors_equal(fill.get_facecolor(), to_rgba(color, .25))
+
+    def test_hue_stacking(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(
+            data=long_df, x="x", hue="a",
+            multiple="layer", common_grid=True,
+            legend=False, ax=ax1,
+        )
+        kdeplot(
+            data=long_df, x="x", hue="a",
+            multiple="stack", fill=False,
+            legend=False, ax=ax2,
+        )
+
+        layered_densities = np.stack([
+            l.get_ydata() for l in ax1.lines
+        ])
+        stacked_densities = np.stack([
+            l.get_ydata() for l in ax2.lines
+        ])
+
+        assert_array_equal(layered_densities.cumsum(axis=0), stacked_densities)
+
+    def test_hue_filling(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(
+            data=long_df, x="x", hue="a",
+            multiple="layer", common_grid=True,
+            legend=False, ax=ax1,
+        )
+        kdeplot(
+            data=long_df, x="x", hue="a",
+            multiple="fill", fill=False,
+            legend=False, ax=ax2,
+        )
+
+        layered = np.stack([l.get_ydata() for l in ax1.lines])
+        filled = np.stack([l.get_ydata() for l in ax2.lines])
+
+        assert_array_almost_equal(
+            (layered / layered.sum(axis=0)).cumsum(axis=0),
+            filled,
+        )
+
+    @pytest.mark.parametrize("multiple", ["stack", "fill"])
+    def test_fill_default(self, long_df, multiple):
+
+        ax = kdeplot(
+            data=long_df, x="x", hue="a", multiple=multiple, fill=None
+        )
+
+        assert len(ax.collections) > 0
+
+    @pytest.mark.parametrize("multiple", ["layer", "stack", "fill"])
+    def test_fill_nondefault(self, long_df, multiple):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kws = dict(data=long_df, x="x", hue="a")
+        kdeplot(**kws, multiple=multiple, fill=False, ax=ax1)
+        kdeplot(**kws, multiple=multiple, fill=True, ax=ax2)
+
+        assert len(ax1.collections) == 0
+        assert len(ax2.collections) > 0
+
+    def test_color_cycle_interaction(self, flat_series):
+
+        color = (.2, 1, .6)
+
+        f, ax = plt.subplots()
+        kdeplot(flat_series)
+        kdeplot(flat_series)
+        assert_colors_equal(ax.lines[0].get_color(), "C0")
+        assert_colors_equal(ax.lines[1].get_color(), "C1")
+        plt.close(f)
+
+        f, ax = plt.subplots()
+        kdeplot(flat_series, color=color)
+        kdeplot(flat_series)
+        assert_colors_equal(ax.lines[0].get_color(), color)
+        assert_colors_equal(ax.lines[1].get_color(), "C0")
+        plt.close(f)
+
+        f, ax = plt.subplots()
+        kdeplot(flat_series, fill=True)
+        kdeplot(flat_series, fill=True)
+        assert_colors_equal(ax.collections[0].get_facecolor(), to_rgba("C0", .25))
+        assert_colors_equal(ax.collections[1].get_facecolor(), to_rgba("C1", .25))
+        plt.close(f)
+
+    @pytest.mark.parametrize("fill", [True, False])
+    def test_artist_color(self, long_df, fill):
+
+        color = (.2, 1, .6)
+        alpha = .5
+
+        f, ax = plt.subplots()
+
+        kdeplot(long_df["x"], fill=fill, color=color)
+        if fill:
+            artist_color = ax.collections[-1].get_facecolor().squeeze()
+        else:
+            artist_color = ax.lines[-1].get_color()
+        default_alpha = .25 if fill else 1
+        assert_colors_equal(artist_color, to_rgba(color, default_alpha))
+
+        kdeplot(long_df["x"], fill=fill, color=color, alpha=alpha)
+        if fill:
+            artist_color = ax.collections[-1].get_facecolor().squeeze()
+        else:
+            artist_color = ax.lines[-1].get_color()
+        assert_colors_equal(artist_color, to_rgba(color, alpha))
+
+    def test_datetime_scale(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        kdeplot(x=long_df["t"], fill=True, ax=ax1)
+        kdeplot(x=long_df["t"], fill=False, ax=ax2)
+        assert ax1.get_xlim() == ax2.get_xlim()
+
+    def test_multiple_argument_check(self, long_df):
+
+        with pytest.raises(ValueError, match="`multiple` must be"):
+            kdeplot(data=long_df, x="x", hue="a", multiple="bad_input")
+
+    def test_cut(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+
+        f, ax = plt.subplots()
+        kdeplot(x=x, cut=0, legend=False)
+
+        xdata_0 = ax.lines[0].get_xdata()
+        assert xdata_0.min() == x.min()
+        assert xdata_0.max() == x.max()
+
+        kdeplot(x=x, cut=2, legend=False)
+
+        xdata_2 = ax.lines[1].get_xdata()
+        assert xdata_2.min() < xdata_0.min()
+        assert xdata_2.max() > xdata_0.max()
+
+        assert len(xdata_0) == len(xdata_2)
+
+    def test_clip(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+
+        clip = -1, 1
+        ax = kdeplot(x=x, clip=clip)
+
+        xdata = ax.lines[0].get_xdata()
+
+        assert xdata.min() >= clip[0]
+        assert xdata.max() <= clip[1]
+
+    def test_line_is_density(self, long_df):
+
+        ax = kdeplot(data=long_df, x="x", cut=5)
+        x, y = ax.lines[0].get_xydata().T
+        assert integrate(y, x) == pytest.approx(1)
+
+    @pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
+    def test_cumulative(self, long_df):
+
+        ax = kdeplot(data=long_df, x="x", cut=5, cumulative=True)
+        y = ax.lines[0].get_ydata()
+        assert y[0] == pytest.approx(0)
+        assert y[-1] == pytest.approx(1)
+
+    @pytest.mark.skipif(not _no_scipy, reason="Test requires scipy's absence")
+    def test_cumulative_requires_scipy(self, long_df):
+
+        with pytest.raises(RuntimeError):
+            kdeplot(data=long_df, x="x", cut=5, cumulative=True)
+
+    def test_common_norm(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(
+            data=long_df, x="x", hue="c", common_norm=True, cut=10, ax=ax1
+        )
+        kdeplot(
+            data=long_df, x="x", hue="c", common_norm=False, cut=10, ax=ax2
+        )
+
+        total_area = 0
+        for line in ax1.lines:
+            xdata, ydata = line.get_xydata().T
+            total_area += integrate(ydata, xdata)
+        assert total_area == pytest.approx(1)
+
+        for line in ax2.lines:
+            xdata, ydata = line.get_xydata().T
+            assert integrate(ydata, xdata) == pytest.approx(1)
+
+    def test_common_grid(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        order = "a", "b", "c"
+
+        kdeplot(
+            data=long_df, x="x", hue="a", hue_order=order,
+            common_grid=False, cut=0, ax=ax1,
+        )
+        kdeplot(
+            data=long_df, x="x", hue="a", hue_order=order,
+            common_grid=True, cut=0, ax=ax2,
+        )
+
+        for line, level in zip(ax1.lines[::-1], order):
+            xdata = line.get_xdata()
+            assert xdata.min() == long_df.loc[long_df["a"] == level, "x"].min()
+            assert xdata.max() == long_df.loc[long_df["a"] == level, "x"].max()
+
+        for line in ax2.lines:
+            xdata = line.get_xdata().T
+            assert xdata.min() == long_df["x"].min()
+            assert xdata.max() == long_df["x"].max()
+
+    def test_bw_method(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, x="x", bw_method=0.2, legend=False)
+        kdeplot(data=long_df, x="x", bw_method=1.0, legend=False)
+        kdeplot(data=long_df, x="x", bw_method=3.0, legend=False)
+
+        l1, l2, l3 = ax.lines
+
+        assert (
+            np.abs(np.diff(l1.get_ydata())).mean()
+            > np.abs(np.diff(l2.get_ydata())).mean()
+        )
+
+        assert (
+            np.abs(np.diff(l2.get_ydata())).mean()
+            > np.abs(np.diff(l3.get_ydata())).mean()
+        )
+
+    def test_bw_adjust(self, long_df):
+
+        f, ax = plt.subplots()
+        kdeplot(data=long_df, x="x", bw_adjust=0.2, legend=False)
+        kdeplot(data=long_df, x="x", bw_adjust=1.0, legend=False)
+        kdeplot(data=long_df, x="x", bw_adjust=3.0, legend=False)
+
+        l1, l2, l3 = ax.lines
+
+        assert (
+            np.abs(np.diff(l1.get_ydata())).mean()
+            > np.abs(np.diff(l2.get_ydata())).mean()
+        )
+
+        assert (
+            np.abs(np.diff(l2.get_ydata())).mean()
+            > np.abs(np.diff(l3.get_ydata())).mean()
+        )
+
+    def test_log_scale_implicit(self, rng):
+
+        x = rng.lognormal(0, 1, 100)
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        ax1.set_xscale("log")
+
+        kdeplot(x=x, ax=ax1)
+        kdeplot(x=x, ax=ax1)
+
+        xdata_log = ax1.lines[0].get_xdata()
+        assert (xdata_log > 0).all()
+        assert (np.diff(xdata_log, 2) > 0).all()
+        assert np.allclose(np.diff(np.log(xdata_log), 2), 0)
+
+        f, ax = plt.subplots()
+        ax.set_yscale("log")
+        kdeplot(y=x, ax=ax)
+        assert_array_equal(ax.lines[0].get_xdata(), ax1.lines[0].get_ydata())
+
+    def test_log_scale_explicit(self, rng):
+
+        x = rng.lognormal(0, 1, 100)
+
+        f, (ax1, ax2, ax3) = plt.subplots(ncols=3)
+
+        ax1.set_xscale("log")
+        kdeplot(x=x, ax=ax1)
+        kdeplot(x=x, log_scale=True, ax=ax2)
+        kdeplot(x=x, log_scale=10, ax=ax3)
+
+        for ax in f.axes:
+            assert ax.get_xscale() == "log"
+
+        supports = [ax.lines[0].get_xdata() for ax in f.axes]
+        for a, b in itertools.product(supports, supports):
+            assert_array_equal(a, b)
+
+        densities = [ax.lines[0].get_ydata() for ax in f.axes]
+        for a, b in itertools.product(densities, densities):
+            assert_array_equal(a, b)
+
+        f, ax = plt.subplots()
+        kdeplot(y=x, log_scale=True, ax=ax)
+        assert ax.get_yscale() == "log"
+
+    def test_log_scale_with_hue(self, rng):
+
+        data = rng.lognormal(0, 1, 50), rng.lognormal(0, 2, 100)
+        ax = kdeplot(data=data, log_scale=True, common_grid=True)
+        assert_array_equal(ax.lines[0].get_xdata(), ax.lines[1].get_xdata())
+
+    def test_log_scale_normalization(self, rng):
+
+        x = rng.lognormal(0, 1, 100)
+        ax = kdeplot(x=x, log_scale=True, cut=10)
+        xdata, ydata = ax.lines[0].get_xydata().T
+        integral = integrate(ydata, np.log10(xdata))
+        assert integral == pytest.approx(1)
+
+    def test_weights(self):
+
+        x = [1, 2]
+        weights = [2, 1]
+
+        ax = kdeplot(x=x, weights=weights, bw_method=.1)
+
+        xdata, ydata = ax.lines[0].get_xydata().T
+
+        y1 = ydata[np.abs(xdata - 1).argmin()]
+        y2 = ydata[np.abs(xdata - 2).argmin()]
+
+        assert y1 == pytest.approx(2 * y2)
+
+    def test_weight_norm(self, rng):
+
+        vals = rng.normal(0, 1, 50)
+        x = np.concatenate([vals, vals])
+        w = np.repeat([1, 2], 50)
+        ax = kdeplot(x=x, weights=w, hue=w, common_norm=True)
+
+        # Recall that artists are added in reverse of hue order
+        x1, y1 = ax.lines[0].get_xydata().T
+        x2, y2 = ax.lines[1].get_xydata().T
+
+        assert integrate(y1, x1) == pytest.approx(2 * integrate(y2, x2))
+
+    def test_sticky_edges(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(data=long_df, x="x", fill=True, ax=ax1)
+        assert ax1.collections[0].sticky_edges.y[:] == [0, np.inf]
+
+        kdeplot(
+            data=long_df, x="x", hue="a", multiple="fill", fill=True, ax=ax2
+        )
+        assert ax2.collections[0].sticky_edges.y[:] == [0, 1]
+
+    def test_line_kws(self, flat_array):
+
+        lw = 3
+        color = (.2, .5, .8)
+        ax = kdeplot(x=flat_array, linewidth=lw, color=color)
+        line, = ax.lines
+        assert line.get_linewidth() == lw
+        assert_colors_equal(line.get_color(), color)
+
+    def test_input_checking(self, long_df):
+
+        err = "The x variable is categorical,"
+        with pytest.raises(TypeError, match=err):
+            kdeplot(data=long_df, x="a")
+
+    def test_axis_labels(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(data=long_df, x="x", ax=ax1)
+        assert ax1.get_xlabel() == "x"
+        assert ax1.get_ylabel() == "Density"
+
+        kdeplot(data=long_df, y="y", ax=ax2)
+        assert ax2.get_xlabel() == "Density"
+        assert ax2.get_ylabel() == "y"
+
+    def test_legend(self, long_df):
+
+        ax = kdeplot(data=long_df, x="x", hue="a")
+
+        assert ax.legend_.get_title().get_text() == "a"
+
+        legend_labels = ax.legend_.get_texts()
+        order = categorical_order(long_df["a"])
+        for label, level in zip(legend_labels, order):
+            assert label.get_text() == level
+
+        legend_artists = ax.legend_.findobj(mpl.lines.Line2D)
+        if _version_predates(mpl, "3.5.0b0"):
+            # https://github.com/matplotlib/matplotlib/pull/20699
+            legend_artists = legend_artists[::2]
+        palette = color_palette()
+        for artist, color in zip(legend_artists, palette):
+            assert_colors_equal(artist.get_color(), color)
+
+        ax.clear()
+
+        kdeplot(data=long_df, x="x", hue="a", legend=False)
+
+        assert ax.legend_ is None
+
+
+class TestKDEPlotBivariate:
+
+    def test_long_vectors(self, long_df):
+
+        ax1 = kdeplot(data=long_df, x="x", y="y")
+
+        x = long_df["x"]
+        x_values = [x, x.to_numpy(), x.to_list()]
+
+        y = long_df["y"]
+        y_values = [y, y.to_numpy(), y.to_list()]
+
+        for x, y in zip(x_values, y_values):
+            f, ax2 = plt.subplots()
+            kdeplot(x=x, y=y, ax=ax2)
+
+            for c1, c2 in zip(ax1.collections, ax2.collections):
+                assert_array_equal(c1.get_offsets(), c2.get_offsets())
+
+    def test_singular_data(self):
+
+        with pytest.warns(UserWarning):
+            ax = dist.kdeplot(x=np.ones(10), y=np.arange(10))
+        assert not ax.lines
+
+        with pytest.warns(UserWarning):
+            ax = dist.kdeplot(x=[5], y=[6])
+        assert not ax.lines
+
+        with pytest.warns(UserWarning):
+            ax = kdeplot(x=[1929245168.06679] * 18, y=np.arange(18))
+        assert not ax.lines
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", UserWarning)
+            ax = kdeplot(x=[5], y=[7], warn_singular=False)
+        assert not ax.lines
+
+    def test_fill_artists(self, long_df):
+
+        for fill in [True, False]:
+            f, ax = plt.subplots()
+            kdeplot(data=long_df, x="x", y="y", hue="c", fill=fill)
+            for c in ax.collections:
+                if fill or not _version_predates(mpl, "3.5.0b0"):
+                    assert isinstance(c, mpl.collections.PathCollection)
+                else:
+                    assert isinstance(c, mpl.collections.LineCollection)
+
+    def test_common_norm(self, rng):
+
+        hue = np.repeat(["a", "a", "a", "b"], 40)
+        x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], len(hue)).T
+        x[hue == "a"] -= 2
+        x[hue == "b"] += 2
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        kdeplot(x=x, y=y, hue=hue, common_norm=True, ax=ax1)
+        kdeplot(x=x, y=y, hue=hue, common_norm=False, ax=ax2)
+
+        n_seg_1 = sum(len(get_contour_coords(c)) > 0 for c in ax1.collections)
+        n_seg_2 = sum(len(get_contour_coords(c)) > 0 for c in ax2.collections)
+        assert n_seg_2 > n_seg_1
+
+    def test_log_scale(self, rng):
+
+        x = rng.lognormal(0, 1, 100)
+        y = rng.uniform(0, 1, 100)
+
+        levels = .2, .5, 1
+
+        f, ax = plt.subplots()
+        kdeplot(x=x, y=y, log_scale=True, levels=levels, ax=ax)
+        assert ax.get_xscale() == "log"
+        assert ax.get_yscale() == "log"
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        kdeplot(x=x, y=y, log_scale=(10, False), levels=levels, ax=ax1)
+        assert ax1.get_xscale() == "log"
+        assert ax1.get_yscale() == "linear"
+
+        p = _DistributionPlotter()
+        kde = KDE()
+        density, (xx, yy) = kde(np.log10(x), y)
+        levels = p._quantile_to_level(density, levels)
+        ax2.contour(10 ** xx, yy, density, levels=levels)
+
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))
+
+    def test_bandwidth(self, rng):
+
+        n = 100
+        x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], n).T
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        kdeplot(x=x, y=y, ax=ax1)
+        kdeplot(x=x, y=y, bw_adjust=2, ax=ax2)
+
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            seg1, seg2 = get_contour_coords(c1), get_contour_coords(c2)
+            if seg1 + seg2:
+                x1 = seg1[0][:, 0]
+                x2 = seg2[0][:, 0]
+                assert np.abs(x2).max() > np.abs(x1).max()
+
+    def test_weights(self, rng):
+
+        import warnings
+        warnings.simplefilter("error", np.VisibleDeprecationWarning)
+
+        n = 100
+        x, y = rng.multivariate_normal([1, 3], [(.2, .5), (.5, 2)], n).T
+        hue = np.repeat([0, 1], n // 2)
+        weights = rng.uniform(0, 1, n)
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+        kdeplot(x=x, y=y, hue=hue, ax=ax1)
+        kdeplot(x=x, y=y, hue=hue, weights=weights, ax=ax2)
+
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            if get_contour_coords(c1) and get_contour_coords(c2):
+                seg1 = np.concatenate(get_contour_coords(c1), axis=0)
+                seg2 = np.concatenate(get_contour_coords(c2), axis=0)
+                assert not np.array_equal(seg1, seg2)
+
+    def test_hue_ignores_cmap(self, long_df):
+
+        with pytest.warns(UserWarning, match="cmap parameter ignored"):
+            ax = kdeplot(data=long_df, x="x", y="y", hue="c", cmap="viridis")
+
+        assert_colors_equal(get_contour_color(ax.collections[0]), "C0")
+
+    def test_contour_line_colors(self, long_df):
+
+        color = (.2, .9, .8, 1)
+        ax = kdeplot(data=long_df, x="x", y="y", color=color)
+
+        for c in ax.collections:
+            assert_colors_equal(get_contour_color(c), color)
+
+    def test_contour_line_cmap(self, long_df):
+
+        color_list = color_palette("Blues", 12)
+        cmap = mpl.colors.ListedColormap(color_list)
+        ax = kdeplot(data=long_df, x="x", y="y", cmap=cmap)
+        for c in ax.collections:
+            color = to_rgb(get_contour_color(c).squeeze())
+            assert color in color_list
+
+    def test_contour_fill_colors(self, long_df):
+
+        n = 6
+        color = (.2, .9, .8, 1)
+        ax = kdeplot(
+            data=long_df, x="x", y="y", fill=True, color=color, levels=n,
+        )
+
+        cmap = light_palette(color, reverse=True, as_cmap=True)
+        lut = cmap(np.linspace(0, 1, 256))
+        for c in ax.collections:
+            color = c.get_facecolor().squeeze()
+            assert color in lut
+
+    def test_colorbar(self, long_df):
+
+        ax = kdeplot(data=long_df, x="x", y="y", fill=True, cbar=True)
+        assert len(ax.figure.axes) == 2
+
+    def test_levels_and_thresh(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(ncols=2)
+
+        n = 8
+        thresh = .1
+        plot_kws = dict(data=long_df, x="x", y="y")
+        kdeplot(**plot_kws, levels=n, thresh=thresh, ax=ax1)
+        kdeplot(**plot_kws, levels=np.linspace(thresh, 1, n), ax=ax2)
+
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))
+
+        with pytest.raises(ValueError):
+            kdeplot(**plot_kws, levels=[0, 1, 2])
+
+        ax1.clear()
+        ax2.clear()
+
+        kdeplot(**plot_kws, levels=n, thresh=None, ax=ax1)
+        kdeplot(**plot_kws, levels=n, thresh=0, ax=ax2)
+
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))
+        for c1, c2 in zip(ax1.collections, ax2.collections):
+            assert_array_equal(c1.get_facecolors(), c2.get_facecolors())
+
+    def test_quantile_to_level(self, rng):
+
+        x = rng.uniform(0, 1, 100000)
+        isoprop = np.linspace(.1, 1, 6)
+
+        levels = _DistributionPlotter()._quantile_to_level(x, isoprop)
+        for h, p in zip(levels, isoprop):
+            assert (x[x <= h].sum() / x.sum()) == pytest.approx(p, abs=1e-4)
+
+    def test_input_checking(self, long_df):
+
+        with pytest.raises(TypeError, match="The x variable is categorical,"):
+            kdeplot(data=long_df, x="a", y="y")
+
+
+class TestHistPlotUnivariate(SharedAxesLevelTests):
+
+    func = staticmethod(histplot)
+
+    def get_last_color(self, ax, element="bars", fill=True):
+
+        if element == "bars":
+            if fill:
+                return ax.patches[-1].get_facecolor()
+            else:
+                return ax.patches[-1].get_edgecolor()
+        else:
+            if fill:
+                artist = ax.collections[-1]
+                facecolor = artist.get_facecolor()
+                edgecolor = artist.get_edgecolor()
+                assert_colors_equal(facecolor, edgecolor, check_alpha=False)
+                return facecolor
+            else:
+                return ax.lines[-1].get_color()
+
+    @pytest.mark.parametrize(
+        "element,fill",
+        itertools.product(["bars", "step", "poly"], [True, False]),
+    )
+    def test_color(self, long_df, element, fill):
+
+        super().test_color(long_df, element=element, fill=fill)
+
+    @pytest.mark.parametrize(
+        "variable", ["x", "y"],
+    )
+    def test_long_vectors(self, long_df, variable):
+
+        vector = long_df[variable]
+        vectors = [
+            variable, vector, vector.to_numpy(), vector.to_list(),
+        ]
+
+        f, axs = plt.subplots(3)
+        for vector, ax in zip(vectors, axs):
+            histplot(data=long_df, ax=ax, **{variable: vector})
+
+        bars = [ax.patches for ax in axs]
+        for a_bars, b_bars in itertools.product(bars, bars):
+            for a, b in zip(a_bars, b_bars):
+                assert_array_equal(a.get_height(), b.get_height())
+                assert_array_equal(a.get_xy(), b.get_xy())
+
+    def test_wide_vs_long_data(self, wide_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        histplot(data=wide_df, ax=ax1, common_bins=False)
+
+        for col in wide_df.columns[::-1]:
+            histplot(data=wide_df, x=col, ax=ax2)
+
+        for a, b in zip(ax1.patches, ax2.patches):
+            assert a.get_height() == b.get_height()
+            assert a.get_xy() == b.get_xy()
+
+    def test_flat_vector(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        histplot(data=long_df["x"], ax=ax1)
+        histplot(data=long_df, x="x", ax=ax2)
+
+        for a, b in zip(ax1.patches, ax2.patches):
+            assert a.get_height() == b.get_height()
+            assert a.get_xy() == b.get_xy()
+
+    def test_empty_data(self):
+
+        ax = histplot(x=[])
+        assert not ax.patches
+
+    def test_variable_assignment(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        histplot(data=long_df, x="x", ax=ax1)
+        histplot(data=long_df, y="x", ax=ax2)
+
+        for a, b in zip(ax1.patches, ax2.patches):
+            assert a.get_height() == b.get_width()
+
+    @pytest.mark.parametrize("element", ["bars", "step", "poly"])
+    @pytest.mark.parametrize("multiple", ["layer", "dodge", "stack", "fill"])
+    def test_hue_fill_colors(self, long_df, multiple, element):
+
+        ax = histplot(
+            data=long_df, x="x", hue="a",
+            multiple=multiple, bins=1,
+            fill=True, element=element, legend=False,
+        )
+
+        palette = color_palette()
+
+        if multiple == "layer":
+            if element == "bars":
+                a = .5
+            else:
+                a = .25
+        else:
+            a = .75
+
+        for bar, color in zip(ax.patches[::-1], palette):
+            assert_colors_equal(bar.get_facecolor(), to_rgba(color, a))
+
+        for poly, color in zip(ax.collections[::-1], palette):
+            assert_colors_equal(poly.get_facecolor(), to_rgba(color, a))
+
+    def test_hue_stack(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        n = 10
+
+        kws = dict(data=long_df, x="x", hue="a", bins=n, element="bars")
+
+        histplot(**kws, multiple="layer", ax=ax1)
+        histplot(**kws, multiple="stack", ax=ax2)
+
+        layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))
+        stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))
+        assert_array_equal(layer_heights, stack_heights)
+
+        stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))
+        assert_array_equal(
+            stack_xys[..., 1] + stack_heights,
+            stack_heights.cumsum(axis=0),
+        )
+
+    def test_hue_fill(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        n = 10
+
+        kws = dict(data=long_df, x="x", hue="a", bins=n, element="bars")
+
+        histplot(**kws, multiple="layer", ax=ax1)
+        histplot(**kws, multiple="fill", ax=ax2)
+
+        layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))
+        stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))
+        assert_array_almost_equal(
+            layer_heights / layer_heights.sum(axis=0), stack_heights
+        )
+
+        stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))
+        assert_array_almost_equal(
+            (stack_xys[..., 1] + stack_heights) / stack_heights.sum(axis=0),
+            stack_heights.cumsum(axis=0),
+        )
+
+    def test_hue_dodge(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        bw = 2
+
+        kws = dict(data=long_df, x="x", hue="c", binwidth=bw, element="bars")
+
+        histplot(**kws, multiple="layer", ax=ax1)
+        histplot(**kws, multiple="dodge", ax=ax2)
+
+        layer_heights = [b.get_height() for b in ax1.patches]
+        dodge_heights = [b.get_height() for b in ax2.patches]
+        assert_array_equal(layer_heights, dodge_heights)
+
+        layer_xs = np.reshape([b.get_x() for b in ax1.patches], (2, -1))
+        dodge_xs = np.reshape([b.get_x() for b in ax2.patches], (2, -1))
+        assert_array_almost_equal(layer_xs[1], dodge_xs[1])
+        assert_array_almost_equal(layer_xs[0], dodge_xs[0] - bw / 2)
+
+    def test_hue_as_numpy_dodged(self, long_df):
+        # https://github.com/mwaskom/seaborn/issues/2452
+
+        ax = histplot(
+            long_df,
+            x="y", hue=long_df["a"].to_numpy(),
+            multiple="dodge", bins=1,
+        )
+        # Note hue order reversal
+        assert ax.patches[1].get_x() < ax.patches[0].get_x()
+
+    def test_multiple_input_check(self, flat_series):
+
+        with pytest.raises(ValueError, match="`multiple` must be"):
+            histplot(flat_series, multiple="invalid")
+
+    def test_element_input_check(self, flat_series):
+
+        with pytest.raises(ValueError, match="`element` must be"):
+            histplot(flat_series, element="invalid")
+
+    def test_count_stat(self, flat_series):
+
+        ax = histplot(flat_series, stat="count")
+        bar_heights = [b.get_height() for b in ax.patches]
+        assert sum(bar_heights) == len(flat_series)
+
+    def test_density_stat(self, flat_series):
+
+        ax = histplot(flat_series, stat="density")
+        bar_heights = [b.get_height() for b in ax.patches]
+        bar_widths = [b.get_width() for b in ax.patches]
+        assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)
+
+    def test_density_stat_common_norm(self, long_df):
+
+        ax = histplot(
+            data=long_df, x="x", hue="a",
+            stat="density", common_norm=True, element="bars",
+        )
+        bar_heights = [b.get_height() for b in ax.patches]
+        bar_widths = [b.get_width() for b in ax.patches]
+        assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)
+
+    def test_density_stat_unique_norm(self, long_df):
+
+        n = 10
+        ax = histplot(
+            data=long_df, x="x", hue="a",
+            stat="density", bins=n, common_norm=False, element="bars",
+        )
+
+        bar_groups = ax.patches[:n], ax.patches[-n:]
+
+        for bars in bar_groups:
+            bar_heights = [b.get_height() for b in bars]
+            bar_widths = [b.get_width() for b in bars]
+            bar_areas = np.multiply(bar_heights, bar_widths)
+            assert bar_areas.sum() == pytest.approx(1)
+
+    @pytest.fixture(params=["probability", "proportion"])
+    def height_norm_arg(self, request):
+        return request.param
+
+    def test_probability_stat(self, flat_series, height_norm_arg):
+
+        ax = histplot(flat_series, stat=height_norm_arg)
+        bar_heights = [b.get_height() for b in ax.patches]
+        assert sum(bar_heights) == pytest.approx(1)
+
+    def test_probability_stat_common_norm(self, long_df, height_norm_arg):
+
+        ax = histplot(
+            data=long_df, x="x", hue="a",
+            stat=height_norm_arg, common_norm=True, element="bars",
+        )
+        bar_heights = [b.get_height() for b in ax.patches]
+        assert sum(bar_heights) == pytest.approx(1)
+
+    def test_probability_stat_unique_norm(self, long_df, height_norm_arg):
+
+        n = 10
+        ax = histplot(
+            data=long_df, x="x", hue="a",
+            stat=height_norm_arg, bins=n, common_norm=False, element="bars",
+        )
+
+        bar_groups = ax.patches[:n], ax.patches[-n:]
+
+        for bars in bar_groups:
+            bar_heights = [b.get_height() for b in bars]
+            assert sum(bar_heights) == pytest.approx(1)
+
+    def test_percent_stat(self, flat_series):
+
+        ax = histplot(flat_series, stat="percent")
+        bar_heights = [b.get_height() for b in ax.patches]
+        assert sum(bar_heights) == 100
+
+    def test_common_bins(self, long_df):
+
+        n = 10
+        ax = histplot(
+            long_df, x="x", hue="a", common_bins=True, bins=n, element="bars",
+        )
+
+        bar_groups = ax.patches[:n], ax.patches[-n:]
+        assert_array_equal(
+            [b.get_xy() for b in bar_groups[0]],
+            [b.get_xy() for b in bar_groups[1]]
+        )
+
+    def test_unique_bins(self, wide_df):
+
+        ax = histplot(wide_df, common_bins=False, bins=10, element="bars")
+
+        bar_groups = np.split(np.array(ax.patches), len(wide_df.columns))
+
+        for i, col in enumerate(wide_df.columns[::-1]):
+            bars = bar_groups[i]
+            start = bars[0].get_x()
+            stop = bars[-1].get_x() + bars[-1].get_width()
+            assert_array_almost_equal(start, wide_df[col].min())
+            assert_array_almost_equal(stop, wide_df[col].max())
+
+    def test_weights_with_missing(self, missing_df):
+
+        ax = histplot(missing_df, x="x", weights="s", bins=5)
+
+        bar_heights = [bar.get_height() for bar in ax.patches]
+        total_weight = missing_df[["x", "s"]].dropna()["s"].sum()
+        assert sum(bar_heights) == pytest.approx(total_weight)
+
+    def test_weight_norm(self, rng):
+
+        vals = rng.normal(0, 1, 50)
+        x = np.concatenate([vals, vals])
+        w = np.repeat([1, 2], 50)
+        ax = histplot(
+            x=x, weights=w, hue=w, common_norm=True, stat="density", bins=5
+        )
+
+        # Recall that artists are added in reverse of hue order
+        y1 = [bar.get_height() for bar in ax.patches[:5]]
+        y2 = [bar.get_height() for bar in ax.patches[5:]]
+
+        assert sum(y1) == 2 * sum(y2)
+
+    def test_discrete(self, long_df):
+
+        ax = histplot(long_df, x="s", discrete=True)
+
+        data_min = long_df["s"].min()
+        data_max = long_df["s"].max()
+        assert len(ax.patches) == (data_max - data_min + 1)
+
+        for i, bar in enumerate(ax.patches):
+            assert bar.get_width() == 1
+            assert bar.get_x() == (data_min + i - .5)
+
+    def test_discrete_categorical_default(self, long_df):
+
+        ax = histplot(long_df, x="a")
+        for i, bar in enumerate(ax.patches):
+            assert bar.get_width() == 1
+
+    def test_categorical_yaxis_inversion(self, long_df):
+
+        ax = histplot(long_df, y="a")
+        ymax, ymin = ax.get_ylim()
+        assert ymax > ymin
+
+    def test_datetime_scale(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        histplot(x=long_df["t"], fill=True, ax=ax1)
+        histplot(x=long_df["t"], fill=False, ax=ax2)
+        assert ax1.get_xlim() == ax2.get_xlim()
+
+    @pytest.mark.parametrize("stat", ["count", "density", "probability"])
+    def test_kde(self, flat_series, stat):
+
+        ax = histplot(
+            flat_series, kde=True, stat=stat, kde_kws={"cut": 10}
+        )
+
+        bar_widths = [b.get_width() for b in ax.patches]
+        bar_heights = [b.get_height() for b in ax.patches]
+        hist_area = np.multiply(bar_widths, bar_heights).sum()
+
+        density, = ax.lines
+        kde_area = integrate(density.get_ydata(), density.get_xdata())
+
+        assert kde_area == pytest.approx(hist_area)
+
+    @pytest.mark.parametrize("multiple", ["layer", "dodge"])
+    @pytest.mark.parametrize("stat", ["count", "density", "probability"])
+    def test_kde_with_hue(self, long_df, stat, multiple):
+
+        n = 10
+        ax = histplot(
+            long_df, x="x", hue="c", multiple=multiple,
+            kde=True, stat=stat, element="bars",
+            kde_kws={"cut": 10}, bins=n,
+        )
+
+        bar_groups = ax.patches[:n], ax.patches[-n:]
+
+        for i, bars in enumerate(bar_groups):
+            bar_widths = [b.get_width() for b in bars]
+            bar_heights = [b.get_height() for b in bars]
+            hist_area = np.multiply(bar_widths, bar_heights).sum()
+
+            x, y = ax.lines[i].get_xydata().T
+            kde_area = integrate(y, x)
+
+            if multiple == "layer":
+                assert kde_area == pytest.approx(hist_area)
+            elif multiple == "dodge":
+                assert kde_area == pytest.approx(hist_area * 2)
+
+    def test_kde_default_cut(self, flat_series):
+
+        ax = histplot(flat_series, kde=True)
+        support = ax.lines[0].get_xdata()
+        assert support.min() == flat_series.min()
+        assert support.max() == flat_series.max()
+
+    def test_kde_hue(self, long_df):
+
+        n = 10
+        ax = histplot(data=long_df, x="x", hue="a", kde=True, bins=n)
+
+        for bar, line in zip(ax.patches[::n], ax.lines):
+            assert_colors_equal(
+                bar.get_facecolor(), line.get_color(), check_alpha=False
+            )
+
+    def test_kde_yaxis(self, flat_series):
+
+        f, ax = plt.subplots()
+        histplot(x=flat_series, kde=True)
+        histplot(y=flat_series, kde=True)
+
+        x, y = ax.lines
+        assert_array_equal(x.get_xdata(), y.get_ydata())
+        assert_array_equal(x.get_ydata(), y.get_xdata())
+
+    def test_kde_line_kws(self, flat_series):
+
+        lw = 5
+        ax = histplot(flat_series, kde=True, line_kws=dict(lw=lw))
+        assert ax.lines[0].get_linewidth() == lw
+
+    def test_kde_singular_data(self):
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            ax = histplot(x=np.ones(10), kde=True)
+        assert not ax.lines
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            ax = histplot(x=[5], kde=True)
+        assert not ax.lines
+
+    def test_element_default(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        histplot(long_df, x="x", ax=ax1)
+        histplot(long_df, x="x", ax=ax2, element="bars")
+        assert len(ax1.patches) == len(ax2.patches)
+
+        f, (ax1, ax2) = plt.subplots(2)
+        histplot(long_df, x="x", hue="a", ax=ax1)
+        histplot(long_df, x="x", hue="a", ax=ax2, element="bars")
+        assert len(ax1.patches) == len(ax2.patches)
+
+    def test_bars_no_fill(self, flat_series):
+
+        alpha = .5
+        ax = histplot(flat_series, element="bars", fill=False, alpha=alpha)
+        for bar in ax.patches:
+            assert bar.get_facecolor() == (0, 0, 0, 0)
+            assert bar.get_edgecolor()[-1] == alpha
+
+    def test_step_fill(self, flat_series):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        n = 10
+        histplot(flat_series, element="bars", fill=True, bins=n, ax=ax1)
+        histplot(flat_series, element="step", fill=True, bins=n, ax=ax2)
+
+        bar_heights = [b.get_height() for b in ax1.patches]
+        bar_widths = [b.get_width() for b in ax1.patches]
+        bar_edges = [b.get_x() for b in ax1.patches]
+
+        fill = ax2.collections[0]
+        x, y = fill.get_paths()[0].vertices[::-1].T
+
+        assert_array_equal(x[1:2 * n:2], bar_edges)
+        assert_array_equal(y[1:2 * n:2], bar_heights)
+
+        assert x[n * 2] == bar_edges[-1] + bar_widths[-1]
+        assert y[n * 2] == bar_heights[-1]
+
+    def test_poly_fill(self, flat_series):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        n = 10
+        histplot(flat_series, element="bars", fill=True, bins=n, ax=ax1)
+        histplot(flat_series, element="poly", fill=True, bins=n, ax=ax2)
+
+        bar_heights = np.array([b.get_height() for b in ax1.patches])
+        bar_widths = np.array([b.get_width() for b in ax1.patches])
+        bar_edges = np.array([b.get_x() for b in ax1.patches])
+
+        fill = ax2.collections[0]
+        x, y = fill.get_paths()[0].vertices[::-1].T
+
+        assert_array_equal(x[1:n + 1], bar_edges + bar_widths / 2)
+        assert_array_equal(y[1:n + 1], bar_heights)
+
+    def test_poly_no_fill(self, flat_series):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        n = 10
+        histplot(flat_series, element="bars", fill=False, bins=n, ax=ax1)
+        histplot(flat_series, element="poly", fill=False, bins=n, ax=ax2)
+
+        bar_heights = np.array([b.get_height() for b in ax1.patches])
+        bar_widths = np.array([b.get_width() for b in ax1.patches])
+        bar_edges = np.array([b.get_x() for b in ax1.patches])
+
+        x, y = ax2.lines[0].get_xydata().T
+
+        assert_array_equal(x, bar_edges + bar_widths / 2)
+        assert_array_equal(y, bar_heights)
+
+    def test_step_no_fill(self, flat_series):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        histplot(flat_series, element="bars", fill=False, ax=ax1)
+        histplot(flat_series, element="step", fill=False, ax=ax2)
+
+        bar_heights = [b.get_height() for b in ax1.patches]
+        bar_widths = [b.get_width() for b in ax1.patches]
+        bar_edges = [b.get_x() for b in ax1.patches]
+
+        x, y = ax2.lines[0].get_xydata().T
+
+        assert_array_equal(x[:-1], bar_edges)
+        assert_array_equal(y[:-1], bar_heights)
+        assert x[-1] == bar_edges[-1] + bar_widths[-1]
+        assert y[-1] == y[-2]
+
+    def test_step_fill_xy(self, flat_series):
+
+        f, ax = plt.subplots()
+
+        histplot(x=flat_series, element="step", fill=True)
+        histplot(y=flat_series, element="step", fill=True)
+
+        xverts = ax.collections[0].get_paths()[0].vertices
+        yverts = ax.collections[1].get_paths()[0].vertices
+
+        assert_array_equal(xverts, yverts[:, ::-1])
+
+    def test_step_no_fill_xy(self, flat_series):
+
+        f, ax = plt.subplots()
+
+        histplot(x=flat_series, element="step", fill=False)
+        histplot(y=flat_series, element="step", fill=False)
+
+        xline, yline = ax.lines
+
+        assert_array_equal(xline.get_xdata(), yline.get_ydata())
+        assert_array_equal(xline.get_ydata(), yline.get_xdata())
+
+    def test_weighted_histogram(self):
+
+        ax = histplot(x=[0, 1, 2], weights=[1, 2, 3], discrete=True)
+
+        bar_heights = [b.get_height() for b in ax.patches]
+        assert bar_heights == [1, 2, 3]
+
+    def test_weights_with_auto_bins(self, long_df):
+
+        with pytest.warns(UserWarning):
+            ax = histplot(long_df, x="x", weights="f")
+        assert len(ax.patches) == 10
+
+    def test_shrink(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(2)
+
+        bw = 2
+        shrink = .4
+
+        histplot(long_df, x="x", binwidth=bw, ax=ax1)
+        histplot(long_df, x="x", binwidth=bw, shrink=shrink, ax=ax2)
+
+        for p1, p2 in zip(ax1.patches, ax2.patches):
+
+            w1, w2 = p1.get_width(), p2.get_width()
+            assert w2 == pytest.approx(shrink * w1)
+
+            x1, x2 = p1.get_x(), p2.get_x()
+            assert (x2 + w2 / 2) == pytest.approx(x1 + w1 / 2)
+
+    def test_log_scale_explicit(self, rng):
+
+        x = rng.lognormal(0, 2, 1000)
+        ax = histplot(x, log_scale=True, binwidth=1)
+
+        bar_widths = [b.get_width() for b in ax.patches]
+        steps = np.divide(bar_widths[1:], bar_widths[:-1])
+        assert np.allclose(steps, 10)
+
+    def test_log_scale_implicit(self, rng):
+
+        x = rng.lognormal(0, 2, 1000)
+
+        f, ax = plt.subplots()
+        ax.set_xscale("log")
+        histplot(x, binwidth=1, ax=ax)
+
+        bar_widths = [b.get_width() for b in ax.patches]
+        steps = np.divide(bar_widths[1:], bar_widths[:-1])
+        assert np.allclose(steps, 10)
+
+    def test_log_scale_dodge(self, rng):
+
+        x = rng.lognormal(0, 2, 100)
+        hue = np.repeat(["a", "b"], 50)
+        ax = histplot(x=x, hue=hue, bins=5, log_scale=True, multiple="dodge")
+        x_min = np.log([b.get_x() for b in ax.patches])
+        x_max = np.log([b.get_x() + b.get_width() for b in ax.patches])
+        assert np.unique(np.round(x_max - x_min, 10)).size == 1
+
+    def test_log_scale_kde(self, rng):
+
+        x = rng.lognormal(0, 1, 1000)
+        ax = histplot(x=x, log_scale=True, kde=True, bins=20)
+        bar_height = max(p.get_height() for p in ax.patches)
+        kde_height = max(ax.lines[0].get_ydata())
+        assert bar_height == pytest.approx(kde_height, rel=.1)
+
+    @pytest.mark.parametrize(
+        "fill", [True, False],
+    )
+    def test_auto_linewidth(self, flat_series, fill):
+
+        get_lw = lambda ax: ax.patches[0].get_linewidth()  # noqa: E731
+
+        kws = dict(element="bars", fill=fill)
+
+        f, (ax1, ax2) = plt.subplots(2)
+        histplot(flat_series, **kws, bins=10, ax=ax1)
+        histplot(flat_series, **kws, bins=100, ax=ax2)
+        assert get_lw(ax1) > get_lw(ax2)
+
+        f, ax1 = plt.subplots(figsize=(10, 5))
+        f, ax2 = plt.subplots(figsize=(2, 5))
+        histplot(flat_series, **kws, bins=30, ax=ax1)
+        histplot(flat_series, **kws, bins=30, ax=ax2)
+        assert get_lw(ax1) > get_lw(ax2)
+
+        f, ax1 = plt.subplots(figsize=(4, 5))
+        f, ax2 = plt.subplots(figsize=(4, 5))
+        histplot(flat_series, **kws, bins=30, ax=ax1)
+        histplot(10 ** flat_series, **kws, bins=30, log_scale=True, ax=ax2)
+        assert get_lw(ax1) == pytest.approx(get_lw(ax2))
+
+        f, ax1 = plt.subplots(figsize=(4, 5))
+        f, ax2 = plt.subplots(figsize=(4, 5))
+        histplot(y=[0, 1, 1], **kws, discrete=True, ax=ax1)
+        histplot(y=["a", "b", "b"], **kws, ax=ax2)
+        assert get_lw(ax1) == pytest.approx(get_lw(ax2))
+
+    def test_bar_kwargs(self, flat_series):
+
+        lw = 2
+        ec = (1, .2, .9, .5)
+        ax = histplot(flat_series, binwidth=1, ec=ec, lw=lw)
+        for bar in ax.patches:
+            assert_colors_equal(bar.get_edgecolor(), ec)
+            assert bar.get_linewidth() == lw
+
+    def test_step_fill_kwargs(self, flat_series):
+
+        lw = 2
+        ec = (1, .2, .9, .5)
+        ax = histplot(flat_series, element="step", ec=ec, lw=lw)
+        poly = ax.collections[0]
+        assert_colors_equal(poly.get_edgecolor(), ec)
+        assert poly.get_linewidth() == lw
+
+    def test_step_line_kwargs(self, flat_series):
+
+        lw = 2
+        ls = "--"
+        ax = histplot(flat_series, element="step", fill=False, lw=lw, ls=ls)
+        line = ax.lines[0]
+        assert line.get_linewidth() == lw
+        assert line.get_linestyle() == ls
+
+    def test_label(self, flat_series):
+
+        ax = histplot(flat_series, label="a label")
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(handles) == 1
+        assert labels == ["a label"]
+
+
+class TestHistPlotBivariate:
+
+    def test_mesh(self, long_df):
+
+        hist = Histogram()
+        counts, (x_edges, y_edges) = hist(long_df["x"], long_df["y"])
+
+        ax = histplot(long_df, x="x", y="y")
+        mesh = ax.collections[0]
+        mesh_data = mesh.get_array()
+
+        assert_array_equal(mesh_data.data, counts.T.flat)
+        assert_array_equal(mesh_data.mask, counts.T.flat == 0)
+
+        edges = itertools.product(y_edges[:-1], x_edges[:-1])
+        for i, (y, x) in enumerate(edges):
+            path = mesh.get_paths()[i]
+            assert path.vertices[0, 0] == x
+            assert path.vertices[0, 1] == y
+
+    def test_mesh_with_hue(self, long_df):
+
+        ax = histplot(long_df, x="x", y="y", hue="c")
+
+        hist = Histogram()
+        hist.define_bin_params(long_df["x"], long_df["y"])
+
+        for i, sub_df in long_df.groupby("c"):
+
+            mesh = ax.collections[i]
+            mesh_data = mesh.get_array()
+
+            counts, (x_edges, y_edges) = hist(sub_df["x"], sub_df["y"])
+
+            assert_array_equal(mesh_data.data, counts.T.flat)
+            assert_array_equal(mesh_data.mask, counts.T.flat == 0)
+
+            edges = itertools.product(y_edges[:-1], x_edges[:-1])
+            for i, (y, x) in enumerate(edges):
+                path = mesh.get_paths()[i]
+                assert path.vertices[0, 0] == x
+                assert path.vertices[0, 1] == y
+
+    def test_mesh_with_hue_unique_bins(self, long_df):
+
+        ax = histplot(long_df, x="x", y="y", hue="c", common_bins=False)
+
+        for i, sub_df in long_df.groupby("c"):
+
+            hist = Histogram()
+
+            mesh = ax.collections[i]
+            mesh_data = mesh.get_array()
+
+            counts, (x_edges, y_edges) = hist(sub_df["x"], sub_df["y"])
+
+            assert_array_equal(mesh_data.data, counts.T.flat)
+            assert_array_equal(mesh_data.mask, counts.T.flat == 0)
+
+            edges = itertools.product(y_edges[:-1], x_edges[:-1])
+            for i, (y, x) in enumerate(edges):
+                path = mesh.get_paths()[i]
+                assert path.vertices[0, 0] == x
+                assert path.vertices[0, 1] == y
+
+    def test_mesh_with_col_unique_bins(self, long_df):
+
+        g = displot(long_df, x="x", y="y", col="c", common_bins=False)
+
+        for i, sub_df in long_df.groupby("c"):
+
+            hist = Histogram()
+
+            mesh = g.axes.flat[i].collections[0]
+            mesh_data = mesh.get_array()
+
+            counts, (x_edges, y_edges) = hist(sub_df["x"], sub_df["y"])
+
+            assert_array_equal(mesh_data.data, counts.T.flat)
+            assert_array_equal(mesh_data.mask, counts.T.flat == 0)
+
+            edges = itertools.product(y_edges[:-1], x_edges[:-1])
+            for i, (y, x) in enumerate(edges):
+                path = mesh.get_paths()[i]
+                assert path.vertices[0, 0] == x
+                assert path.vertices[0, 1] == y
+
+    def test_mesh_log_scale(self, rng):
+
+        x, y = rng.lognormal(0, 1, (2, 1000))
+        hist = Histogram()
+        counts, (x_edges, y_edges) = hist(np.log10(x), np.log10(y))
+
+        ax = histplot(x=x, y=y, log_scale=True)
+        mesh = ax.collections[0]
+        mesh_data = mesh.get_array()
+
+        assert_array_equal(mesh_data.data, counts.T.flat)
+
+        edges = itertools.product(y_edges[:-1], x_edges[:-1])
+        for i, (y_i, x_i) in enumerate(edges):
+            path = mesh.get_paths()[i]
+            assert path.vertices[0, 0] == pytest.approx(10 ** x_i)
+            assert path.vertices[0, 1] == pytest.approx(10 ** y_i)
+
+    def test_mesh_thresh(self, long_df):
+
+        hist = Histogram()
+        counts, (x_edges, y_edges) = hist(long_df["x"], long_df["y"])
+
+        thresh = 5
+        ax = histplot(long_df, x="x", y="y", thresh=thresh)
+        mesh = ax.collections[0]
+        mesh_data = mesh.get_array()
+
+        assert_array_equal(mesh_data.data, counts.T.flat)
+        assert_array_equal(mesh_data.mask, (counts <= thresh).T.flat)
+
+    def test_mesh_sticky_edges(self, long_df):
+
+        ax = histplot(long_df, x="x", y="y", thresh=None)
+        mesh = ax.collections[0]
+        assert mesh.sticky_edges.x == [long_df["x"].min(), long_df["x"].max()]
+        assert mesh.sticky_edges.y == [long_df["y"].min(), long_df["y"].max()]
+
+        ax.clear()
+        ax = histplot(long_df, x="x", y="y")
+        mesh = ax.collections[0]
+        assert not mesh.sticky_edges.x
+        assert not mesh.sticky_edges.y
+
+    def test_mesh_common_norm(self, long_df):
+
+        stat = "density"
+        ax = histplot(
+            long_df, x="x", y="y", hue="c", common_norm=True, stat=stat,
+        )
+
+        hist = Histogram(stat="density")
+        hist.define_bin_params(long_df["x"], long_df["y"])
+
+        for i, sub_df in long_df.groupby("c"):
+
+            mesh = ax.collections[i]
+            mesh_data = mesh.get_array()
+
+            density, (x_edges, y_edges) = hist(sub_df["x"], sub_df["y"])
+
+            scale = len(sub_df) / len(long_df)
+            assert_array_equal(mesh_data.data, (density * scale).T.flat)
+
+    def test_mesh_unique_norm(self, long_df):
+
+        stat = "density"
+        ax = histplot(
+            long_df, x="x", y="y", hue="c", common_norm=False, stat=stat,
+        )
+
+        hist = Histogram()
+        bin_kws = hist.define_bin_params(long_df["x"], long_df["y"])
+
+        for i, sub_df in long_df.groupby("c"):
+
+            sub_hist = Histogram(bins=bin_kws["bins"], stat=stat)
+
+            mesh = ax.collections[i]
+            mesh_data = mesh.get_array()
+
+            density, (x_edges, y_edges) = sub_hist(sub_df["x"], sub_df["y"])
+            assert_array_equal(mesh_data.data, density.T.flat)
+
+    @pytest.mark.parametrize("stat", ["probability", "proportion", "percent"])
+    def test_mesh_normalization(self, long_df, stat):
+
+        ax = histplot(
+            long_df, x="x", y="y", stat=stat,
+        )
+
+        mesh_data = ax.collections[0].get_array()
+        expected_sum = {"percent": 100}.get(stat, 1)
+        assert mesh_data.data.sum() == expected_sum
+
+    def test_mesh_colors(self, long_df):
+
+        color = "r"
+        f, ax = plt.subplots()
+        histplot(
+            long_df, x="x", y="y", color=color,
+        )
+        mesh = ax.collections[0]
+        assert_array_equal(
+            mesh.get_cmap().colors,
+            _DistributionPlotter()._cmap_from_color(color).colors,
+        )
+
+        f, ax = plt.subplots()
+        histplot(
+            long_df, x="x", y="y", hue="c",
+        )
+        colors = color_palette()
+        for i, mesh in enumerate(ax.collections):
+            assert_array_equal(
+                mesh.get_cmap().colors,
+                _DistributionPlotter()._cmap_from_color(colors[i]).colors,
+            )
+
+    def test_color_limits(self, long_df):
+
+        f, (ax1, ax2, ax3) = plt.subplots(3)
+        kws = dict(data=long_df, x="x", y="y")
+        hist = Histogram()
+        counts, _ = hist(long_df["x"], long_df["y"])
+
+        histplot(**kws, ax=ax1)
+        assert ax1.collections[0].get_clim() == (0, counts.max())
+
+        vmax = 10
+        histplot(**kws, vmax=vmax, ax=ax2)
+        counts, _ = hist(long_df["x"], long_df["y"])
+        assert ax2.collections[0].get_clim() == (0, vmax)
+
+        pmax = .8
+        pthresh = .1
+        f = _DistributionPlotter()._quantile_to_level
+
+        histplot(**kws, pmax=pmax, pthresh=pthresh, ax=ax3)
+        counts, _ = hist(long_df["x"], long_df["y"])
+        mesh = ax3.collections[0]
+        assert mesh.get_clim() == (0, f(counts, pmax))
+        assert_array_equal(
+            mesh.get_array().mask,
+            (counts <= f(counts, pthresh)).T.flat,
+        )
+
+    def test_hue_color_limits(self, long_df):
+
+        _, (ax1, ax2, ax3, ax4) = plt.subplots(4)
+        kws = dict(data=long_df, x="x", y="y", hue="c", bins=4)
+
+        hist = Histogram(bins=kws["bins"])
+        hist.define_bin_params(long_df["x"], long_df["y"])
+        full_counts, _ = hist(long_df["x"], long_df["y"])
+
+        sub_counts = []
+        for _, sub_df in long_df.groupby(kws["hue"]):
+            c, _ = hist(sub_df["x"], sub_df["y"])
+            sub_counts.append(c)
+
+        pmax = .8
+        pthresh = .05
+        f = _DistributionPlotter()._quantile_to_level
+
+        histplot(**kws, common_norm=True, ax=ax1)
+        for i, mesh in enumerate(ax1.collections):
+            assert mesh.get_clim() == (0, full_counts.max())
+
+        histplot(**kws, common_norm=False, ax=ax2)
+        for i, mesh in enumerate(ax2.collections):
+            assert mesh.get_clim() == (0, sub_counts[i].max())
+
+        histplot(**kws, common_norm=True, pmax=pmax, pthresh=pthresh, ax=ax3)
+        for i, mesh in enumerate(ax3.collections):
+            assert mesh.get_clim() == (0, f(full_counts, pmax))
+            assert_array_equal(
+                mesh.get_array().mask,
+                (sub_counts[i] <= f(full_counts, pthresh)).T.flat,
+            )
+
+        histplot(**kws, common_norm=False, pmax=pmax, pthresh=pthresh, ax=ax4)
+        for i, mesh in enumerate(ax4.collections):
+            assert mesh.get_clim() == (0, f(sub_counts[i], pmax))
+            assert_array_equal(
+                mesh.get_array().mask,
+                (sub_counts[i] <= f(sub_counts[i], pthresh)).T.flat,
+            )
+
+    def test_colorbar(self, long_df):
+
+        f, ax = plt.subplots()
+        histplot(long_df, x="x", y="y", cbar=True, ax=ax)
+        assert len(ax.figure.axes) == 2
+
+        f, (ax, cax) = plt.subplots(2)
+        histplot(long_df, x="x", y="y", cbar=True, cbar_ax=cax, ax=ax)
+        assert len(ax.figure.axes) == 2
+
+
+class TestECDFPlotUnivariate(SharedAxesLevelTests):
+
+    func = staticmethod(ecdfplot)
+
+    def get_last_color(self, ax):
+
+        return to_rgb(ax.lines[-1].get_color())
+
+    @pytest.mark.parametrize("variable", ["x", "y"])
+    def test_long_vectors(self, long_df, variable):
+
+        vector = long_df[variable]
+        vectors = [
+            variable, vector, vector.to_numpy(), vector.to_list(),
+        ]
+
+        f, ax = plt.subplots()
+        for vector in vectors:
+            ecdfplot(data=long_df, ax=ax, **{variable: vector})
+
+        xdata = [l.get_xdata() for l in ax.lines]
+        for a, b in itertools.product(xdata, xdata):
+            assert_array_equal(a, b)
+
+        ydata = [l.get_ydata() for l in ax.lines]
+        for a, b in itertools.product(ydata, ydata):
+            assert_array_equal(a, b)
+
+    def test_hue(self, long_df):
+
+        ax = ecdfplot(long_df, x="x", hue="a")
+
+        for line, color in zip(ax.lines[::-1], color_palette()):
+            assert_colors_equal(line.get_color(), color)
+
+    def test_line_kwargs(self, long_df):
+
+        color = "r"
+        ls = "--"
+        lw = 3
+        ax = ecdfplot(long_df, x="x", color=color, ls=ls, lw=lw)
+
+        for line in ax.lines:
+            assert_colors_equal(line.get_color(), color)
+            assert line.get_linestyle() == ls
+            assert line.get_linewidth() == lw
+
+    @pytest.mark.parametrize("data_var", ["x", "y"])
+    def test_drawstyle(self, flat_series, data_var):
+
+        ax = ecdfplot(**{data_var: flat_series})
+        drawstyles = dict(x="steps-post", y="steps-pre")
+        assert ax.lines[0].get_drawstyle() == drawstyles[data_var]
+
+    @pytest.mark.parametrize(
+        "data_var,stat_var", [["x", "y"], ["y", "x"]],
+    )
+    def test_proportion_limits(self, flat_series, data_var, stat_var):
+
+        ax = ecdfplot(**{data_var: flat_series})
+        data = getattr(ax.lines[0], f"get_{stat_var}data")()
+        assert data[0] == 0
+        assert data[-1] == 1
+        sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)
+        assert sticky_edges[:] == [0, 1]
+
+    @pytest.mark.parametrize(
+        "data_var,stat_var", [["x", "y"], ["y", "x"]],
+    )
+    def test_proportion_limits_complementary(self, flat_series, data_var, stat_var):
+
+        ax = ecdfplot(**{data_var: flat_series}, complementary=True)
+        data = getattr(ax.lines[0], f"get_{stat_var}data")()
+        assert data[0] == 1
+        assert data[-1] == 0
+        sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)
+        assert sticky_edges[:] == [0, 1]
+
+    @pytest.mark.parametrize(
+        "data_var,stat_var", [["x", "y"], ["y", "x"]],
+    )
+    def test_proportion_count(self, flat_series, data_var, stat_var):
+
+        n = len(flat_series)
+        ax = ecdfplot(**{data_var: flat_series}, stat="count")
+        data = getattr(ax.lines[0], f"get_{stat_var}data")()
+        assert data[0] == 0
+        assert data[-1] == n
+        sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)
+        assert sticky_edges[:] == [0, n]
+
+    def test_weights(self):
+
+        ax = ecdfplot(x=[1, 2, 3], weights=[1, 1, 2])
+        y = ax.lines[0].get_ydata()
+        assert_array_equal(y, [0, .25, .5, 1])
+
+    def test_bivariate_error(self, long_df):
+
+        with pytest.raises(NotImplementedError, match="Bivariate ECDF plots"):
+            ecdfplot(data=long_df, x="x", y="y")
+
+    def test_log_scale(self, long_df):
+
+        ax1, ax2 = plt.figure().subplots(2)
+
+        ecdfplot(data=long_df, x="z", ax=ax1)
+        ecdfplot(data=long_df, x="z", log_scale=True, ax=ax2)
+
+        # Ignore first point, which either -inf (in linear) or 0 (in log)
+        line1 = ax1.lines[0].get_xydata()[1:]
+        line2 = ax2.lines[0].get_xydata()[1:]
+
+        assert_array_almost_equal(line1, line2)
+
+
+class TestDisPlot:
+
+    # TODO probably good to move these utility attributes/methods somewhere else
+    @pytest.mark.parametrize(
+        "kwargs", [
+            dict(),
+            dict(x="x"),
+            dict(x="t"),
+            dict(x="a"),
+            dict(x="z", log_scale=True),
+            dict(x="x", binwidth=4),
+            dict(x="x", weights="f", bins=5),
+            dict(x="x", color="green", linewidth=2, binwidth=4),
+            dict(x="x", hue="a", fill=False),
+            dict(x="y", hue="a", fill=False),
+            dict(x="x", hue="a", multiple="stack"),
+            dict(x="x", hue="a", element="step"),
+            dict(x="x", hue="a", palette="muted"),
+            dict(x="x", hue="a", kde=True),
+            dict(x="x", hue="a", stat="density", common_norm=False),
+            dict(x="x", y="y"),
+        ],
+    )
+    def test_versus_single_histplot(self, long_df, kwargs):
+
+        ax = histplot(long_df, **kwargs)
+        g = displot(long_df, **kwargs)
+        assert_plots_equal(ax, g.ax)
+
+        if ax.legend_ is not None:
+            assert_legends_equal(ax.legend_, g._legend)
+
+        if kwargs:
+            long_df["_"] = "_"
+            g2 = displot(long_df, col="_", **kwargs)
+            assert_plots_equal(ax, g2.ax)
+
+    @pytest.mark.parametrize(
+        "kwargs", [
+            dict(),
+            dict(x="x"),
+            dict(x="t"),
+            dict(x="z", log_scale=True),
+            dict(x="x", bw_adjust=.5),
+            dict(x="x", weights="f"),
+            dict(x="x", color="green", linewidth=2),
+            dict(x="x", hue="a", multiple="stack"),
+            dict(x="x", hue="a", fill=True),
+            dict(x="y", hue="a", fill=False),
+            dict(x="x", hue="a", palette="muted"),
+            dict(x="x", y="y"),
+        ],
+    )
+    def test_versus_single_kdeplot(self, long_df, kwargs):
+
+        ax = kdeplot(data=long_df, **kwargs)
+        g = displot(long_df, kind="kde", **kwargs)
+        assert_plots_equal(ax, g.ax)
+
+        if ax.legend_ is not None:
+            assert_legends_equal(ax.legend_, g._legend)
+
+        if kwargs:
+            long_df["_"] = "_"
+            g2 = displot(long_df, kind="kde", col="_", **kwargs)
+            assert_plots_equal(ax, g2.ax)
+
+    @pytest.mark.parametrize(
+        "kwargs", [
+            dict(),
+            dict(x="x"),
+            dict(x="t"),
+            dict(x="z", log_scale=True),
+            dict(x="x", weights="f"),
+            dict(y="x"),
+            dict(x="x", color="green", linewidth=2),
+            dict(x="x", hue="a", complementary=True),
+            dict(x="x", hue="a", stat="count"),
+            dict(x="x", hue="a", palette="muted"),
+        ],
+    )
+    def test_versus_single_ecdfplot(self, long_df, kwargs):
+
+        ax = ecdfplot(data=long_df, **kwargs)
+        g = displot(long_df, kind="ecdf", **kwargs)
+        assert_plots_equal(ax, g.ax)
+
+        if ax.legend_ is not None:
+            assert_legends_equal(ax.legend_, g._legend)
+
+        if kwargs:
+            long_df["_"] = "_"
+            g2 = displot(long_df, kind="ecdf", col="_", **kwargs)
+            assert_plots_equal(ax, g2.ax)
+
+    @pytest.mark.parametrize(
+        "kwargs", [
+            dict(x="x"),
+            dict(x="x", y="y"),
+            dict(x="x", hue="a"),
+        ]
+    )
+    def test_with_rug(self, long_df, kwargs):
+
+        ax = plt.figure().subplots()
+        histplot(data=long_df, **kwargs, ax=ax)
+        rugplot(data=long_df, **kwargs, ax=ax)
+
+        g = displot(long_df, rug=True, **kwargs)
+
+        assert_plots_equal(ax, g.ax, labels=False)
+
+        long_df["_"] = "_"
+        g2 = displot(long_df, col="_", rug=True, **kwargs)
+
+        assert_plots_equal(ax, g2.ax, labels=False)
+
+    @pytest.mark.parametrize(
+        "facet_var", ["col", "row"],
+    )
+    def test_facets(self, long_df, facet_var):
+
+        kwargs = {facet_var: "a"}
+        ax = kdeplot(data=long_df, x="x", hue="a")
+        g = displot(long_df, x="x", kind="kde", **kwargs)
+
+        legend_texts = ax.legend_.get_texts()
+
+        for i, line in enumerate(ax.lines[::-1]):
+            facet_ax = g.axes.flat[i]
+            facet_line = facet_ax.lines[0]
+            assert_array_equal(line.get_xydata(), facet_line.get_xydata())
+
+            text = legend_texts[i].get_text()
+            assert text in facet_ax.get_title()
+
+    @pytest.mark.parametrize("multiple", ["dodge", "stack", "fill"])
+    def test_facet_multiple(self, long_df, multiple):
+
+        bins = np.linspace(0, 20, 5)
+        ax = histplot(
+            data=long_df[long_df["c"] == 0],
+            x="x", hue="a", hue_order=["a", "b", "c"],
+            multiple=multiple, bins=bins,
+        )
+
+        g = displot(
+            data=long_df, x="x", hue="a", col="c", hue_order=["a", "b", "c"],
+            multiple=multiple, bins=bins,
+        )
+
+        assert_plots_equal(ax, g.axes_dict[0])
+
+    def test_ax_warning(self, long_df):
+
+        ax = plt.figure().subplots()
+        with pytest.warns(UserWarning, match="`displot` is a figure-level"):
+            displot(long_df, x="x", ax=ax)
+
+    @pytest.mark.parametrize("key", ["col", "row"])
+    def test_array_faceting(self, long_df, key):
+
+        a = long_df["a"].to_numpy()
+        vals = categorical_order(a)
+        g = displot(long_df, x="x", **{key: a})
+        assert len(g.axes.flat) == len(vals)
+        for ax, val in zip(g.axes.flat, vals):
+            assert val in ax.get_title()
+
+    def test_legend(self, long_df):
+
+        g = displot(long_df, x="x", hue="a")
+        assert g._legend is not None
+
+    def test_empty(self):
+
+        g = displot(x=[], y=[])
+        assert isinstance(g, FacetGrid)
+
+    def test_bivariate_ecdf_error(self, long_df):
+
+        with pytest.raises(NotImplementedError):
+            displot(long_df, x="x", y="y", kind="ecdf")
+
+    def test_bivariate_kde_norm(self, rng):
+
+        x, y = rng.normal(0, 1, (2, 100))
+        z = [0] * 80 + [1] * 20
+
+        g = displot(x=x, y=y, col=z, kind="kde", levels=10)
+        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)
+        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)
+        assert l1 > l2
+
+        g = displot(x=x, y=y, col=z, kind="kde", levels=10, common_norm=False)
+        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)
+        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)
+        assert l1 == l2
+
+    def test_bivariate_hist_norm(self, rng):
+
+        x, y = rng.normal(0, 1, (2, 100))
+        z = [0] * 80 + [1] * 20
+
+        g = displot(x=x, y=y, col=z, kind="hist")
+        clim1 = g.axes.flat[0].collections[0].get_clim()
+        clim2 = g.axes.flat[1].collections[0].get_clim()
+        assert clim1 == clim2
+
+        g = displot(x=x, y=y, col=z, kind="hist", common_norm=False)
+        clim1 = g.axes.flat[0].collections[0].get_clim()
+        clim2 = g.axes.flat[1].collections[0].get_clim()
+        assert clim1[1] > clim2[1]
+
+    def test_facetgrid_data(self, long_df):
+
+        g = displot(
+            data=long_df.to_dict(orient="list"),
+            x="z",
+            hue=long_df["a"].rename("hue_var"),
+            col=long_df["c"].to_numpy(),
+        )
+        expected_cols = set(long_df.columns.to_list() + ["hue_var", "_col_"])
+        assert set(g.data.columns) == expected_cols
+        assert_array_equal(g.data["hue_var"], long_df["a"])
+        assert_array_equal(g.data["_col_"], long_df["c"])
+
+
+def integrate(y, x):
+    """"Simple numerical integration for testing KDE code."""
+    y = np.asarray(y)
+    x = np.asarray(x)
+    dx = np.diff(x)
+    return (dx * y[:-1] + dx * y[1:]).sum() / 2
diff --git a/testbed/mwaskom__seaborn/tests/test_docstrings.py b/testbed/mwaskom__seaborn/tests/test_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc6c5106c62bc75314e0b9593bc14071b8f3a67f
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_docstrings.py
@@ -0,0 +1,58 @@
+from seaborn._docstrings import DocstringComponents
+
+
+EXAMPLE_DICT = dict(
+    param_a="""
+a : str
+    The first parameter.
+    """,
+)
+
+
+class ExampleClass:
+    def example_method(self):
+        """An example method.
+
+        Parameters
+        ----------
+        a : str
+           A method parameter.
+
+        """
+
+
+def example_func():
+    """An example function.
+
+    Parameters
+    ----------
+    a : str
+        A function parameter.
+
+    """
+
+
+class TestDocstringComponents:
+
+    def test_from_dict(self):
+
+        obj = DocstringComponents(EXAMPLE_DICT)
+        assert obj.param_a == "a : str\n    The first parameter."
+
+    def test_from_nested_components(self):
+
+        obj_inner = DocstringComponents(EXAMPLE_DICT)
+        obj_outer = DocstringComponents.from_nested_components(inner=obj_inner)
+        assert obj_outer.inner.param_a == "a : str\n    The first parameter."
+
+    def test_from_function(self):
+
+        obj = DocstringComponents.from_function_params(example_func)
+        assert obj.a == "a : str\n    A function parameter."
+
+    def test_from_method(self):
+
+        obj = DocstringComponents.from_function_params(
+            ExampleClass.example_method
+        )
+        assert obj.a == "a : str\n    A method parameter."
diff --git a/testbed/mwaskom__seaborn/tests/test_matrix.py b/testbed/mwaskom__seaborn/tests/test_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..159bb0635bf2601ae2709cb5ae40eb4f9caf3ad3
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_matrix.py
@@ -0,0 +1,1343 @@
+import tempfile
+import copy
+
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+import pandas as pd
+
+try:
+    from scipy.spatial import distance
+    from scipy.cluster import hierarchy
+    _no_scipy = False
+except ImportError:
+    _no_scipy = True
+
+try:
+    import fastcluster
+    assert fastcluster
+    _no_fastcluster = False
+except ImportError:
+    _no_fastcluster = True
+
+import numpy.testing as npt
+try:
+    import pandas.testing as pdt
+except ImportError:
+    import pandas.util.testing as pdt
+import pytest
+
+from seaborn import matrix as mat
+from seaborn import color_palette
+from seaborn._compat import get_colormap
+from seaborn._testing import assert_colors_equal
+
+
+class TestHeatmap:
+    rs = np.random.RandomState(sum(map(ord, "heatmap")))
+
+    x_norm = rs.randn(4, 8)
+    letters = pd.Series(["A", "B", "C", "D"], name="letters")
+    df_norm = pd.DataFrame(x_norm, index=letters)
+
+    x_unif = rs.rand(20, 13)
+    df_unif = pd.DataFrame(x_unif)
+
+    default_kws = dict(vmin=None, vmax=None, cmap=None, center=None,
+                       robust=False, annot=False, fmt=".2f", annot_kws=None,
+                       cbar=True, cbar_kws=None, mask=None)
+
+    def test_ndarray_input(self):
+
+        p = mat._HeatMapper(self.x_norm, **self.default_kws)
+        npt.assert_array_equal(p.plot_data, self.x_norm)
+        pdt.assert_frame_equal(p.data, pd.DataFrame(self.x_norm))
+
+        npt.assert_array_equal(p.xticklabels, np.arange(8))
+        npt.assert_array_equal(p.yticklabels, np.arange(4))
+
+        assert p.xlabel == ""
+        assert p.ylabel == ""
+
+    def test_df_input(self):
+
+        p = mat._HeatMapper(self.df_norm, **self.default_kws)
+        npt.assert_array_equal(p.plot_data, self.x_norm)
+        pdt.assert_frame_equal(p.data, self.df_norm)
+
+        npt.assert_array_equal(p.xticklabels, np.arange(8))
+        npt.assert_array_equal(p.yticklabels, self.letters.values)
+
+        assert p.xlabel == ""
+        assert p.ylabel == "letters"
+
+    def test_df_multindex_input(self):
+
+        df = self.df_norm.copy()
+        index = pd.MultiIndex.from_tuples([("A", 1), ("B", 2),
+                                           ("C", 3), ("D", 4)],
+                                          names=["letter", "number"])
+        index.name = "letter-number"
+        df.index = index
+
+        p = mat._HeatMapper(df, **self.default_kws)
+
+        combined_tick_labels = ["A-1", "B-2", "C-3", "D-4"]
+        npt.assert_array_equal(p.yticklabels, combined_tick_labels)
+        assert p.ylabel == "letter-number"
+
+        p = mat._HeatMapper(df.T, **self.default_kws)
+
+        npt.assert_array_equal(p.xticklabels, combined_tick_labels)
+        assert p.xlabel == "letter-number"
+
+    @pytest.mark.parametrize("dtype", [float, np.int64, object])
+    def test_mask_input(self, dtype):
+        kws = self.default_kws.copy()
+
+        mask = self.x_norm > 0
+        kws['mask'] = mask
+        data = self.x_norm.astype(dtype)
+        p = mat._HeatMapper(data, **kws)
+        plot_data = np.ma.masked_where(mask, data)
+
+        npt.assert_array_equal(p.plot_data, plot_data)
+
+    def test_mask_limits(self):
+        """Make sure masked cells are not used to calculate extremes"""
+
+        kws = self.default_kws.copy()
+
+        mask = self.x_norm > 0
+        kws['mask'] = mask
+        p = mat._HeatMapper(self.x_norm, **kws)
+
+        assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()
+        assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()
+
+        mask = self.x_norm < 0
+        kws['mask'] = mask
+        p = mat._HeatMapper(self.x_norm, **kws)
+
+        assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()
+        assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()
+
+    def test_default_vlims(self):
+
+        p = mat._HeatMapper(self.df_unif, **self.default_kws)
+        assert p.vmin == self.x_unif.min()
+        assert p.vmax == self.x_unif.max()
+
+    def test_robust_vlims(self):
+
+        kws = self.default_kws.copy()
+        kws["robust"] = True
+        p = mat._HeatMapper(self.df_unif, **kws)
+
+        assert p.vmin == np.percentile(self.x_unif, 2)
+        assert p.vmax == np.percentile(self.x_unif, 98)
+
+    def test_custom_sequential_vlims(self):
+
+        kws = self.default_kws.copy()
+        kws["vmin"] = 0
+        kws["vmax"] = 1
+        p = mat._HeatMapper(self.df_unif, **kws)
+
+        assert p.vmin == 0
+        assert p.vmax == 1
+
+    def test_custom_diverging_vlims(self):
+
+        kws = self.default_kws.copy()
+        kws["vmin"] = -4
+        kws["vmax"] = 5
+        kws["center"] = 0
+        p = mat._HeatMapper(self.df_norm, **kws)
+
+        assert p.vmin == -4
+        assert p.vmax == 5
+
+    def test_array_with_nans(self):
+
+        x1 = self.rs.rand(10, 10)
+        nulls = np.zeros(10) * np.nan
+        x2 = np.c_[x1, nulls]
+
+        m1 = mat._HeatMapper(x1, **self.default_kws)
+        m2 = mat._HeatMapper(x2, **self.default_kws)
+
+        assert m1.vmin == m2.vmin
+        assert m1.vmax == m2.vmax
+
+    def test_mask(self):
+
+        df = pd.DataFrame(data={'a': [1, 1, 1],
+                                'b': [2, np.nan, 2],
+                                'c': [3, 3, np.nan]})
+
+        kws = self.default_kws.copy()
+        kws["mask"] = np.isnan(df.values)
+
+        m = mat._HeatMapper(df, **kws)
+
+        npt.assert_array_equal(np.isnan(m.plot_data.data),
+                               m.plot_data.mask)
+
+    def test_custom_cmap(self):
+
+        kws = self.default_kws.copy()
+        kws["cmap"] = "BuGn"
+        p = mat._HeatMapper(self.df_unif, **kws)
+        assert p.cmap == mpl.cm.BuGn
+
+    def test_centered_vlims(self):
+
+        kws = self.default_kws.copy()
+        kws["center"] = .5
+
+        p = mat._HeatMapper(self.df_unif, **kws)
+
+        assert p.vmin == self.df_unif.values.min()
+        assert p.vmax == self.df_unif.values.max()
+
+    def test_default_colors(self):
+
+        vals = np.linspace(.2, 1, 9)
+        cmap = mpl.cm.binary
+        ax = mat.heatmap([vals], cmap=cmap)
+        fc = ax.collections[0].get_facecolors()
+        cvals = np.linspace(0, 1, 9)
+        npt.assert_array_almost_equal(fc, cmap(cvals), 2)
+
+    def test_custom_vlim_colors(self):
+
+        vals = np.linspace(.2, 1, 9)
+        cmap = mpl.cm.binary
+        ax = mat.heatmap([vals], vmin=0, cmap=cmap)
+        fc = ax.collections[0].get_facecolors()
+        npt.assert_array_almost_equal(fc, cmap(vals), 2)
+
+    def test_custom_center_colors(self):
+
+        vals = np.linspace(.2, 1, 9)
+        cmap = mpl.cm.binary
+        ax = mat.heatmap([vals], center=.5, cmap=cmap)
+        fc = ax.collections[0].get_facecolors()
+        npt.assert_array_almost_equal(fc, cmap(vals), 2)
+
+    def test_cmap_with_properties(self):
+
+        kws = self.default_kws.copy()
+        cmap = copy.copy(get_colormap("BrBG"))
+        cmap.set_bad("red")
+        kws["cmap"] = cmap
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(
+            cmap(np.ma.masked_invalid([np.nan])),
+            hm.cmap(np.ma.masked_invalid([np.nan])))
+
+        kws["center"] = 0.5
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(
+            cmap(np.ma.masked_invalid([np.nan])),
+            hm.cmap(np.ma.masked_invalid([np.nan])))
+
+        kws = self.default_kws.copy()
+        cmap = copy.copy(get_colormap("BrBG"))
+        cmap.set_under("red")
+        kws["cmap"] = cmap
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))
+
+        kws["center"] = .5
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))
+
+        kws = self.default_kws.copy()
+        cmap = copy.copy(get_colormap("BrBG"))
+        cmap.set_over("red")
+        kws["cmap"] = cmap
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))
+
+        kws["center"] = .5
+        hm = mat._HeatMapper(self.df_unif, **kws)
+        npt.assert_array_equal(cmap(np.inf), hm.cmap(np.inf))
+
+    def test_ticklabels_off(self):
+        kws = self.default_kws.copy()
+        kws['xticklabels'] = False
+        kws['yticklabels'] = False
+        p = mat._HeatMapper(self.df_norm, **kws)
+        assert p.xticklabels == []
+        assert p.yticklabels == []
+
+    def test_custom_ticklabels(self):
+        kws = self.default_kws.copy()
+        xticklabels = list('iheartheatmaps'[:self.df_norm.shape[1]])
+        yticklabels = list('heatmapsarecool'[:self.df_norm.shape[0]])
+        kws['xticklabels'] = xticklabels
+        kws['yticklabels'] = yticklabels
+        p = mat._HeatMapper(self.df_norm, **kws)
+        assert p.xticklabels == xticklabels
+        assert p.yticklabels == yticklabels
+
+    def test_custom_ticklabel_interval(self):
+
+        kws = self.default_kws.copy()
+        xstep, ystep = 2, 3
+        kws['xticklabels'] = xstep
+        kws['yticklabels'] = ystep
+        p = mat._HeatMapper(self.df_norm, **kws)
+
+        nx, ny = self.df_norm.T.shape
+        npt.assert_array_equal(p.xticks, np.arange(0, nx, xstep) + .5)
+        npt.assert_array_equal(p.yticks, np.arange(0, ny, ystep) + .5)
+        npt.assert_array_equal(p.xticklabels,
+                               self.df_norm.columns[0:nx:xstep])
+        npt.assert_array_equal(p.yticklabels,
+                               self.df_norm.index[0:ny:ystep])
+
+    def test_heatmap_annotation(self):
+
+        ax = mat.heatmap(self.df_norm, annot=True, fmt=".1f",
+                         annot_kws={"fontsize": 14})
+        for val, text in zip(self.x_norm.flat, ax.texts):
+            assert text.get_text() == f"{val:.1f}"
+            assert text.get_fontsize() == 14
+
+    def test_heatmap_annotation_overwrite_kws(self):
+
+        annot_kws = dict(color="0.3", va="bottom", ha="left")
+        ax = mat.heatmap(self.df_norm, annot=True, fmt=".1f",
+                         annot_kws=annot_kws)
+        for text in ax.texts:
+            assert text.get_color() == "0.3"
+            assert text.get_ha() == "left"
+            assert text.get_va() == "bottom"
+
+    def test_heatmap_annotation_with_mask(self):
+
+        df = pd.DataFrame(data={'a': [1, 1, 1],
+                                'b': [2, np.nan, 2],
+                                'c': [3, 3, np.nan]})
+        mask = np.isnan(df.values)
+        df_masked = np.ma.masked_where(mask, df)
+        ax = mat.heatmap(df, annot=True, fmt='.1f', mask=mask)
+        assert len(df_masked.compressed()) == len(ax.texts)
+        for val, text in zip(df_masked.compressed(), ax.texts):
+            assert f"{val:.1f}" == text.get_text()
+
+    def test_heatmap_annotation_mesh_colors(self):
+
+        ax = mat.heatmap(self.df_norm, annot=True)
+        mesh = ax.collections[0]
+        assert len(mesh.get_facecolors()) == self.df_norm.values.size
+
+        plt.close("all")
+
+    def test_heatmap_annotation_other_data(self):
+        annot_data = self.df_norm + 10
+
+        ax = mat.heatmap(self.df_norm, annot=annot_data, fmt=".1f",
+                         annot_kws={"fontsize": 14})
+
+        for val, text in zip(annot_data.values.flat, ax.texts):
+            assert text.get_text() == f"{val:.1f}"
+            assert text.get_fontsize() == 14
+
+    def test_heatmap_annotation_different_shapes(self):
+
+        annot_data = self.df_norm.iloc[:-1]
+        with pytest.raises(ValueError):
+            mat.heatmap(self.df_norm, annot=annot_data)
+
+    def test_heatmap_annotation_with_limited_ticklabels(self):
+        ax = mat.heatmap(self.df_norm, fmt=".2f", annot=True,
+                         xticklabels=False, yticklabels=False)
+        for val, text in zip(self.x_norm.flat, ax.texts):
+            assert text.get_text() == f"{val:.2f}"
+
+    def test_heatmap_cbar(self):
+
+        f = plt.figure()
+        mat.heatmap(self.df_norm)
+        assert len(f.axes) == 2
+        plt.close(f)
+
+        f = plt.figure()
+        mat.heatmap(self.df_norm, cbar=False)
+        assert len(f.axes) == 1
+        plt.close(f)
+
+        f, (ax1, ax2) = plt.subplots(2)
+        mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2)
+        assert len(f.axes) == 2
+        plt.close(f)
+
+    @pytest.mark.xfail(mpl.__version__ == "3.1.1",
+                       reason="matplotlib 3.1.1 bug")
+    def test_heatmap_axes(self):
+
+        ax = mat.heatmap(self.df_norm)
+
+        xtl = [int(l.get_text()) for l in ax.get_xticklabels()]
+        assert xtl == list(self.df_norm.columns)
+        ytl = [l.get_text() for l in ax.get_yticklabels()]
+        assert ytl == list(self.df_norm.index)
+
+        assert ax.get_xlabel() == ""
+        assert ax.get_ylabel() == "letters"
+
+        assert ax.get_xlim() == (0, 8)
+        assert ax.get_ylim() == (4, 0)
+
+    def test_heatmap_ticklabel_rotation(self):
+
+        f, ax = plt.subplots(figsize=(2, 2))
+        mat.heatmap(self.df_norm, xticklabels=1, yticklabels=1, ax=ax)
+
+        for t in ax.get_xticklabels():
+            assert t.get_rotation() == 0
+
+        for t in ax.get_yticklabels():
+            assert t.get_rotation() == 90
+
+        plt.close(f)
+
+        df = self.df_norm.copy()
+        df.columns = [str(c) * 10 for c in df.columns]
+        df.index = [i * 10 for i in df.index]
+
+        f, ax = plt.subplots(figsize=(2, 2))
+        mat.heatmap(df, xticklabels=1, yticklabels=1, ax=ax)
+
+        for t in ax.get_xticklabels():
+            assert t.get_rotation() == 90
+
+        for t in ax.get_yticklabels():
+            assert t.get_rotation() == 0
+
+        plt.close(f)
+
+    def test_heatmap_inner_lines(self):
+
+        c = (0, 0, 1, 1)
+        ax = mat.heatmap(self.df_norm, linewidths=2, linecolor=c)
+        mesh = ax.collections[0]
+        assert mesh.get_linewidths()[0] == 2
+        assert tuple(mesh.get_edgecolor()[0]) == c
+
+    def test_square_aspect(self):
+
+        ax = mat.heatmap(self.df_norm, square=True)
+        obs_aspect = ax.get_aspect()
+        # mpl>3.3 returns 1 for setting "equal" aspect
+        # so test for the two possible equal outcomes
+        assert obs_aspect == "equal" or obs_aspect == 1
+
+    def test_mask_validation(self):
+
+        mask = mat._matrix_mask(self.df_norm, None)
+        assert mask.shape == self.df_norm.shape
+        assert mask.values.sum() == 0
+
+        with pytest.raises(ValueError):
+            bad_array_mask = self.rs.randn(3, 6) > 0
+            mat._matrix_mask(self.df_norm, bad_array_mask)
+
+        with pytest.raises(ValueError):
+            bad_df_mask = pd.DataFrame(self.rs.randn(4, 8) > 0)
+            mat._matrix_mask(self.df_norm, bad_df_mask)
+
+    def test_missing_data_mask(self):
+
+        data = pd.DataFrame(np.arange(4, dtype=float).reshape(2, 2))
+        data.loc[0, 0] = np.nan
+        mask = mat._matrix_mask(data, None)
+        npt.assert_array_equal(mask, [[True, False], [False, False]])
+
+        mask_in = np.array([[False, True], [False, False]])
+        mask_out = mat._matrix_mask(data, mask_in)
+        npt.assert_array_equal(mask_out, [[True, True], [False, False]])
+
+    def test_cbar_ticks(self):
+
+        f, (ax1, ax2) = plt.subplots(2)
+        mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2,
+                    cbar_kws=dict(drawedges=True))
+        assert len(ax2.collections) == 2
+
+
+@pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
+class TestDendrogram:
+
+    rs = np.random.RandomState(sum(map(ord, "dendrogram")))
+
+    default_kws = dict(linkage=None, metric='euclidean', method='single',
+                       axis=1, label=True, rotate=False)
+
+    x_norm = rs.randn(4, 8) + np.arange(8)
+    x_norm = (x_norm.T + np.arange(4)).T
+    letters = pd.Series(["A", "B", "C", "D", "E", "F", "G", "H"],
+                        name="letters")
+
+    df_norm = pd.DataFrame(x_norm, columns=letters)
+
+    if not _no_scipy:
+        if _no_fastcluster:
+            x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')
+            x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')
+        else:
+            x_norm_linkage = fastcluster.linkage_vector(x_norm.T,
+                                                        metric='euclidean',
+                                                        method='single')
+
+        x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,
+                                                 color_threshold=-np.inf)
+        x_norm_leaves = x_norm_dendrogram['leaves']
+        df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])
+
+    def test_ndarray_input(self):
+        p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)
+        npt.assert_array_equal(p.array.T, self.x_norm)
+        pdt.assert_frame_equal(p.data.T, pd.DataFrame(self.x_norm))
+
+        npt.assert_array_equal(p.linkage, self.x_norm_linkage)
+        assert p.dendrogram == self.x_norm_dendrogram
+
+        npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)
+
+        npt.assert_array_equal(p.xticklabels, self.x_norm_leaves)
+        npt.assert_array_equal(p.yticklabels, [])
+
+        assert p.xlabel is None
+        assert p.ylabel == ''
+
+    def test_df_input(self):
+        p = mat._DendrogramPlotter(self.df_norm, **self.default_kws)
+        npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))
+        pdt.assert_frame_equal(p.data.T, self.df_norm)
+
+        npt.assert_array_equal(p.linkage, self.x_norm_linkage)
+        assert p.dendrogram == self.x_norm_dendrogram
+
+        npt.assert_array_equal(p.xticklabels,
+                               np.asarray(self.df_norm.columns)[
+                                   self.x_norm_leaves])
+        npt.assert_array_equal(p.yticklabels, [])
+
+        assert p.xlabel == 'letters'
+        assert p.ylabel == ''
+
+    def test_df_multindex_input(self):
+
+        df = self.df_norm.copy()
+        index = pd.MultiIndex.from_tuples([("A", 1), ("B", 2),
+                                           ("C", 3), ("D", 4)],
+                                          names=["letter", "number"])
+        index.name = "letter-number"
+        df.index = index
+        kws = self.default_kws.copy()
+        kws['label'] = True
+
+        p = mat._DendrogramPlotter(df.T, **kws)
+
+        xticklabels = ["A-1", "B-2", "C-3", "D-4"]
+        xticklabels = [xticklabels[i] for i in p.reordered_ind]
+        npt.assert_array_equal(p.xticklabels, xticklabels)
+        npt.assert_array_equal(p.yticklabels, [])
+        assert p.xlabel == "letter-number"
+
+    def test_axis0_input(self):
+        kws = self.default_kws.copy()
+        kws['axis'] = 0
+        p = mat._DendrogramPlotter(self.df_norm.T, **kws)
+
+        npt.assert_array_equal(p.array, np.asarray(self.df_norm.T))
+        pdt.assert_frame_equal(p.data, self.df_norm.T)
+
+        npt.assert_array_equal(p.linkage, self.x_norm_linkage)
+        assert p.dendrogram == self.x_norm_dendrogram
+
+        npt.assert_array_equal(p.xticklabels, self.df_norm_leaves)
+        npt.assert_array_equal(p.yticklabels, [])
+
+        assert p.xlabel == 'letters'
+        assert p.ylabel == ''
+
+    def test_rotate_input(self):
+        kws = self.default_kws.copy()
+        kws['rotate'] = True
+        p = mat._DendrogramPlotter(self.df_norm, **kws)
+        npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))
+        pdt.assert_frame_equal(p.data.T, self.df_norm)
+
+        npt.assert_array_equal(p.xticklabels, [])
+        npt.assert_array_equal(p.yticklabels, self.df_norm_leaves)
+
+        assert p.xlabel == ''
+        assert p.ylabel == 'letters'
+
+    def test_rotate_axis0_input(self):
+        kws = self.default_kws.copy()
+        kws['rotate'] = True
+        kws['axis'] = 0
+        p = mat._DendrogramPlotter(self.df_norm.T, **kws)
+
+        npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)
+
+    def test_custom_linkage(self):
+        kws = self.default_kws.copy()
+
+        try:
+            import fastcluster
+
+            linkage = fastcluster.linkage_vector(self.x_norm, method='single',
+                                                 metric='euclidean')
+        except ImportError:
+            d = distance.pdist(self.x_norm, metric='euclidean')
+            linkage = hierarchy.linkage(d, method='single')
+        dendrogram = hierarchy.dendrogram(linkage, no_plot=True,
+                                          color_threshold=-np.inf)
+        kws['linkage'] = linkage
+        p = mat._DendrogramPlotter(self.df_norm, **kws)
+
+        npt.assert_array_equal(p.linkage, linkage)
+        assert p.dendrogram == dendrogram
+
+    def test_label_false(self):
+        kws = self.default_kws.copy()
+        kws['label'] = False
+        p = mat._DendrogramPlotter(self.df_norm, **kws)
+        assert p.xticks == []
+        assert p.yticks == []
+        assert p.xticklabels == []
+        assert p.yticklabels == []
+        assert p.xlabel == ""
+        assert p.ylabel == ""
+
+    def test_linkage_scipy(self):
+        p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)
+
+        scipy_linkage = p._calculate_linkage_scipy()
+
+        from scipy.spatial import distance
+        from scipy.cluster import hierarchy
+
+        dists = distance.pdist(self.x_norm.T,
+                               metric=self.default_kws['metric'])
+        linkage = hierarchy.linkage(dists, method=self.default_kws['method'])
+
+        npt.assert_array_equal(scipy_linkage, linkage)
+
+    @pytest.mark.skipif(_no_fastcluster, reason="fastcluster not installed")
+    def test_fastcluster_other_method(self):
+        import fastcluster
+
+        kws = self.default_kws.copy()
+        kws['method'] = 'average'
+        linkage = fastcluster.linkage(self.x_norm.T, method='average',
+                                      metric='euclidean')
+        p = mat._DendrogramPlotter(self.x_norm, **kws)
+        npt.assert_array_equal(p.linkage, linkage)
+
+    @pytest.mark.skipif(_no_fastcluster, reason="fastcluster not installed")
+    def test_fastcluster_non_euclidean(self):
+        import fastcluster
+
+        kws = self.default_kws.copy()
+        kws['metric'] = 'cosine'
+        kws['method'] = 'average'
+        linkage = fastcluster.linkage(self.x_norm.T, method=kws['method'],
+                                      metric=kws['metric'])
+        p = mat._DendrogramPlotter(self.x_norm, **kws)
+        npt.assert_array_equal(p.linkage, linkage)
+
+    def test_dendrogram_plot(self):
+        d = mat.dendrogram(self.x_norm, **self.default_kws)
+
+        ax = plt.gca()
+        xlim = ax.get_xlim()
+        # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy
+        xmax = len(d.reordered_ind) * 10
+
+        assert xlim[0] == 0
+        assert xlim[1] == xmax
+
+        assert len(ax.collections[0].get_paths()) == len(d.dependent_coord)
+
+    @pytest.mark.xfail(mpl.__version__ == "3.1.1",
+                       reason="matplotlib 3.1.1 bug")
+    def test_dendrogram_rotate(self):
+        kws = self.default_kws.copy()
+        kws['rotate'] = True
+
+        d = mat.dendrogram(self.x_norm, **kws)
+
+        ax = plt.gca()
+        ylim = ax.get_ylim()
+
+        # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy
+        ymax = len(d.reordered_ind) * 10
+
+        # Since y axis is inverted, ylim is (80, 0)
+        # and therefore not (0, 80) as usual:
+        assert ylim[1] == 0
+        assert ylim[0] == ymax
+
+    def test_dendrogram_ticklabel_rotation(self):
+        f, ax = plt.subplots(figsize=(2, 2))
+        mat.dendrogram(self.df_norm, ax=ax)
+
+        for t in ax.get_xticklabels():
+            assert t.get_rotation() == 0
+
+        plt.close(f)
+
+        df = self.df_norm.copy()
+        df.columns = [str(c) * 10 for c in df.columns]
+        df.index = [i * 10 for i in df.index]
+
+        f, ax = plt.subplots(figsize=(2, 2))
+        mat.dendrogram(df, ax=ax)
+
+        for t in ax.get_xticklabels():
+            assert t.get_rotation() == 90
+
+        plt.close(f)
+
+        f, ax = plt.subplots(figsize=(2, 2))
+        mat.dendrogram(df.T, axis=0, rotate=True)
+        for t in ax.get_yticklabels():
+            assert t.get_rotation() == 0
+        plt.close(f)
+
+
+@pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
+class TestClustermap:
+
+    rs = np.random.RandomState(sum(map(ord, "clustermap")))
+
+    x_norm = rs.randn(4, 8) + np.arange(8)
+    x_norm = (x_norm.T + np.arange(4)).T
+    letters = pd.Series(["A", "B", "C", "D", "E", "F", "G", "H"],
+                        name="letters")
+
+    df_norm = pd.DataFrame(x_norm, columns=letters)
+
+    default_kws = dict(pivot_kws=None, z_score=None, standard_scale=None,
+                       figsize=(10, 10), row_colors=None, col_colors=None,
+                       dendrogram_ratio=.2, colors_ratio=.03,
+                       cbar_pos=(0, .8, .05, .2))
+
+    default_plot_kws = dict(metric='euclidean', method='average',
+                            colorbar_kws=None,
+                            row_cluster=True, col_cluster=True,
+                            row_linkage=None, col_linkage=None,
+                            tree_kws=None)
+
+    row_colors = color_palette('Set2', df_norm.shape[0])
+    col_colors = color_palette('Dark2', df_norm.shape[1])
+
+    if not _no_scipy:
+        if _no_fastcluster:
+            x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')
+            x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')
+        else:
+            x_norm_linkage = fastcluster.linkage_vector(x_norm.T,
+                                                        metric='euclidean',
+                                                        method='single')
+
+        x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,
+                                                 color_threshold=-np.inf)
+        x_norm_leaves = x_norm_dendrogram['leaves']
+        df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])
+
+    def test_ndarray_input(self):
+        cg = mat.ClusterGrid(self.x_norm, **self.default_kws)
+        pdt.assert_frame_equal(cg.data, pd.DataFrame(self.x_norm))
+        assert len(cg.fig.axes) == 4
+        assert cg.ax_row_colors is None
+        assert cg.ax_col_colors is None
+
+    def test_df_input(self):
+        cg = mat.ClusterGrid(self.df_norm, **self.default_kws)
+        pdt.assert_frame_equal(cg.data, self.df_norm)
+
+    def test_corr_df_input(self):
+        df = self.df_norm.corr()
+        cg = mat.ClusterGrid(df, **self.default_kws)
+        cg.plot(**self.default_plot_kws)
+        diag = cg.data2d.values[np.diag_indices_from(cg.data2d)]
+        npt.assert_array_almost_equal(diag, np.ones(cg.data2d.shape[0]))
+
+    def test_pivot_input(self):
+        df_norm = self.df_norm.copy()
+        df_norm.index.name = 'numbers'
+        df_long = pd.melt(df_norm.reset_index(), var_name='letters',
+                          id_vars='numbers')
+        kws = self.default_kws.copy()
+        kws['pivot_kws'] = dict(index='numbers', columns='letters',
+                                values='value')
+        cg = mat.ClusterGrid(df_long, **kws)
+
+        pdt.assert_frame_equal(cg.data2d, df_norm)
+
+    def test_colors_input(self):
+        kws = self.default_kws.copy()
+
+        kws['row_colors'] = self.row_colors
+        kws['col_colors'] = self.col_colors
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        npt.assert_array_equal(cg.row_colors, self.row_colors)
+        npt.assert_array_equal(cg.col_colors, self.col_colors)
+
+        assert len(cg.fig.axes) == 6
+
+    def test_categorical_colors_input(self):
+        kws = self.default_kws.copy()
+
+        row_colors = pd.Series(self.row_colors, dtype="category")
+        col_colors = pd.Series(
+            self.col_colors, dtype="category", index=self.df_norm.columns
+        )
+
+        kws['row_colors'] = row_colors
+        kws['col_colors'] = col_colors
+
+        exp_row_colors = list(map(mpl.colors.to_rgb, row_colors))
+        exp_col_colors = list(map(mpl.colors.to_rgb, col_colors))
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        npt.assert_array_equal(cg.row_colors, exp_row_colors)
+        npt.assert_array_equal(cg.col_colors, exp_col_colors)
+
+        assert len(cg.fig.axes) == 6
+
+    def test_nested_colors_input(self):
+        kws = self.default_kws.copy()
+
+        row_colors = [self.row_colors, self.row_colors]
+        col_colors = [self.col_colors, self.col_colors]
+        kws['row_colors'] = row_colors
+        kws['col_colors'] = col_colors
+
+        cm = mat.ClusterGrid(self.df_norm, **kws)
+        npt.assert_array_equal(cm.row_colors, row_colors)
+        npt.assert_array_equal(cm.col_colors, col_colors)
+
+        assert len(cm.fig.axes) == 6
+
+    def test_colors_input_custom_cmap(self):
+        kws = self.default_kws.copy()
+
+        kws['cmap'] = mpl.cm.PRGn
+        kws['row_colors'] = self.row_colors
+        kws['col_colors'] = self.col_colors
+
+        cg = mat.clustermap(self.df_norm, **kws)
+        npt.assert_array_equal(cg.row_colors, self.row_colors)
+        npt.assert_array_equal(cg.col_colors, self.col_colors)
+
+        assert len(cg.fig.axes) == 6
+
+    def test_z_score(self):
+        df = self.df_norm.copy()
+        df = (df - df.mean()) / df.std()
+        kws = self.default_kws.copy()
+        kws['z_score'] = 1
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        pdt.assert_frame_equal(cg.data2d, df)
+
+    def test_z_score_axis0(self):
+        df = self.df_norm.copy()
+        df = df.T
+        df = (df - df.mean()) / df.std()
+        df = df.T
+        kws = self.default_kws.copy()
+        kws['z_score'] = 0
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        pdt.assert_frame_equal(cg.data2d, df)
+
+    def test_standard_scale(self):
+        df = self.df_norm.copy()
+        df = (df - df.min()) / (df.max() - df.min())
+        kws = self.default_kws.copy()
+        kws['standard_scale'] = 1
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        pdt.assert_frame_equal(cg.data2d, df)
+
+    def test_standard_scale_axis0(self):
+        df = self.df_norm.copy()
+        df = df.T
+        df = (df - df.min()) / (df.max() - df.min())
+        df = df.T
+        kws = self.default_kws.copy()
+        kws['standard_scale'] = 0
+
+        cg = mat.ClusterGrid(self.df_norm, **kws)
+        pdt.assert_frame_equal(cg.data2d, df)
+
+    def test_z_score_standard_scale(self):
+        kws = self.default_kws.copy()
+        kws['z_score'] = True
+        kws['standard_scale'] = True
+        with pytest.raises(ValueError):
+            mat.ClusterGrid(self.df_norm, **kws)
+
+    def test_color_list_to_matrix_and_cmap(self):
+        # Note this uses the attribute named col_colors but tests row colors
+        matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
+            self.col_colors, self.x_norm_leaves, axis=0)
+
+        for i, leaf in enumerate(self.x_norm_leaves):
+            color = self.col_colors[leaf]
+            assert_colors_equal(cmap(matrix[i, 0]), color)
+
+    def test_nested_color_list_to_matrix_and_cmap(self):
+        # Note this uses the attribute named col_colors but tests row colors
+        colors = [self.col_colors, self.col_colors[::-1]]
+        matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
+            colors, self.x_norm_leaves, axis=0)
+
+        for i, leaf in enumerate(self.x_norm_leaves):
+            for j, color_row in enumerate(colors):
+                color = color_row[leaf]
+                assert_colors_equal(cmap(matrix[i, j]), color)
+
+    def test_color_list_to_matrix_and_cmap_axis1(self):
+        matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
+            self.col_colors, self.x_norm_leaves, axis=1)
+
+        for j, leaf in enumerate(self.x_norm_leaves):
+            color = self.col_colors[leaf]
+            assert_colors_equal(cmap(matrix[0, j]), color)
+
+    def test_color_list_to_matrix_and_cmap_different_sizes(self):
+        colors = [self.col_colors, self.col_colors * 2]
+        with pytest.raises(ValueError):
+            matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
+                colors, self.x_norm_leaves, axis=1)
+
+    def test_savefig(self):
+        # Not sure if this is the right way to test....
+        cg = mat.ClusterGrid(self.df_norm, **self.default_kws)
+        cg.plot(**self.default_plot_kws)
+        cg.savefig(tempfile.NamedTemporaryFile(), format='png')
+
+    def test_plot_dendrograms(self):
+        cm = mat.clustermap(self.df_norm, **self.default_kws)
+
+        assert len(cm.ax_row_dendrogram.collections[0].get_paths()) == len(
+            cm.dendrogram_row.independent_coord
+        )
+        assert len(cm.ax_col_dendrogram.collections[0].get_paths()) == len(
+            cm.dendrogram_col.independent_coord
+        )
+        data2d = self.df_norm.iloc[cm.dendrogram_row.reordered_ind,
+                                   cm.dendrogram_col.reordered_ind]
+        pdt.assert_frame_equal(cm.data2d, data2d)
+
+    def test_cluster_false(self):
+        kws = self.default_kws.copy()
+        kws['row_cluster'] = False
+        kws['col_cluster'] = False
+
+        cm = mat.clustermap(self.df_norm, **kws)
+        assert len(cm.ax_row_dendrogram.lines) == 0
+        assert len(cm.ax_col_dendrogram.lines) == 0
+
+        assert len(cm.ax_row_dendrogram.get_xticks()) == 0
+        assert len(cm.ax_row_dendrogram.get_yticks()) == 0
+        assert len(cm.ax_col_dendrogram.get_xticks()) == 0
+        assert len(cm.ax_col_dendrogram.get_yticks()) == 0
+
+        pdt.assert_frame_equal(cm.data2d, self.df_norm)
+
+    def test_row_col_colors(self):
+        kws = self.default_kws.copy()
+        kws['row_colors'] = self.row_colors
+        kws['col_colors'] = self.col_colors
+
+        cm = mat.clustermap(self.df_norm, **kws)
+
+        assert len(cm.ax_row_colors.collections) == 1
+        assert len(cm.ax_col_colors.collections) == 1
+
+    def test_cluster_false_row_col_colors(self):
+        kws = self.default_kws.copy()
+        kws['row_cluster'] = False
+        kws['col_cluster'] = False
+        kws['row_colors'] = self.row_colors
+        kws['col_colors'] = self.col_colors
+
+        cm = mat.clustermap(self.df_norm, **kws)
+        assert len(cm.ax_row_dendrogram.lines) == 0
+        assert len(cm.ax_col_dendrogram.lines) == 0
+
+        assert len(cm.ax_row_dendrogram.get_xticks()) == 0
+        assert len(cm.ax_row_dendrogram.get_yticks()) == 0
+        assert len(cm.ax_col_dendrogram.get_xticks()) == 0
+        assert len(cm.ax_col_dendrogram.get_yticks()) == 0
+        assert len(cm.ax_row_colors.collections) == 1
+        assert len(cm.ax_col_colors.collections) == 1
+
+        pdt.assert_frame_equal(cm.data2d, self.df_norm)
+
+    def test_row_col_colors_df(self):
+        kws = self.default_kws.copy()
+        kws['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),
+                                          'row_2': list(self.row_colors)},
+                                         index=self.df_norm.index,
+                                         columns=['row_1', 'row_2'])
+        kws['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),
+                                          'col_2': list(self.col_colors)},
+                                         index=self.df_norm.columns,
+                                         columns=['col_1', 'col_2'])
+
+        cm = mat.clustermap(self.df_norm, **kws)
+
+        row_labels = [l.get_text() for l in
+                      cm.ax_row_colors.get_xticklabels()]
+        assert cm.row_color_labels == ['row_1', 'row_2']
+        assert row_labels == cm.row_color_labels
+
+        col_labels = [l.get_text() for l in
+                      cm.ax_col_colors.get_yticklabels()]
+        assert cm.col_color_labels == ['col_1', 'col_2']
+        assert col_labels == cm.col_color_labels
+
+    def test_row_col_colors_df_shuffled(self):
+        # Tests if colors are properly matched, even if given in wrong order
+
+        m, n = self.df_norm.shape
+        shuffled_inds = [self.df_norm.index[i] for i in
+                         list(range(0, m, 2)) + list(range(1, m, 2))]
+        shuffled_cols = [self.df_norm.columns[i] for i in
+                         list(range(0, n, 2)) + list(range(1, n, 2))]
+
+        kws = self.default_kws.copy()
+
+        row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},
+                                  index=self.df_norm.index)
+        kws['row_colors'] = row_colors.loc[shuffled_inds]
+
+        col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},
+                                  index=self.df_norm.columns)
+        kws['col_colors'] = col_colors.loc[shuffled_cols]
+
+        cm = mat.clustermap(self.df_norm, **kws)
+        assert list(cm.col_colors)[0] == list(self.col_colors)
+        assert list(cm.row_colors)[0] == list(self.row_colors)
+
+    def test_row_col_colors_df_missing(self):
+        kws = self.default_kws.copy()
+        row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},
+                                  index=self.df_norm.index)
+        kws['row_colors'] = row_colors.drop(self.df_norm.index[0])
+
+        col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},
+                                  index=self.df_norm.columns)
+        kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])
+
+        cm = mat.clustermap(self.df_norm, **kws)
+
+        assert list(cm.col_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])
+        assert list(cm.row_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])
+
+    def test_row_col_colors_df_one_axis(self):
+        # Test case with only row annotation.
+        kws1 = self.default_kws.copy()
+        kws1['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),
+                                           'row_2': list(self.row_colors)},
+                                          index=self.df_norm.index,
+                                          columns=['row_1', 'row_2'])
+
+        cm1 = mat.clustermap(self.df_norm, **kws1)
+
+        row_labels = [l.get_text() for l in
+                      cm1.ax_row_colors.get_xticklabels()]
+        assert cm1.row_color_labels == ['row_1', 'row_2']
+        assert row_labels == cm1.row_color_labels
+
+        # Test case with only col annotation.
+        kws2 = self.default_kws.copy()
+        kws2['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),
+                                           'col_2': list(self.col_colors)},
+                                          index=self.df_norm.columns,
+                                          columns=['col_1', 'col_2'])
+
+        cm2 = mat.clustermap(self.df_norm, **kws2)
+
+        col_labels = [l.get_text() for l in
+                      cm2.ax_col_colors.get_yticklabels()]
+        assert cm2.col_color_labels == ['col_1', 'col_2']
+        assert col_labels == cm2.col_color_labels
+
+    def test_row_col_colors_series(self):
+        kws = self.default_kws.copy()
+        kws['row_colors'] = pd.Series(list(self.row_colors), name='row_annot',
+                                      index=self.df_norm.index)
+        kws['col_colors'] = pd.Series(list(self.col_colors), name='col_annot',
+                                      index=self.df_norm.columns)
+
+        cm = mat.clustermap(self.df_norm, **kws)
+
+        row_labels = [l.get_text() for l in cm.ax_row_colors.get_xticklabels()]
+        assert cm.row_color_labels == ['row_annot']
+        assert row_labels == cm.row_color_labels
+
+        col_labels = [l.get_text() for l in cm.ax_col_colors.get_yticklabels()]
+        assert cm.col_color_labels == ['col_annot']
+        assert col_labels == cm.col_color_labels
+
+    def test_row_col_colors_series_shuffled(self):
+        # Tests if colors are properly matched, even if given in wrong order
+
+        m, n = self.df_norm.shape
+        shuffled_inds = [self.df_norm.index[i] for i in
+                         list(range(0, m, 2)) + list(range(1, m, 2))]
+        shuffled_cols = [self.df_norm.columns[i] for i in
+                         list(range(0, n, 2)) + list(range(1, n, 2))]
+
+        kws = self.default_kws.copy()
+
+        row_colors = pd.Series(list(self.row_colors), name='row_annot',
+                               index=self.df_norm.index)
+        kws['row_colors'] = row_colors.loc[shuffled_inds]
+
+        col_colors = pd.Series(list(self.col_colors), name='col_annot',
+                               index=self.df_norm.columns)
+        kws['col_colors'] = col_colors.loc[shuffled_cols]
+
+        cm = mat.clustermap(self.df_norm, **kws)
+
+        assert list(cm.col_colors) == list(self.col_colors)
+        assert list(cm.row_colors) == list(self.row_colors)
+
+    def test_row_col_colors_series_missing(self):
+        kws = self.default_kws.copy()
+        row_colors = pd.Series(list(self.row_colors), name='row_annot',
+                               index=self.df_norm.index)
+        kws['row_colors'] = row_colors.drop(self.df_norm.index[0])
+
+        col_colors = pd.Series(list(self.col_colors), name='col_annot',
+                               index=self.df_norm.columns)
+        kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])
+
+        cm = mat.clustermap(self.df_norm, **kws)
+        assert list(cm.col_colors) == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])
+        assert list(cm.row_colors) == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])
+
+    def test_row_col_colors_ignore_heatmap_kwargs(self):
+
+        g = mat.clustermap(self.rs.uniform(0, 200, self.df_norm.shape),
+                           row_colors=self.row_colors,
+                           col_colors=self.col_colors,
+                           cmap="Spectral",
+                           norm=mpl.colors.LogNorm(),
+                           vmax=100)
+
+        assert np.array_equal(
+            np.array(self.row_colors)[g.dendrogram_row.reordered_ind],
+            g.ax_row_colors.collections[0].get_facecolors()[:, :3]
+        )
+
+        assert np.array_equal(
+            np.array(self.col_colors)[g.dendrogram_col.reordered_ind],
+            g.ax_col_colors.collections[0].get_facecolors()[:, :3]
+        )
+
+    def test_row_col_colors_raise_on_mixed_index_types(self):
+
+        row_colors = pd.Series(
+            list(self.row_colors), name="row_annot", index=self.df_norm.index
+        )
+
+        col_colors = pd.Series(
+            list(self.col_colors), name="col_annot", index=self.df_norm.columns
+        )
+
+        with pytest.raises(TypeError):
+            mat.clustermap(self.x_norm, row_colors=row_colors)
+
+        with pytest.raises(TypeError):
+            mat.clustermap(self.x_norm, col_colors=col_colors)
+
+    def test_mask_reorganization(self):
+
+        kws = self.default_kws.copy()
+        kws["mask"] = self.df_norm > 0
+
+        g = mat.clustermap(self.df_norm, **kws)
+        npt.assert_array_equal(g.data2d.index, g.mask.index)
+        npt.assert_array_equal(g.data2d.columns, g.mask.columns)
+
+        npt.assert_array_equal(g.mask.index,
+                               self.df_norm.index[
+                                   g.dendrogram_row.reordered_ind])
+        npt.assert_array_equal(g.mask.columns,
+                               self.df_norm.columns[
+                                   g.dendrogram_col.reordered_ind])
+
+    def test_ticklabel_reorganization(self):
+
+        kws = self.default_kws.copy()
+        xtl = np.arange(self.df_norm.shape[1])
+        kws["xticklabels"] = list(xtl)
+        ytl = self.letters.loc[:self.df_norm.shape[0]]
+        kws["yticklabels"] = ytl
+
+        g = mat.clustermap(self.df_norm, **kws)
+
+        xtl_actual = [t.get_text() for t in g.ax_heatmap.get_xticklabels()]
+        ytl_actual = [t.get_text() for t in g.ax_heatmap.get_yticklabels()]
+
+        xtl_want = xtl[g.dendrogram_col.reordered_ind].astype(" g1.ax_col_dendrogram.get_position().height)
+
+        assert (g2.ax_col_colors.get_position().height
+                > g1.ax_col_colors.get_position().height)
+
+        assert (g2.ax_heatmap.get_position().height
+                < g1.ax_heatmap.get_position().height)
+
+        assert (g2.ax_row_dendrogram.get_position().width
+                > g1.ax_row_dendrogram.get_position().width)
+
+        assert (g2.ax_row_colors.get_position().width
+                > g1.ax_row_colors.get_position().width)
+
+        assert (g2.ax_heatmap.get_position().width
+                < g1.ax_heatmap.get_position().width)
+
+        kws1 = self.default_kws.copy()
+        kws1.update(col_colors=self.col_colors)
+        kws2 = kws1.copy()
+        kws2.update(col_colors=[self.col_colors, self.col_colors])
+
+        g1 = mat.clustermap(self.df_norm, **kws1)
+        g2 = mat.clustermap(self.df_norm, **kws2)
+
+        assert (g2.ax_col_colors.get_position().height
+                > g1.ax_col_colors.get_position().height)
+
+        kws1 = self.default_kws.copy()
+        kws1.update(dendrogram_ratio=(.2, .2))
+
+        kws2 = kws1.copy()
+        kws2.update(dendrogram_ratio=(.2, .3))
+
+        g1 = mat.clustermap(self.df_norm, **kws1)
+        g2 = mat.clustermap(self.df_norm, **kws2)
+
+        # Fails on pinned matplotlib?
+        # assert (g2.ax_row_dendrogram.get_position().width
+        #         == g1.ax_row_dendrogram.get_position().width)
+        assert g1.gs.get_width_ratios() == g2.gs.get_width_ratios()
+
+        assert (g2.ax_col_dendrogram.get_position().height
+                > g1.ax_col_dendrogram.get_position().height)
+
+    def test_cbar_pos(self):
+
+        kws = self.default_kws.copy()
+        kws["cbar_pos"] = (.2, .1, .4, .3)
+
+        g = mat.clustermap(self.df_norm, **kws)
+        pos = g.ax_cbar.get_position()
+        assert pytest.approx(tuple(pos.p0)) == kws["cbar_pos"][:2]
+        assert pytest.approx(pos.width) == kws["cbar_pos"][2]
+        assert pytest.approx(pos.height) == kws["cbar_pos"][3]
+
+        kws["cbar_pos"] = None
+        g = mat.clustermap(self.df_norm, **kws)
+        assert g.ax_cbar is None
+
+    def test_square_warning(self):
+
+        kws = self.default_kws.copy()
+        g1 = mat.clustermap(self.df_norm, **kws)
+
+        with pytest.warns(UserWarning):
+            kws["square"] = True
+            g2 = mat.clustermap(self.df_norm, **kws)
+
+        g1_shape = g1.ax_heatmap.get_position().get_points()
+        g2_shape = g2.ax_heatmap.get_position().get_points()
+        assert np.array_equal(g1_shape, g2_shape)
+
+    def test_clustermap_annotation(self):
+
+        g = mat.clustermap(self.df_norm, annot=True, fmt=".1f")
+        for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):
+            assert text.get_text() == f"{val:.1f}"
+
+        g = mat.clustermap(self.df_norm, annot=self.df_norm, fmt=".1f")
+        for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):
+            assert text.get_text() == f"{val:.1f}"
+
+    def test_tree_kws(self):
+
+        rgb = (1, .5, .2)
+        g = mat.clustermap(self.df_norm, tree_kws=dict(color=rgb))
+        for ax in [g.ax_col_dendrogram, g.ax_row_dendrogram]:
+            tree, = ax.collections
+            assert tuple(tree.get_color().squeeze())[:3] == rgb
+
+
+if _no_scipy:
+
+    def test_required_scipy_errors():
+
+        x = np.random.normal(0, 1, (10, 10))
+
+        with pytest.raises(RuntimeError):
+            mat.clustermap(x)
+
+        with pytest.raises(RuntimeError):
+            mat.ClusterGrid(x)
+
+        with pytest.raises(RuntimeError):
+            mat.dendrogram(x)
diff --git a/testbed/mwaskom__seaborn/tests/test_miscplot.py b/testbed/mwaskom__seaborn/tests/test_miscplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff51d0c04941c685066047d63671dfdc5a82b0b3
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_miscplot.py
@@ -0,0 +1,34 @@
+import matplotlib.pyplot as plt
+
+from seaborn import miscplot as misc
+from seaborn.palettes import color_palette
+from .test_utils import _network
+
+
+class TestPalPlot:
+    """Test the function that visualizes a color palette."""
+    def test_palplot_size(self):
+
+        pal4 = color_palette("husl", 4)
+        misc.palplot(pal4)
+        size4 = plt.gcf().get_size_inches()
+        assert tuple(size4) == (4, 1)
+
+        pal5 = color_palette("husl", 5)
+        misc.palplot(pal5)
+        size5 = plt.gcf().get_size_inches()
+        assert tuple(size5) == (5, 1)
+
+        palbig = color_palette("husl", 3)
+        misc.palplot(palbig, 2)
+        sizebig = plt.gcf().get_size_inches()
+        assert tuple(sizebig) == (6, 2)
+
+
+class TestDogPlot:
+
+    @_network(url="https://github.com/mwaskom/seaborn-data")
+    def test_dogplot(self):
+        misc.dogplot()
+        ax = plt.gca()
+        assert len(ax.images) == 1
diff --git a/testbed/mwaskom__seaborn/tests/test_objects.py b/testbed/mwaskom__seaborn/tests/test_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7f5b9f91a02dedc427a11872c750b5782ba2aa
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_objects.py
@@ -0,0 +1,14 @@
+import seaborn.objects
+from seaborn._core.plot import Plot
+from seaborn._core.moves import Move
+from seaborn._core.scales import Scale
+from seaborn._marks.base import Mark
+from seaborn._stats.base import Stat
+
+
+def test_objects_namespace():
+
+    for name in dir(seaborn.objects):
+        if not name.startswith("__"):
+            obj = getattr(seaborn.objects, name)
+            assert issubclass(obj, (Plot, Mark, Stat, Move, Scale))
diff --git a/testbed/mwaskom__seaborn/tests/test_palettes.py b/testbed/mwaskom__seaborn/tests/test_palettes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d9e9f916e68d6a3abc6e43a35e6431cc961560f
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_palettes.py
@@ -0,0 +1,439 @@
+import colorsys
+import numpy as np
+import matplotlib as mpl
+
+import pytest
+import numpy.testing as npt
+
+from seaborn import palettes, utils, rcmod
+from seaborn.external import husl
+from seaborn._compat import get_colormap
+from seaborn.colors import xkcd_rgb, crayons
+
+
+class TestColorPalettes:
+
+    def test_current_palette(self):
+
+        pal = palettes.color_palette(["red", "blue", "green"])
+        rcmod.set_palette(pal)
+        assert pal == utils.get_color_cycle()
+        rcmod.set()
+
+    def test_palette_context(self):
+
+        default_pal = palettes.color_palette()
+        context_pal = palettes.color_palette("muted")
+
+        with palettes.color_palette(context_pal):
+            assert utils.get_color_cycle() == context_pal
+
+        assert utils.get_color_cycle() == default_pal
+
+    def test_big_palette_context(self):
+
+        original_pal = palettes.color_palette("deep", n_colors=8)
+        context_pal = palettes.color_palette("husl", 10)
+
+        rcmod.set_palette(original_pal)
+        with palettes.color_palette(context_pal, 10):
+            assert utils.get_color_cycle() == context_pal
+
+        assert utils.get_color_cycle() == original_pal
+
+        # Reset default
+        rcmod.set()
+
+    def test_palette_size(self):
+
+        pal = palettes.color_palette("deep")
+        assert len(pal) == palettes.QUAL_PALETTE_SIZES["deep"]
+
+        pal = palettes.color_palette("pastel6")
+        assert len(pal) == palettes.QUAL_PALETTE_SIZES["pastel6"]
+
+        pal = palettes.color_palette("Set3")
+        assert len(pal) == palettes.QUAL_PALETTE_SIZES["Set3"]
+
+        pal = palettes.color_palette("husl")
+        assert len(pal) == 6
+
+        pal = palettes.color_palette("Greens")
+        assert len(pal) == 6
+
+    def test_seaborn_palettes(self):
+
+        pals = "deep", "muted", "pastel", "bright", "dark", "colorblind"
+        for name in pals:
+            full = palettes.color_palette(name, 10).as_hex()
+            short = palettes.color_palette(name + "6", 6).as_hex()
+            b, _, g, r, m, _, _, _, y, c = full
+            assert [b, g, r, m, y, c] == list(short)
+
+    def test_hls_palette(self):
+
+        pal1 = palettes.hls_palette()
+        pal2 = palettes.color_palette("hls")
+        npt.assert_array_equal(pal1, pal2)
+
+        cmap1 = palettes.hls_palette(as_cmap=True)
+        cmap2 = palettes.color_palette("hls", as_cmap=True)
+        npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))
+
+    def test_husl_palette(self):
+
+        pal1 = palettes.husl_palette()
+        pal2 = palettes.color_palette("husl")
+        npt.assert_array_equal(pal1, pal2)
+
+        cmap1 = palettes.husl_palette(as_cmap=True)
+        cmap2 = palettes.color_palette("husl", as_cmap=True)
+        npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))
+
+    def test_mpl_palette(self):
+
+        pal1 = palettes.mpl_palette("Reds")
+        pal2 = palettes.color_palette("Reds")
+        npt.assert_array_equal(pal1, pal2)
+
+        cmap1 = get_colormap("Reds")
+        cmap2 = palettes.mpl_palette("Reds", as_cmap=True)
+        cmap3 = palettes.color_palette("Reds", as_cmap=True)
+        npt.assert_array_equal(cmap1, cmap2)
+        npt.assert_array_equal(cmap1, cmap3)
+
+    def test_mpl_dark_palette(self):
+
+        mpl_pal1 = palettes.mpl_palette("Blues_d")
+        mpl_pal2 = palettes.color_palette("Blues_d")
+        npt.assert_array_equal(mpl_pal1, mpl_pal2)
+
+        mpl_pal1 = palettes.mpl_palette("Blues_r_d")
+        mpl_pal2 = palettes.color_palette("Blues_r_d")
+        npt.assert_array_equal(mpl_pal1, mpl_pal2)
+
+    def test_bad_palette_name(self):
+
+        with pytest.raises(ValueError):
+            palettes.color_palette("IAmNotAPalette")
+
+    def test_terrible_palette_name(self):
+
+        with pytest.raises(ValueError):
+            palettes.color_palette("jet")
+
+    def test_bad_palette_colors(self):
+
+        pal = ["red", "blue", "iamnotacolor"]
+        with pytest.raises(ValueError):
+            palettes.color_palette(pal)
+
+    def test_palette_desat(self):
+
+        pal1 = palettes.husl_palette(6)
+        pal1 = [utils.desaturate(c, .5) for c in pal1]
+        pal2 = palettes.color_palette("husl", desat=.5)
+        npt.assert_array_equal(pal1, pal2)
+
+    def test_palette_is_list_of_tuples(self):
+
+        pal_in = np.array(["red", "blue", "green"])
+        pal_out = palettes.color_palette(pal_in, 3)
+
+        assert isinstance(pal_out, list)
+        assert isinstance(pal_out[0], tuple)
+        assert isinstance(pal_out[0][0], float)
+        assert len(pal_out[0]) == 3
+
+    def test_palette_cycles(self):
+
+        deep = palettes.color_palette("deep6")
+        double_deep = palettes.color_palette("deep6", 12)
+        assert double_deep == deep + deep
+
+    def test_hls_values(self):
+
+        pal1 = palettes.hls_palette(6, h=0)
+        pal2 = palettes.hls_palette(6, h=.5)
+        pal2 = pal2[3:] + pal2[:3]
+        npt.assert_array_almost_equal(pal1, pal2)
+
+        pal_dark = palettes.hls_palette(5, l=.2)  # noqa
+        pal_bright = palettes.hls_palette(5, l=.8)  # noqa
+        npt.assert_array_less(list(map(sum, pal_dark)),
+                              list(map(sum, pal_bright)))
+
+        pal_flat = palettes.hls_palette(5, s=.1)
+        pal_bold = palettes.hls_palette(5, s=.9)
+        npt.assert_array_less(list(map(np.std, pal_flat)),
+                              list(map(np.std, pal_bold)))
+
+    def test_husl_values(self):
+
+        pal1 = palettes.husl_palette(6, h=0)
+        pal2 = palettes.husl_palette(6, h=.5)
+        pal2 = pal2[3:] + pal2[:3]
+        npt.assert_array_almost_equal(pal1, pal2)
+
+        pal_dark = palettes.husl_palette(5, l=.2)  # noqa
+        pal_bright = palettes.husl_palette(5, l=.8)  # noqa
+        npt.assert_array_less(list(map(sum, pal_dark)),
+                              list(map(sum, pal_bright)))
+
+        pal_flat = palettes.husl_palette(5, s=.1)
+        pal_bold = palettes.husl_palette(5, s=.9)
+        npt.assert_array_less(list(map(np.std, pal_flat)),
+                              list(map(np.std, pal_bold)))
+
+    def test_cbrewer_qual(self):
+
+        pal_short = palettes.mpl_palette("Set1", 4)
+        pal_long = palettes.mpl_palette("Set1", 6)
+        assert pal_short == pal_long[:4]
+
+        pal_full = palettes.mpl_palette("Set2", 8)
+        pal_long = palettes.mpl_palette("Set2", 10)
+        assert pal_full == pal_long[:8]
+
+    def test_mpl_reversal(self):
+
+        pal_forward = palettes.mpl_palette("BuPu", 6)
+        pal_reverse = palettes.mpl_palette("BuPu_r", 6)
+        npt.assert_array_almost_equal(pal_forward, pal_reverse[::-1])
+
+    def test_rgb_from_hls(self):
+
+        color = .5, .8, .4
+        rgb_got = palettes._color_to_rgb(color, "hls")
+        rgb_want = colorsys.hls_to_rgb(*color)
+        assert rgb_got == rgb_want
+
+    def test_rgb_from_husl(self):
+
+        color = 120, 50, 40
+        rgb_got = palettes._color_to_rgb(color, "husl")
+        rgb_want = tuple(husl.husl_to_rgb(*color))
+        assert rgb_got == rgb_want
+
+        for h in range(0, 360):
+            color = h, 100, 100
+            rgb = palettes._color_to_rgb(color, "husl")
+            assert min(rgb) >= 0
+            assert max(rgb) <= 1
+
+    def test_rgb_from_xkcd(self):
+
+        color = "dull red"
+        rgb_got = palettes._color_to_rgb(color, "xkcd")
+        rgb_want = mpl.colors.to_rgb(xkcd_rgb[color])
+        assert rgb_got == rgb_want
+
+    def test_light_palette(self):
+
+        n = 4
+        pal_forward = palettes.light_palette("red", n)
+        pal_reverse = palettes.light_palette("red", n, reverse=True)
+        assert np.allclose(pal_forward, pal_reverse[::-1])
+
+        red = mpl.colors.colorConverter.to_rgb("red")
+        assert pal_forward[-1] == red
+
+        pal_f_from_string = palettes.color_palette("light:red", n)
+        assert pal_forward[3] == pal_f_from_string[3]
+
+        pal_r_from_string = palettes.color_palette("light:red_r", n)
+        assert pal_reverse[3] == pal_r_from_string[3]
+
+        pal_cmap = palettes.light_palette("blue", as_cmap=True)
+        assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)
+
+        pal_cmap_from_string = palettes.color_palette("light:blue", as_cmap=True)
+        assert pal_cmap(.8) == pal_cmap_from_string(.8)
+
+        pal_cmap = palettes.light_palette("blue", as_cmap=True, reverse=True)
+        pal_cmap_from_string = palettes.color_palette("light:blue_r", as_cmap=True)
+        assert pal_cmap(.8) == pal_cmap_from_string(.8)
+
+    def test_dark_palette(self):
+
+        n = 4
+        pal_forward = palettes.dark_palette("red", n)
+        pal_reverse = palettes.dark_palette("red", n, reverse=True)
+        assert np.allclose(pal_forward, pal_reverse[::-1])
+
+        red = mpl.colors.colorConverter.to_rgb("red")
+        assert pal_forward[-1] == red
+
+        pal_f_from_string = palettes.color_palette("dark:red", n)
+        assert pal_forward[3] == pal_f_from_string[3]
+
+        pal_r_from_string = palettes.color_palette("dark:red_r", n)
+        assert pal_reverse[3] == pal_r_from_string[3]
+
+        pal_cmap = palettes.dark_palette("blue", as_cmap=True)
+        assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)
+
+        pal_cmap_from_string = palettes.color_palette("dark:blue", as_cmap=True)
+        assert pal_cmap(.8) == pal_cmap_from_string(.8)
+
+        pal_cmap = palettes.dark_palette("blue", as_cmap=True, reverse=True)
+        pal_cmap_from_string = palettes.color_palette("dark:blue_r", as_cmap=True)
+        assert pal_cmap(.8) == pal_cmap_from_string(.8)
+
+    def test_diverging_palette(self):
+
+        h_neg, h_pos = 100, 200
+        sat, lum = 70, 50
+        args = h_neg, h_pos, sat, lum
+
+        n = 12
+        pal = palettes.diverging_palette(*args, n=n)
+        neg_pal = palettes.light_palette((h_neg, sat, lum), int(n // 2),
+                                         input="husl")
+        pos_pal = palettes.light_palette((h_pos, sat, lum), int(n // 2),
+                                         input="husl")
+        assert len(pal) == n
+        assert pal[0] == neg_pal[-1]
+        assert pal[-1] == pos_pal[-1]
+
+        pal_dark = palettes.diverging_palette(*args, n=n, center="dark")
+        assert np.mean(pal[int(n / 2)]) > np.mean(pal_dark[int(n / 2)])
+
+        pal_cmap = palettes.diverging_palette(*args, as_cmap=True)
+        assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)
+
+    def test_blend_palette(self):
+
+        colors = ["red", "yellow", "white"]
+        pal_cmap = palettes.blend_palette(colors, as_cmap=True)
+        assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)
+
+        colors = ["red", "blue"]
+        pal = palettes.blend_palette(colors)
+        pal_str = "blend:" + ",".join(colors)
+        pal_from_str = palettes.color_palette(pal_str)
+        assert pal == pal_from_str
+
+    def test_cubehelix_against_matplotlib(self):
+
+        x = np.linspace(0, 1, 8)
+        mpl_pal = mpl.cm.cubehelix(x)[:, :3].tolist()
+
+        sns_pal = palettes.cubehelix_palette(8, start=0.5, rot=-1.5, hue=1,
+                                             dark=0, light=1, reverse=True)
+
+        assert sns_pal == mpl_pal
+
+    def test_cubehelix_n_colors(self):
+
+        for n in [3, 5, 8]:
+            pal = palettes.cubehelix_palette(n)
+            assert len(pal) == n
+
+    def test_cubehelix_reverse(self):
+
+        pal_forward = palettes.cubehelix_palette()
+        pal_reverse = palettes.cubehelix_palette(reverse=True)
+        assert pal_forward == pal_reverse[::-1]
+
+    def test_cubehelix_cmap(self):
+
+        cmap = palettes.cubehelix_palette(as_cmap=True)
+        assert isinstance(cmap, mpl.colors.ListedColormap)
+        pal = palettes.cubehelix_palette()
+        x = np.linspace(0, 1, 6)
+        npt.assert_array_equal(cmap(x)[:, :3], pal)
+
+        cmap_rev = palettes.cubehelix_palette(as_cmap=True, reverse=True)
+        x = np.linspace(0, 1, 6)
+        pal_forward = cmap(x).tolist()
+        pal_reverse = cmap_rev(x[::-1]).tolist()
+        assert pal_forward == pal_reverse
+
+    def test_cubehelix_code(self):
+
+        color_palette = palettes.color_palette
+        cubehelix_palette = palettes.cubehelix_palette
+
+        pal1 = color_palette("ch:", 8)
+        pal2 = color_palette(cubehelix_palette(8))
+        assert pal1 == pal2
+
+        pal1 = color_palette("ch:.5, -.25,hue = .5,light=.75", 8)
+        pal2 = color_palette(cubehelix_palette(8, .5, -.25, hue=.5, light=.75))
+        assert pal1 == pal2
+
+        pal1 = color_palette("ch:h=1,r=.5", 9)
+        pal2 = color_palette(cubehelix_palette(9, hue=1, rot=.5))
+        assert pal1 == pal2
+
+        pal1 = color_palette("ch:_r", 6)
+        pal2 = color_palette(cubehelix_palette(6, reverse=True))
+        assert pal1 == pal2
+
+        pal1 = color_palette("ch:_r", as_cmap=True)
+        pal2 = cubehelix_palette(6, reverse=True, as_cmap=True)
+        assert pal1(.5) == pal2(.5)
+
+    def test_xkcd_palette(self):
+
+        names = list(xkcd_rgb.keys())[10:15]
+        colors = palettes.xkcd_palette(names)
+        for name, color in zip(names, colors):
+            as_hex = mpl.colors.rgb2hex(color)
+            assert as_hex == xkcd_rgb[name]
+
+    def test_crayon_palette(self):
+
+        names = list(crayons.keys())[10:15]
+        colors = palettes.crayon_palette(names)
+        for name, color in zip(names, colors):
+            as_hex = mpl.colors.rgb2hex(color)
+            assert as_hex == crayons[name].lower()
+
+    def test_color_codes(self):
+
+        palettes.set_color_codes("deep")
+        colors = palettes.color_palette("deep6") + [".1"]
+        for code, color in zip("bgrmyck", colors):
+            rgb_want = mpl.colors.colorConverter.to_rgb(color)
+            rgb_got = mpl.colors.colorConverter.to_rgb(code)
+            assert rgb_want == rgb_got
+        palettes.set_color_codes("reset")
+
+        with pytest.raises(ValueError):
+            palettes.set_color_codes("Set1")
+
+    def test_as_hex(self):
+
+        pal = palettes.color_palette("deep")
+        for rgb, hex in zip(pal, pal.as_hex()):
+            assert mpl.colors.rgb2hex(rgb) == hex
+
+    def test_preserved_palette_length(self):
+
+        pal_in = palettes.color_palette("Set1", 10)
+        pal_out = palettes.color_palette(pal_in)
+        assert pal_in == pal_out
+
+    def test_html_repr(self):
+
+        pal = palettes.color_palette()
+        html = pal._repr_html_()
+        for color in pal.as_hex():
+            assert color in html
+
+    def test_colormap_display_patch(self):
+
+        orig_repr_png = getattr(mpl.colors.Colormap, "_repr_png_", None)
+        orig_repr_html = getattr(mpl.colors.Colormap, "_repr_html_", None)
+
+        try:
+            palettes._patch_colormap_display()
+            cmap = mpl.cm.Reds
+            assert cmap._repr_html_().startswith('Reds')
+        finally:
+            if orig_repr_png is not None:
+                mpl.colors.Colormap._repr_png_ = orig_repr_png
+            if orig_repr_html is not None:
+                mpl.colors.Colormap._repr_html_ = orig_repr_html
diff --git a/testbed/mwaskom__seaborn/tests/test_rcmod.py b/testbed/mwaskom__seaborn/tests/test_rcmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac3ff615f77759244ecb4e19e53f2274194ed5b9
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_rcmod.py
@@ -0,0 +1,311 @@
+import pytest
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+import numpy.testing as npt
+
+from seaborn import rcmod, palettes, utils
+
+
+def has_verdana():
+     yhat_log[0]
+        assert yhat_log[20] > yhat_lin[20]
+        assert yhat_lin[90] > yhat_log[90]
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_regress_n_boot(self):
+
+        p = lm._RegressionPlotter("x", "y", data=self.df, n_boot=self.n_boot)
+
+        # Fast (linear algebra) version
+        _, boots_fast = p.fit_fast(self.grid)
+        npt.assert_equal(boots_fast.shape, (self.n_boot, self.grid.size))
+
+        # Slower (np.polyfit) version
+        _, boots_poly = p.fit_poly(self.grid, 1)
+        npt.assert_equal(boots_poly.shape, (self.n_boot, self.grid.size))
+
+        # Slowest (statsmodels) version
+        _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)
+        npt.assert_equal(boots_smod.shape, (self.n_boot, self.grid.size))
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_regress_without_bootstrap(self):
+
+        p = lm._RegressionPlotter("x", "y", data=self.df,
+                                  n_boot=self.n_boot, ci=None)
+
+        # Fast (linear algebra) version
+        _, boots_fast = p.fit_fast(self.grid)
+        assert boots_fast is None
+
+        # Slower (np.polyfit) version
+        _, boots_poly = p.fit_poly(self.grid, 1)
+        assert boots_poly is None
+
+        # Slowest (statsmodels) version
+        _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)
+        assert boots_smod is None
+
+    def test_regress_bootstrap_seed(self):
+
+        seed = 200
+        p1 = lm._RegressionPlotter("x", "y", data=self.df,
+                                   n_boot=self.n_boot, seed=seed)
+        p2 = lm._RegressionPlotter("x", "y", data=self.df,
+                                   n_boot=self.n_boot, seed=seed)
+
+        _, boots1 = p1.fit_fast(self.grid)
+        _, boots2 = p2.fit_fast(self.grid)
+        npt.assert_array_equal(boots1, boots2)
+
+    def test_numeric_bins(self):
+
+        p = lm._RegressionPlotter(self.df.x, self.df.y)
+        x_binned, bins = p.bin_predictor(self.bins_numeric)
+        npt.assert_equal(len(bins), self.bins_numeric)
+        npt.assert_array_equal(np.unique(x_binned), bins)
+
+    def test_provided_bins(self):
+
+        p = lm._RegressionPlotter(self.df.x, self.df.y)
+        x_binned, bins = p.bin_predictor(self.bins_given)
+        npt.assert_array_equal(np.unique(x_binned), self.bins_given)
+
+    def test_bin_results(self):
+
+        p = lm._RegressionPlotter(self.df.x, self.df.y)
+        x_binned, bins = p.bin_predictor(self.bins_given)
+        assert self.df.x[x_binned == 0].min() > self.df.x[x_binned == -1].max()
+        assert self.df.x[x_binned == 1].min() > self.df.x[x_binned == 0].max()
+
+    def test_scatter_data(self):
+
+        p = lm._RegressionPlotter(self.df.x, self.df.y)
+        x, y = p.scatter_data
+        npt.assert_array_equal(x, self.df.x)
+        npt.assert_array_equal(y, self.df.y)
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y)
+        x, y = p.scatter_data
+        npt.assert_array_equal(x, self.df.d)
+        npt.assert_array_equal(y, self.df.y)
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y, x_jitter=.1)
+        x, y = p.scatter_data
+        assert (x != self.df.d).any()
+        npt.assert_array_less(np.abs(self.df.d - x), np.repeat(.1, len(x)))
+        npt.assert_array_equal(y, self.df.y)
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y, y_jitter=.05)
+        x, y = p.scatter_data
+        npt.assert_array_equal(x, self.df.d)
+        npt.assert_array_less(np.abs(self.df.y - y), np.repeat(.1, len(y)))
+
+    def test_estimate_data(self):
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y, x_estimator=np.mean)
+
+        x, y, ci = p.estimate_data
+
+        npt.assert_array_equal(x, np.sort(np.unique(self.df.d)))
+        npt.assert_array_almost_equal(y, self.df.groupby("d").y.mean())
+        npt.assert_array_less(np.array(ci)[:, 0], y)
+        npt.assert_array_less(y, np.array(ci)[:, 1])
+
+    def test_estimate_cis(self):
+
+        seed = 123
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y,
+                                  x_estimator=np.mean, ci=95, seed=seed)
+        _, _, ci_big = p.estimate_data
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y,
+                                  x_estimator=np.mean, ci=50, seed=seed)
+        _, _, ci_wee = p.estimate_data
+        npt.assert_array_less(np.diff(ci_wee), np.diff(ci_big))
+
+        p = lm._RegressionPlotter(self.df.d, self.df.y,
+                                  x_estimator=np.mean, ci=None)
+        _, _, ci_nil = p.estimate_data
+        npt.assert_array_equal(ci_nil, [None] * len(ci_nil))
+
+    def test_estimate_units(self):
+
+        # Seed the RNG locally
+        seed = 345
+
+        p = lm._RegressionPlotter("x", "y", data=self.df,
+                                  units="s", seed=seed, x_bins=3)
+        _, _, ci_big = p.estimate_data
+        ci_big = np.diff(ci_big, axis=1)
+
+        p = lm._RegressionPlotter("x", "y", data=self.df, seed=seed, x_bins=3)
+        _, _, ci_wee = p.estimate_data
+        ci_wee = np.diff(ci_wee, axis=1)
+
+        npt.assert_array_less(ci_wee, ci_big)
+
+    def test_partial(self):
+
+        x = self.rs.randn(100)
+        y = x + self.rs.randn(100)
+        z = x + self.rs.randn(100)
+
+        p = lm._RegressionPlotter(y, z)
+        _, r_orig = np.corrcoef(p.x, p.y)[0]
+
+        p = lm._RegressionPlotter(y, z, y_partial=x)
+        _, r_semipartial = np.corrcoef(p.x, p.y)[0]
+        assert r_semipartial < r_orig
+
+        p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)
+        _, r_partial = np.corrcoef(p.x, p.y)[0]
+        assert r_partial < r_orig
+
+        x = pd.Series(x)
+        y = pd.Series(y)
+        p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)
+        _, r_partial = np.corrcoef(p.x, p.y)[0]
+        assert r_partial < r_orig
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_logistic_regression(self):
+
+        p = lm._RegressionPlotter("x", "c", data=self.df,
+                                  logistic=True, n_boot=self.n_boot)
+        _, yhat, _ = p.fit_regression(x_range=(-3, 3))
+        npt.assert_array_less(yhat, 1)
+        npt.assert_array_less(0, yhat)
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_logistic_perfect_separation(self):
+
+        y = self.df.x > self.df.x.mean()
+        p = lm._RegressionPlotter("x", y, data=self.df,
+                                  logistic=True, n_boot=10)
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore", RuntimeWarning)
+            _, yhat, _ = p.fit_regression(x_range=(-3, 3))
+        assert np.isnan(yhat).all()
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_robust_regression(self):
+
+        p_ols = lm._RegressionPlotter("x", "y", data=self.df,
+                                      n_boot=self.n_boot)
+        _, ols_yhat, _ = p_ols.fit_regression(x_range=(-3, 3))
+
+        p_robust = lm._RegressionPlotter("x", "y", data=self.df,
+                                         robust=True, n_boot=self.n_boot)
+        _, robust_yhat, _ = p_robust.fit_regression(x_range=(-3, 3))
+
+        assert len(ols_yhat) == len(robust_yhat)
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_lowess_regression(self):
+
+        p = lm._RegressionPlotter("x", "y", data=self.df, lowess=True)
+        grid, yhat, err_bands = p.fit_regression(x_range=(-3, 3))
+
+        assert len(grid) == len(yhat)
+        assert err_bands is None
+
+    def test_regression_options(self):
+
+        with pytest.raises(ValueError):
+            lm._RegressionPlotter("x", "y", data=self.df,
+                                  lowess=True, order=2)
+
+        with pytest.raises(ValueError):
+            lm._RegressionPlotter("x", "y", data=self.df,
+                                  lowess=True, logistic=True)
+
+    def test_regression_limits(self):
+
+        f, ax = plt.subplots()
+        ax.scatter(self.df.x, self.df.y)
+        p = lm._RegressionPlotter("x", "y", data=self.df)
+        grid, _, _ = p.fit_regression(ax)
+        xlim = ax.get_xlim()
+        assert grid.min() == xlim[0]
+        assert grid.max() == xlim[1]
+
+        p = lm._RegressionPlotter("x", "y", data=self.df, truncate=True)
+        grid, _, _ = p.fit_regression()
+        assert grid.min() == self.df.x.min()
+        assert grid.max() == self.df.x.max()
+
+
+class TestRegressionPlots:
+
+    rs = np.random.RandomState(56)
+    df = pd.DataFrame(dict(x=rs.randn(90),
+                           y=rs.randn(90) + 5,
+                           z=rs.randint(0, 1, 90),
+                           g=np.repeat(list("abc"), 30),
+                           h=np.tile(list("xy"), 45),
+                           u=np.tile(np.arange(6), 15)))
+    bw_err = rs.randn(6)[df.u.values]
+    df.y += bw_err
+
+    def test_regplot_basic(self):
+
+        f, ax = plt.subplots()
+        lm.regplot(x="x", y="y", data=self.df)
+        assert len(ax.lines) == 1
+        assert len(ax.collections) == 2
+
+        x, y = ax.collections[0].get_offsets().T
+        npt.assert_array_equal(x, self.df.x)
+        npt.assert_array_equal(y, self.df.y)
+
+    def test_regplot_selective(self):
+
+        f, ax = plt.subplots()
+        ax = lm.regplot(x="x", y="y", data=self.df, scatter=False, ax=ax)
+        assert len(ax.lines) == 1
+        assert len(ax.collections) == 1
+        ax.clear()
+
+        f, ax = plt.subplots()
+        ax = lm.regplot(x="x", y="y", data=self.df, fit_reg=False)
+        assert len(ax.lines) == 0
+        assert len(ax.collections) == 1
+        ax.clear()
+
+        f, ax = plt.subplots()
+        ax = lm.regplot(x="x", y="y", data=self.df, ci=None)
+        assert len(ax.lines) == 1
+        assert len(ax.collections) == 1
+        ax.clear()
+
+    def test_regplot_scatter_kws_alpha(self):
+
+        f, ax = plt.subplots()
+        color = np.array([[0.3, 0.8, 0.5, 0.5]])
+        ax = lm.regplot(x="x", y="y", data=self.df,
+                        scatter_kws={'color': color})
+        assert ax.collections[0]._alpha is None
+        assert ax.collections[0]._facecolors[0, 3] == 0.5
+
+        f, ax = plt.subplots()
+        color = np.array([[0.3, 0.8, 0.5]])
+        ax = lm.regplot(x="x", y="y", data=self.df,
+                        scatter_kws={'color': color})
+        assert ax.collections[0]._alpha == 0.8
+
+        f, ax = plt.subplots()
+        color = np.array([[0.3, 0.8, 0.5]])
+        ax = lm.regplot(x="x", y="y", data=self.df,
+                        scatter_kws={'color': color, 'alpha': 0.4})
+        assert ax.collections[0]._alpha == 0.4
+
+        f, ax = plt.subplots()
+        color = 'r'
+        ax = lm.regplot(x="x", y="y", data=self.df,
+                        scatter_kws={'color': color})
+        assert ax.collections[0]._alpha == 0.8
+
+        f, ax = plt.subplots()
+        alpha = .3
+        ax = lm.regplot(x="x", y="y", data=self.df,
+                        x_bins=5, fit_reg=False,
+                        scatter_kws={"alpha": alpha})
+        for line in ax.lines:
+            assert line.get_alpha() == alpha
+
+    def test_regplot_binned(self):
+
+        ax = lm.regplot(x="x", y="y", data=self.df, x_bins=5)
+        assert len(ax.lines) == 6
+        assert len(ax.collections) == 2
+
+    def test_lmplot_no_data(self):
+
+        with pytest.raises(TypeError):
+            # keyword argument `data` is required
+            lm.lmplot(x="x", y="y")
+
+    def test_lmplot_basic(self):
+
+        g = lm.lmplot(x="x", y="y", data=self.df)
+        ax = g.axes[0, 0]
+        assert len(ax.lines) == 1
+        assert len(ax.collections) == 2
+
+        x, y = ax.collections[0].get_offsets().T
+        npt.assert_array_equal(x, self.df.x)
+        npt.assert_array_equal(y, self.df.y)
+
+    def test_lmplot_hue(self):
+
+        g = lm.lmplot(x="x", y="y", data=self.df, hue="h")
+        ax = g.axes[0, 0]
+
+        assert len(ax.lines) == 2
+        assert len(ax.collections) == 4
+
+    def test_lmplot_markers(self):
+
+        g1 = lm.lmplot(x="x", y="y", data=self.df, hue="h", markers="s")
+        assert g1.hue_kws == {"marker": ["s", "s"]}
+
+        g2 = lm.lmplot(x="x", y="y", data=self.df, hue="h", markers=["o", "s"])
+        assert g2.hue_kws == {"marker": ["o", "s"]}
+
+        with pytest.raises(ValueError):
+            lm.lmplot(x="x", y="y", data=self.df, hue="h",
+                      markers=["o", "s", "d"])
+
+    def test_lmplot_marker_linewidths(self):
+
+        g = lm.lmplot(x="x", y="y", data=self.df, hue="h",
+                      fit_reg=False, markers=["o", "+"])
+        c = g.axes[0, 0].collections
+        assert c[1].get_linewidths()[0] == mpl.rcParams["lines.linewidth"]
+
+    def test_lmplot_facets(self):
+
+        g = lm.lmplot(x="x", y="y", data=self.df, row="g", col="h")
+        assert g.axes.shape == (3, 2)
+
+        g = lm.lmplot(x="x", y="y", data=self.df, col="u", col_wrap=4)
+        assert g.axes.shape == (6,)
+
+        g = lm.lmplot(x="x", y="y", data=self.df, hue="h", col="u")
+        assert g.axes.shape == (1, 6)
+
+    def test_lmplot_hue_col_nolegend(self):
+
+        g = lm.lmplot(x="x", y="y", data=self.df, col="h", hue="h")
+        assert g._legend is None
+
+    def test_lmplot_scatter_kws(self):
+
+        g = lm.lmplot(x="x", y="y", hue="h", data=self.df, ci=None)
+        red_scatter, blue_scatter = g.axes[0, 0].collections
+
+        red, blue = color_palette(n_colors=2)
+        npt.assert_array_equal(red, red_scatter.get_facecolors()[0, :3])
+        npt.assert_array_equal(blue, blue_scatter.get_facecolors()[0, :3])
+
+    @pytest.mark.skipif(_version_predates(mpl, "3.4"),
+                        reason="MPL bug #15967")
+    @pytest.mark.parametrize("sharex", [True, False])
+    def test_lmplot_facet_truncate(self, sharex):
+
+        g = lm.lmplot(
+            data=self.df, x="x", y="y", hue="g", col="h",
+            truncate=False, facet_kws=dict(sharex=sharex),
+        )
+
+        for ax in g.axes.flat:
+            for line in ax.lines:
+                xdata = line.get_xdata()
+                assert ax.get_xlim() == tuple(xdata[[0, -1]])
+
+    def test_lmplot_sharey(self):
+
+        df = pd.DataFrame(dict(
+            x=[0, 1, 2, 0, 1, 2],
+            y=[1, -1, 0, -100, 200, 0],
+            z=["a", "a", "a", "b", "b", "b"],
+        ))
+
+        with pytest.warns(UserWarning):
+            g = lm.lmplot(data=df, x="x", y="y", col="z", sharey=False)
+        ax1, ax2 = g.axes.flat
+        assert ax1.get_ylim()[0] > ax2.get_ylim()[0]
+        assert ax1.get_ylim()[1] < ax2.get_ylim()[1]
+
+    def test_lmplot_facet_kws(self):
+
+        xlim = -4, 20
+        g = lm.lmplot(
+            data=self.df, x="x", y="y", col="h", facet_kws={"xlim": xlim}
+        )
+        for ax in g.axes.flat:
+            assert ax.get_xlim() == xlim
+
+    def test_residplot(self):
+
+        x, y = self.df.x, self.df.y
+        ax = lm.residplot(x=x, y=y)
+
+        resid = y - np.polyval(np.polyfit(x, y, 1), x)
+        x_plot, y_plot = ax.collections[0].get_offsets().T
+
+        npt.assert_array_equal(x, x_plot)
+        npt.assert_array_almost_equal(resid, y_plot)
+
+    @pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
+    def test_residplot_lowess(self):
+
+        ax = lm.residplot(x="x", y="y", data=self.df, lowess=True)
+        assert len(ax.lines) == 2
+
+        x, y = ax.lines[1].get_xydata().T
+        npt.assert_array_equal(x, np.sort(self.df.x))
+
+    def test_three_point_colors(self):
+
+        x, y = np.random.randn(2, 3)
+        ax = lm.regplot(x=x, y=y, color=(1, 0, 0))
+        color = ax.collections[0].get_facecolors()
+        npt.assert_almost_equal(color[0, :3],
+                                (1, 0, 0))
+
+    def test_regplot_xlim(self):
+
+        f, ax = plt.subplots()
+        x, y1, y2 = np.random.randn(3, 50)
+        lm.regplot(x=x, y=y1, truncate=False)
+        lm.regplot(x=x, y=y2, truncate=False)
+        line1, line2 = ax.lines
+        assert np.array_equal(line1.get_xdata(), line2.get_xdata())
diff --git a/testbed/mwaskom__seaborn/tests/test_relational.py b/testbed/mwaskom__seaborn/tests/test_relational.py
new file mode 100644
index 0000000000000000000000000000000000000000..53fcd9f95c11c1048f788c4abad11a9a88041fb8
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_relational.py
@@ -0,0 +1,1863 @@
+from itertools import product
+import warnings
+
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from matplotlib.colors import same_color, to_rgba
+
+import pytest
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn.palettes import color_palette
+from seaborn._oldcore import categorical_order
+
+from seaborn.relational import (
+    _RelationalPlotter,
+    _LinePlotter,
+    _ScatterPlotter,
+    relplot,
+    lineplot,
+    scatterplot
+)
+
+from seaborn.utils import _draw_figure
+from seaborn._compat import get_colormap
+from seaborn._testing import assert_plots_equal
+
+
+@pytest.fixture(params=[
+    dict(x="x", y="y"),
+    dict(x="t", y="y"),
+    dict(x="a", y="y"),
+    dict(x="x", y="y", hue="y"),
+    dict(x="x", y="y", hue="a"),
+    dict(x="x", y="y", size="a"),
+    dict(x="x", y="y", style="a"),
+    dict(x="x", y="y", hue="s"),
+    dict(x="x", y="y", size="s"),
+    dict(x="x", y="y", style="s"),
+    dict(x="x", y="y", hue="a", style="a"),
+    dict(x="x", y="y", hue="a", size="b", style="b"),
+])
+def long_semantics(request):
+    return request.param
+
+
+class Helpers:
+
+    # TODO Better place for these?
+
+    def scatter_rgbs(self, collections):
+        rgbs = []
+        for col in collections:
+            rgb = tuple(col.get_facecolor().squeeze()[:3])
+            rgbs.append(rgb)
+        return rgbs
+
+    def paths_equal(self, *args):
+
+        equal = all([len(a) == len(args[0]) for a in args])
+
+        for p1, p2 in zip(*args):
+            equal &= np.array_equal(p1.vertices, p2.vertices)
+            equal &= np.array_equal(p1.codes, p2.codes)
+        return equal
+
+
+class SharedAxesLevelTests:
+
+    def test_color(self, long_df):
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C0")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", ax=ax)
+        self.func(data=long_df, x="x", y="y", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C1")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", color="C2", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C2")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", c="C2", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C2")
+
+
+class TestRelationalPlotter(Helpers):
+
+    def test_wide_df_variables(self, wide_df):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_df)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+        assert len(p.plot_data) == np.product(wide_df.shape)
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(wide_df.index, wide_df.shape[1])
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = wide_df.to_numpy().ravel(order="f")
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(wide_df.columns.to_numpy(), wide_df.shape[0])
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] == wide_df.index.name
+        assert p.variables["y"] is None
+        assert p.variables["hue"] == wide_df.columns.name
+        assert p.variables["style"] == wide_df.columns.name
+
+    def test_wide_df_with_nonnumeric_variables(self, long_df):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=long_df)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        numeric_df = long_df.select_dtypes("number")
+
+        assert len(p.plot_data) == np.product(numeric_df.shape)
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(numeric_df.index, numeric_df.shape[1])
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = numeric_df.to_numpy().ravel(order="f")
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(
+            numeric_df.columns.to_numpy(), numeric_df.shape[0]
+        )
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] == numeric_df.index.name
+        assert p.variables["y"] is None
+        assert p.variables["hue"] == numeric_df.columns.name
+        assert p.variables["style"] == numeric_df.columns.name
+
+    def test_wide_array_variables(self, wide_array):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_array)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+        assert len(p.plot_data) == np.product(wide_array.shape)
+
+        nrow, ncol = wide_array.shape
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(nrow), ncol)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = wide_array.ravel(order="f")
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(np.arange(ncol), nrow)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_flat_array_variables(self, flat_array):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=flat_array)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y"]
+        assert len(p.plot_data) == np.product(flat_array.shape)
+
+        x = p.plot_data["x"]
+        expected_x = np.arange(flat_array.shape[0])
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = flat_array
+        assert_array_equal(y, expected_y)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+
+    def test_flat_list_variables(self, flat_list):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=flat_list)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y"]
+        assert len(p.plot_data) == len(flat_list)
+
+        x = p.plot_data["x"]
+        expected_x = np.arange(len(flat_list))
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = flat_list
+        assert_array_equal(y, expected_y)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+
+    def test_flat_series_variables(self, flat_series):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=flat_series)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y"]
+        assert len(p.plot_data) == len(flat_series)
+
+        x = p.plot_data["x"]
+        expected_x = flat_series.index
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = flat_series
+        assert_array_equal(y, expected_y)
+
+        assert p.variables["x"] is flat_series.index.name
+        assert p.variables["y"] is flat_series.name
+
+    def test_wide_list_of_series_variables(self, wide_list_of_series):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_list_of_series)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_list_of_series)
+        chunk_size = max(len(l) for l in wide_list_of_series)
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        index_union = np.unique(
+            np.concatenate([s.index for s in wide_list_of_series])
+        )
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(index_union, chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"]
+        expected_y = np.concatenate([
+            s.reindex(index_union) for s in wide_list_of_series
+        ])
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        series_names = [s.name for s in wide_list_of_series]
+        expected_hue = np.repeat(series_names, chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_wide_list_of_arrays_variables(self, wide_list_of_arrays):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_list_of_arrays)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_list_of_arrays)
+        chunk_size = max(len(l) for l in wide_list_of_arrays)
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(chunk_size), chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"].dropna()
+        expected_y = np.concatenate(wide_list_of_arrays)
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(np.arange(chunks), chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_wide_list_of_list_variables(self, wide_list_of_lists):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_list_of_lists)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_list_of_lists)
+        chunk_size = max(len(l) for l in wide_list_of_lists)
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(chunk_size), chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"].dropna()
+        expected_y = np.concatenate(wide_list_of_lists)
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(np.arange(chunks), chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_wide_dict_of_series_variables(self, wide_dict_of_series):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_dict_of_series)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_dict_of_series)
+        chunk_size = max(len(l) for l in wide_dict_of_series.values())
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(chunk_size), chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"].dropna()
+        expected_y = np.concatenate(list(wide_dict_of_series.values()))
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(list(wide_dict_of_series), chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_wide_dict_of_arrays_variables(self, wide_dict_of_arrays):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_dict_of_arrays)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_dict_of_arrays)
+        chunk_size = max(len(l) for l in wide_dict_of_arrays.values())
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(chunk_size), chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"].dropna()
+        expected_y = np.concatenate(list(wide_dict_of_arrays.values()))
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(list(wide_dict_of_arrays), chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_wide_dict_of_lists_variables(self, wide_dict_of_lists):
+
+        p = _RelationalPlotter()
+        p.assign_variables(data=wide_dict_of_lists)
+        assert p.input_format == "wide"
+        assert list(p.variables) == ["x", "y", "hue", "style"]
+
+        chunks = len(wide_dict_of_lists)
+        chunk_size = max(len(l) for l in wide_dict_of_lists.values())
+
+        assert len(p.plot_data) == chunks * chunk_size
+
+        x = p.plot_data["x"]
+        expected_x = np.tile(np.arange(chunk_size), chunks)
+        assert_array_equal(x, expected_x)
+
+        y = p.plot_data["y"].dropna()
+        expected_y = np.concatenate(list(wide_dict_of_lists.values()))
+        assert_array_equal(y, expected_y)
+
+        hue = p.plot_data["hue"]
+        expected_hue = np.repeat(list(wide_dict_of_lists), chunk_size)
+        assert_array_equal(hue, expected_hue)
+
+        style = p.plot_data["style"]
+        expected_style = expected_hue
+        assert_array_equal(style, expected_style)
+
+        assert p.variables["x"] is None
+        assert p.variables["y"] is None
+        assert p.variables["hue"] is None
+        assert p.variables["style"] is None
+
+    def test_relplot_simple(self, long_df):
+
+        g = relplot(data=long_df, x="x", y="y", kind="scatter")
+        x, y = g.ax.collections[0].get_offsets().T
+        assert_array_equal(x, long_df["x"])
+        assert_array_equal(y, long_df["y"])
+
+        g = relplot(data=long_df, x="x", y="y", kind="line")
+        x, y = g.ax.lines[0].get_xydata().T
+        expected = long_df.groupby("x").y.mean()
+        assert_array_equal(x, expected.index)
+        assert y == pytest.approx(expected.values)
+
+        with pytest.raises(ValueError):
+            g = relplot(data=long_df, x="x", y="y", kind="not_a_kind")
+
+    def test_relplot_complex(self, long_df):
+
+        for sem in ["hue", "size", "style"]:
+            g = relplot(data=long_df, x="x", y="y", **{sem: "a"})
+            x, y = g.ax.collections[0].get_offsets().T
+            assert_array_equal(x, long_df["x"])
+            assert_array_equal(y, long_df["y"])
+
+        for sem in ["hue", "size", "style"]:
+            g = relplot(
+                data=long_df, x="x", y="y", col="c", **{sem: "a"}
+            )
+            grouped = long_df.groupby("c")
+            for (_, grp_df), ax in zip(grouped, g.axes.flat):
+                x, y = ax.collections[0].get_offsets().T
+                assert_array_equal(x, grp_df["x"])
+                assert_array_equal(y, grp_df["y"])
+
+        for sem in ["size", "style"]:
+            g = relplot(
+                data=long_df, x="x", y="y", hue="b", col="c", **{sem: "a"}
+            )
+            grouped = long_df.groupby("c")
+            for (_, grp_df), ax in zip(grouped, g.axes.flat):
+                x, y = ax.collections[0].get_offsets().T
+                assert_array_equal(x, grp_df["x"])
+                assert_array_equal(y, grp_df["y"])
+
+        for sem in ["hue", "size", "style"]:
+            g = relplot(
+                data=long_df.sort_values(["c", "b"]),
+                x="x", y="y", col="b", row="c", **{sem: "a"}
+            )
+            grouped = long_df.groupby(["c", "b"])
+            for (_, grp_df), ax in zip(grouped, g.axes.flat):
+                x, y = ax.collections[0].get_offsets().T
+                assert_array_equal(x, grp_df["x"])
+                assert_array_equal(y, grp_df["y"])
+
+    @pytest.mark.parametrize("vector_type", ["series", "numpy", "list"])
+    def test_relplot_vectors(self, long_df, vector_type):
+
+        semantics = dict(x="x", y="y", hue="f", col="c")
+        kws = {key: long_df[val] for key, val in semantics.items()}
+        if vector_type == "numpy":
+            kws = {k: v.to_numpy() for k, v in kws.items()}
+        elif vector_type == "list":
+            kws = {k: v.to_list() for k, v in kws.items()}
+        g = relplot(data=long_df, **kws)
+        grouped = long_df.groupby("c")
+        assert len(g.axes_dict) == len(grouped)
+        for (_, grp_df), ax in zip(grouped, g.axes.flat):
+            x, y = ax.collections[0].get_offsets().T
+            assert_array_equal(x, grp_df["x"])
+            assert_array_equal(y, grp_df["y"])
+
+    def test_relplot_wide(self, wide_df):
+
+        g = relplot(data=wide_df)
+        x, y = g.ax.collections[0].get_offsets().T
+        assert_array_equal(y, wide_df.to_numpy().T.ravel())
+        assert not g.ax.get_ylabel()
+
+    def test_relplot_hues(self, long_df):
+
+        palette = ["r", "b", "g"]
+        g = relplot(
+            x="x", y="y", hue="a", style="b", col="c",
+            palette=palette, data=long_df
+        )
+
+        palette = dict(zip(long_df["a"].unique(), palette))
+        grouped = long_df.groupby("c")
+        for (_, grp_df), ax in zip(grouped, g.axes.flat):
+            points = ax.collections[0]
+            expected_hues = [palette[val] for val in grp_df["a"]]
+            assert same_color(points.get_facecolors(), expected_hues)
+
+    def test_relplot_sizes(self, long_df):
+
+        sizes = [5, 12, 7]
+        g = relplot(
+            data=long_df,
+            x="x", y="y", size="a", hue="b", col="c",
+            sizes=sizes,
+        )
+
+        sizes = dict(zip(long_df["a"].unique(), sizes))
+        grouped = long_df.groupby("c")
+        for (_, grp_df), ax in zip(grouped, g.axes.flat):
+            points = ax.collections[0]
+            expected_sizes = [sizes[val] for val in grp_df["a"]]
+            assert_array_equal(points.get_sizes(), expected_sizes)
+
+    def test_relplot_styles(self, long_df):
+
+        markers = ["o", "d", "s"]
+        g = relplot(
+            data=long_df,
+            x="x", y="y", style="a", hue="b", col="c",
+            markers=markers,
+        )
+
+        paths = []
+        for m in markers:
+            m = mpl.markers.MarkerStyle(m)
+            paths.append(m.get_path().transformed(m.get_transform()))
+        paths = dict(zip(long_df["a"].unique(), paths))
+
+        grouped = long_df.groupby("c")
+        for (_, grp_df), ax in zip(grouped, g.axes.flat):
+            points = ax.collections[0]
+            expected_paths = [paths[val] for val in grp_df["a"]]
+            assert self.paths_equal(points.get_paths(), expected_paths)
+
+    def test_relplot_stringy_numerics(self, long_df):
+
+        long_df["x_str"] = long_df["x"].astype(str)
+
+        g = relplot(data=long_df, x="x", y="y", hue="x_str")
+        points = g.ax.collections[0]
+        xys = points.get_offsets()
+        mask = np.ma.getmask(xys)
+        assert not mask.any()
+        assert_array_equal(xys, long_df[["x", "y"]])
+
+        g = relplot(data=long_df, x="x", y="y", size="x_str")
+        points = g.ax.collections[0]
+        xys = points.get_offsets()
+        mask = np.ma.getmask(xys)
+        assert not mask.any()
+        assert_array_equal(xys, long_df[["x", "y"]])
+
+    def test_relplot_legend(self, long_df):
+
+        g = relplot(data=long_df, x="x", y="y")
+        assert g._legend is None
+
+        g = relplot(data=long_df, x="x", y="y", hue="a")
+        texts = [t.get_text() for t in g._legend.texts]
+        expected_texts = long_df["a"].unique()
+        assert_array_equal(texts, expected_texts)
+
+        g = relplot(data=long_df, x="x", y="y", hue="s", size="s")
+        texts = [t.get_text() for t in g._legend.texts]
+        assert_array_equal(texts, np.sort(texts))
+
+        g = relplot(data=long_df, x="x", y="y", hue="a", legend=False)
+        assert g._legend is None
+
+        palette = color_palette("deep", len(long_df["b"].unique()))
+        a_like_b = dict(zip(long_df["a"].unique(), long_df["b"].unique()))
+        long_df["a_like_b"] = long_df["a"].map(a_like_b)
+        g = relplot(
+            data=long_df,
+            x="x", y="y", hue="b", style="a_like_b",
+            palette=palette, kind="line", estimator=None,
+        )
+        lines = g._legend.get_lines()[1:]  # Chop off title dummy
+        for line, color in zip(lines, palette):
+            assert line.get_color() == color
+
+    def test_relplot_unshared_axis_labels(self, long_df):
+
+        col, row = "a", "b"
+        g = relplot(
+            data=long_df, x="x", y="y", col=col, row=row,
+            facet_kws=dict(sharex=False, sharey=False),
+        )
+
+        for ax in g.axes[-1, :].flat:
+            assert ax.get_xlabel() == "x"
+        for ax in g.axes[:-1, :].flat:
+            assert ax.get_xlabel() == ""
+        for ax in g.axes[:, 0].flat:
+            assert ax.get_ylabel() == "y"
+        for ax in g.axes[:, 1:].flat:
+            assert ax.get_ylabel() == ""
+
+    def test_relplot_data(self, long_df):
+
+        g = relplot(
+            data=long_df.to_dict(orient="list"),
+            x="x",
+            y=long_df["y"].rename("y_var"),
+            hue=long_df["a"].to_numpy(),
+            col="c",
+        )
+        expected_cols = set(long_df.columns.to_list() + ["_hue_", "y_var"])
+        assert set(g.data.columns) == expected_cols
+        assert_array_equal(g.data["y_var"], long_df["y"])
+        assert_array_equal(g.data["_hue_"], long_df["a"])
+
+    def test_facet_variable_collision(self, long_df):
+
+        # https://github.com/mwaskom/seaborn/issues/2488
+        col_data = long_df["c"]
+        long_df = long_df.assign(size=col_data)
+
+        g = relplot(
+            data=long_df,
+            x="x", y="y", col="size",
+        )
+        assert g.axes.shape == (1, len(col_data.unique()))
+
+    def test_ax_kwarg_removal(self, long_df):
+
+        f, ax = plt.subplots()
+        with pytest.warns(UserWarning):
+            g = relplot(data=long_df, x="x", y="y", ax=ax)
+        assert len(ax.collections) == 0
+        assert len(g.ax.collections) > 0
+
+    def test_legend_has_no_offset(self, long_df):
+
+        g = relplot(data=long_df, x="x", y="y", hue=long_df["z"] + 1e8)
+        for text in g.legend.texts:
+            assert float(text.get_text()) > 1e7
+
+
+class TestLinePlotter(SharedAxesLevelTests, Helpers):
+
+    func = staticmethod(lineplot)
+
+    def get_last_color(self, ax):
+
+        return to_rgba(ax.lines[-1].get_color())
+
+    def test_legend_data(self, long_df):
+
+        f, ax = plt.subplots()
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+            legend="full"
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert handles == []
+
+        # --
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            legend="full",
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_color() for h in handles]
+        assert labels == p._hue_map.levels
+        assert colors == p._hue_map(p._hue_map.levels)
+
+        # --
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="a"),
+            legend="full",
+        )
+        p.map_style(markers=True)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_color() for h in handles]
+        markers = [h.get_marker() for h in handles]
+        assert labels == p._hue_map.levels
+        assert labels == p._style_map.levels
+        assert colors == p._hue_map(p._hue_map.levels)
+        assert markers == p._style_map(p._style_map.levels, "marker")
+
+        # --
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="b"),
+            legend="full",
+        )
+        p.map_style(markers=True)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_color() for h in handles]
+        markers = [h.get_marker() for h in handles]
+        expected_labels = (
+            ["a"]
+            + p._hue_map.levels
+            + ["b"] + p._style_map.levels
+        )
+        expected_colors = (
+            ["w"] + p._hue_map(p._hue_map.levels)
+            + ["w"] + [".2" for _ in p._style_map.levels]
+        )
+        expected_markers = (
+            [""] + ["None" for _ in p._hue_map.levels]
+            + [""] + p._style_map(p._style_map.levels, "marker")
+        )
+        assert labels == expected_labels
+        assert colors == expected_colors
+        assert markers == expected_markers
+
+        # --
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", size="a"),
+            legend="full"
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_color() for h in handles]
+        widths = [h.get_linewidth() for h in handles]
+        assert labels == p._hue_map.levels
+        assert labels == p._size_map.levels
+        assert colors == p._hue_map(p._hue_map.levels)
+        assert widths == p._size_map(p._size_map.levels)
+
+        # --
+
+        x, y = np.random.randn(2, 40)
+        z = np.tile(np.arange(20), 2)
+
+        p = _LinePlotter(variables=dict(x=x, y=y, hue=z))
+
+        ax.clear()
+        p.legend = "full"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == [str(l) for l in p._hue_map.levels]
+
+        ax.clear()
+        p.legend = "brief"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._hue_map.levels)
+
+        p = _LinePlotter(variables=dict(x=x, y=y, size=z))
+
+        ax.clear()
+        p.legend = "full"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == [str(l) for l in p._size_map.levels]
+
+        ax.clear()
+        p.legend = "brief"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._size_map.levels)
+
+        ax.clear()
+        p.legend = "auto"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._size_map.levels)
+
+        ax.clear()
+        p.legend = True
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._size_map.levels)
+
+        ax.clear()
+        p.legend = "bad_value"
+        with pytest.raises(ValueError):
+            p.add_legend_data(ax)
+
+        ax.clear()
+        p = _LinePlotter(
+            variables=dict(x=x, y=y, hue=z + 1),
+            legend="brief"
+        )
+        p.map_hue(norm=mpl.colors.LogNorm()),
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert float(labels[1]) / float(labels[0]) == 10
+
+        ax.clear()
+        p = _LinePlotter(
+            variables=dict(x=x, y=y, hue=z % 2),
+            legend="auto"
+        )
+        p.map_hue(norm=mpl.colors.LogNorm()),
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == ["0", "1"]
+
+        ax.clear()
+        p = _LinePlotter(
+            variables=dict(x=x, y=y, size=z + 1),
+            legend="brief"
+        )
+        p.map_size(norm=mpl.colors.LogNorm())
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert float(labels[1]) / float(labels[0]) == 10
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="f"),
+            legend="brief",
+        )
+        p.add_legend_data(ax)
+        expected_labels = ['0.20', '0.22', '0.24', '0.26', '0.28']
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == expected_labels
+
+        ax.clear()
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="f"),
+            legend="brief",
+        )
+        p.add_legend_data(ax)
+        expected_levels = ['0.20', '0.22', '0.24', '0.26', '0.28']
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == expected_levels
+
+    def test_plot(self, long_df, repeated_df):
+
+        f, ax = plt.subplots()
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+            sort=False,
+            estimator=None
+        )
+        p.plot(ax, {})
+        line, = ax.lines
+        assert_array_equal(line.get_xdata(), long_df.x.to_numpy())
+        assert_array_equal(line.get_ydata(), long_df.y.to_numpy())
+
+        ax.clear()
+        p.plot(ax, {"color": "k", "label": "test"})
+        line, = ax.lines
+        assert line.get_color() == "k"
+        assert line.get_label() == "test"
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+            sort=True, estimator=None
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        line, = ax.lines
+        sorted_data = long_df.sort_values(["x", "y"])
+        assert_array_equal(line.get_xdata(), sorted_data.x.to_numpy())
+        assert_array_equal(line.get_ydata(), sorted_data.y.to_numpy())
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        assert len(ax.lines) == len(p._hue_map.levels)
+        for line, level in zip(ax.lines, p._hue_map.levels):
+            assert line.get_color() == p._hue_map(level)
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="a"),
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        assert len(ax.lines) == len(p._size_map.levels)
+        for line, level in zip(ax.lines, p._size_map.levels):
+            assert line.get_linewidth() == p._size_map(level)
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="a"),
+        )
+        p.map_style(markers=True)
+
+        ax.clear()
+        p.plot(ax, {})
+        assert len(ax.lines) == len(p._hue_map.levels)
+        assert len(ax.lines) == len(p._style_map.levels)
+        for line, level in zip(ax.lines, p._hue_map.levels):
+            assert line.get_color() == p._hue_map(level)
+            assert line.get_marker() == p._style_map(level, "marker")
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="b"),
+        )
+        p.map_style(markers=True)
+
+        ax.clear()
+        p.plot(ax, {})
+        levels = product(p._hue_map.levels, p._style_map.levels)
+        expected_line_count = len(p._hue_map.levels) * len(p._style_map.levels)
+        assert len(ax.lines) == expected_line_count
+        for line, (hue, style) in zip(ax.lines, levels):
+            assert line.get_color() == p._hue_map(hue)
+            assert line.get_marker() == p._style_map(style, "marker")
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+            estimator="mean", err_style="band", errorbar="sd", sort=True
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        line, = ax.lines
+        expected_data = long_df.groupby("x").y.mean()
+        assert_array_equal(line.get_xdata(), expected_data.index.to_numpy())
+        assert np.allclose(line.get_ydata(), expected_data.to_numpy())
+        assert len(ax.collections) == 1
+
+        # Test that nans do not propagate to means or CIs
+
+        p = _LinePlotter(
+            variables=dict(
+                x=[1, 1, 1, 2, 2, 2, 3, 3, 3],
+                y=[1, 2, 3, 3, np.nan, 5, 4, 5, 6],
+            ),
+            estimator="mean", err_style="band", errorbar="ci", n_boot=100, sort=True,
+        )
+        ax.clear()
+        p.plot(ax, {})
+        line, = ax.lines
+        assert line.get_xdata().tolist() == [1, 2, 3]
+        err_band = ax.collections[0].get_paths()
+        assert len(err_band) == 1
+        assert len(err_band[0].vertices) == 9
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            estimator="mean", err_style="band", errorbar="sd"
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        assert len(ax.lines) == len(ax.collections) == len(p._hue_map.levels)
+        for c in ax.collections:
+            assert isinstance(c, mpl.collections.PolyCollection)
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            estimator="mean", err_style="bars", errorbar="sd"
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        n_lines = len(ax.lines)
+        assert n_lines / 2 == len(ax.collections) == len(p._hue_map.levels)
+        assert len(ax.collections) == len(p._hue_map.levels)
+        for c in ax.collections:
+            assert isinstance(c, mpl.collections.LineCollection)
+
+        p = _LinePlotter(
+            data=repeated_df,
+            variables=dict(x="x", y="y", units="u"),
+            estimator=None
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        n_units = len(repeated_df["u"].unique())
+        assert len(ax.lines) == n_units
+
+        p = _LinePlotter(
+            data=repeated_df,
+            variables=dict(x="x", y="y", hue="a", units="u"),
+            estimator=None
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        n_units *= len(repeated_df["a"].unique())
+        assert len(ax.lines) == n_units
+
+        p.estimator = "mean"
+        with pytest.raises(ValueError):
+            p.plot(ax, {})
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            err_style="band", err_kws={"alpha": .5},
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        for band in ax.collections:
+            assert band.get_alpha() == .5
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            err_style="bars", err_kws={"elinewidth": 2},
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        for lines in ax.collections:
+            assert lines.get_linestyles() == 2
+
+        p.err_style = "invalid"
+        with pytest.raises(ValueError):
+            p.plot(ax, {})
+
+        x_str = long_df["x"].astype(str)
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue=x_str),
+        )
+        ax.clear()
+        p.plot(ax, {})
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size=x_str),
+        )
+        ax.clear()
+        p.plot(ax, {})
+
+    def test_non_aggregated_data(self):
+
+        x = [1, 2, 3, 4]
+        y = [2, 4, 6, 8]
+        ax = lineplot(x=x, y=y)
+        line, = ax.lines
+        assert_array_equal(line.get_xdata(), x)
+        assert_array_equal(line.get_ydata(), y)
+
+    def test_orient(self, long_df):
+
+        long_df = long_df.drop("x", axis=1).rename(columns={"s": "y", "y": "x"})
+
+        ax1 = plt.figure().subplots()
+        lineplot(data=long_df, x="x", y="y", orient="y", errorbar="sd")
+        assert len(ax1.lines) == len(ax1.collections)
+        line, = ax1.lines
+        expected = long_df.groupby("y").agg({"x": "mean"}).reset_index()
+        assert_array_almost_equal(line.get_xdata(), expected["x"])
+        assert_array_almost_equal(line.get_ydata(), expected["y"])
+        ribbon_y = ax1.collections[0].get_paths()[0].vertices[:, 1]
+        assert_array_equal(np.unique(ribbon_y), long_df["y"].sort_values().unique())
+
+        ax2 = plt.figure().subplots()
+        lineplot(
+            data=long_df, x="x", y="y", orient="y", errorbar="sd", err_style="bars"
+        )
+        segments = ax2.collections[0].get_segments()
+        for i, val in enumerate(sorted(long_df["y"].unique())):
+            assert (segments[i][:, 1] == val).all()
+
+        with pytest.raises(ValueError, match="`orient` must be either 'x' or 'y'"):
+            lineplot(long_df, x="y", y="x", orient="bad")
+
+    def test_log_scale(self):
+
+        f, ax = plt.subplots()
+        ax.set_xscale("log")
+
+        x = [1, 10, 100]
+        y = [1, 2, 3]
+
+        lineplot(x=x, y=y)
+        line = ax.lines[0]
+        assert_array_equal(line.get_xdata(), x)
+        assert_array_equal(line.get_ydata(), y)
+
+        f, ax = plt.subplots()
+        ax.set_xscale("log")
+        ax.set_yscale("log")
+
+        x = [1, 1, 2, 2]
+        y = [1, 10, 1, 100]
+
+        lineplot(x=x, y=y, err_style="bars", errorbar=("pi", 100))
+        line = ax.lines[0]
+        assert line.get_ydata()[1] == 10
+
+        ebars = ax.collections[0].get_segments()
+        assert_array_equal(ebars[0][:, 1], y[:2])
+        assert_array_equal(ebars[1][:, 1], y[2:])
+
+    def test_axis_labels(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
+
+        p = _LinePlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+        )
+
+        p.plot(ax1, {})
+        assert ax1.get_xlabel() == "x"
+        assert ax1.get_ylabel() == "y"
+
+        p.plot(ax2, {})
+        assert ax2.get_xlabel() == "x"
+        assert ax2.get_ylabel() == "y"
+        assert not ax2.yaxis.label.get_visible()
+
+    def test_matplotlib_kwargs(self, long_df):
+
+        kws = {
+            "linestyle": "--",
+            "linewidth": 3,
+            "color": (1, .5, .2),
+            "markeredgecolor": (.2, .5, .2),
+            "markeredgewidth": 1,
+        }
+        ax = lineplot(data=long_df, x="x", y="y", **kws)
+
+        line, *_ = ax.lines
+        for key, val in kws.items():
+            plot_val = getattr(line, f"get_{key}")()
+            assert plot_val == val
+
+    def test_nonmapped_dashes(self):
+
+        ax = lineplot(x=[1, 2], y=[1, 2], dashes=(2, 1))
+        line = ax.lines[0]
+        # Not a great test, but lines don't expose the dash style publicly
+        assert line.get_linestyle() == "--"
+
+    def test_lineplot_axes(self, wide_df):
+
+        f1, ax1 = plt.subplots()
+        f2, ax2 = plt.subplots()
+
+        ax = lineplot(data=wide_df)
+        assert ax is ax2
+
+        ax = lineplot(data=wide_df, ax=ax1)
+        assert ax is ax1
+
+    def test_lineplot_vs_relplot(self, long_df, long_semantics):
+
+        ax = lineplot(data=long_df, **long_semantics)
+        g = relplot(data=long_df, kind="line", **long_semantics)
+
+        lin_lines = ax.lines
+        rel_lines = g.ax.lines
+
+        for l1, l2 in zip(lin_lines, rel_lines):
+            assert_array_equal(l1.get_xydata(), l2.get_xydata())
+            assert same_color(l1.get_color(), l2.get_color())
+            assert l1.get_linewidth() == l2.get_linewidth()
+            assert l1.get_linestyle() == l2.get_linestyle()
+
+    def test_lineplot_smoke(
+        self,
+        wide_df, wide_array,
+        wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,
+        flat_array, flat_series, flat_list,
+        long_df, missing_df, object_df
+    ):
+
+        f, ax = plt.subplots()
+
+        lineplot(x=[], y=[])
+        ax.clear()
+
+        lineplot(data=wide_df)
+        ax.clear()
+
+        lineplot(data=wide_array)
+        ax.clear()
+
+        lineplot(data=wide_list_of_series)
+        ax.clear()
+
+        lineplot(data=wide_list_of_arrays)
+        ax.clear()
+
+        lineplot(data=wide_list_of_lists)
+        ax.clear()
+
+        lineplot(data=flat_series)
+        ax.clear()
+
+        lineplot(data=flat_array)
+        ax.clear()
+
+        lineplot(data=flat_list)
+        ax.clear()
+
+        lineplot(x="x", y="y", data=long_df)
+        ax.clear()
+
+        lineplot(x=long_df.x, y=long_df.y)
+        ax.clear()
+
+        lineplot(x=long_df.x, y="y", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y=long_df.y.to_numpy(), data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="t", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", style="a", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", style="b", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", style="a", data=missing_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", style="b", data=missing_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", size="a", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", size="s", data=long_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", size="a", data=missing_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="a", size="s", data=missing_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="f", data=object_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="c", size="f", data=object_df)
+        ax.clear()
+
+        lineplot(x="x", y="y", hue="f", size="s", data=object_df)
+        ax.clear()
+
+    def test_ci_deprecation(self, long_df):
+
+        axs = plt.figure().subplots(2)
+        lineplot(data=long_df, x="x", y="y", errorbar=("ci", 95), seed=0, ax=axs[0])
+        with pytest.warns(FutureWarning, match="\n\nThe `ci` parameter is deprecated"):
+            lineplot(data=long_df, x="x", y="y", ci=95, seed=0, ax=axs[1])
+        assert_plots_equal(*axs)
+
+        axs = plt.figure().subplots(2)
+        lineplot(data=long_df, x="x", y="y", errorbar="sd", ax=axs[0])
+        with pytest.warns(FutureWarning, match="\n\nThe `ci` parameter is deprecated"):
+            lineplot(data=long_df, x="x", y="y", ci="sd", ax=axs[1])
+        assert_plots_equal(*axs)
+
+
+class TestScatterPlotter(SharedAxesLevelTests, Helpers):
+
+    func = staticmethod(scatterplot)
+
+    def get_last_color(self, ax):
+
+        colors = ax.collections[-1].get_facecolors()
+        unique_colors = np.unique(colors, axis=0)
+        assert len(unique_colors) == 1
+        return to_rgba(unique_colors.squeeze())
+
+    def test_color(self, long_df):
+
+        super().test_color(long_df)
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", facecolor="C5", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C5")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", facecolors="C6", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C6")
+
+        ax = plt.figure().subplots()
+        self.func(data=long_df, x="x", y="y", fc="C4", ax=ax)
+        assert self.get_last_color(ax) == to_rgba("C4")
+
+    def test_legend_data(self, long_df):
+
+        m = mpl.markers.MarkerStyle("o")
+        default_mark = m.get_path().transformed(m.get_transform())
+
+        m = mpl.markers.MarkerStyle("")
+        null = m.get_path().transformed(m.get_transform())
+
+        f, ax = plt.subplots()
+
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y"),
+            legend="full",
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert handles == []
+
+        # --
+
+        ax.clear()
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a"),
+            legend="full",
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_facecolors()[0] for h in handles]
+        expected_colors = p._hue_map(p._hue_map.levels)
+        assert labels == p._hue_map.levels
+        assert same_color(colors, expected_colors)
+
+        # --
+
+        ax.clear()
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="a"),
+            legend="full",
+        )
+        p.map_style(markers=True)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_facecolors()[0] for h in handles]
+        expected_colors = p._hue_map(p._hue_map.levels)
+        paths = [h.get_paths()[0] for h in handles]
+        expected_paths = p._style_map(p._style_map.levels, "path")
+        assert labels == p._hue_map.levels
+        assert labels == p._style_map.levels
+        assert same_color(colors, expected_colors)
+        assert self.paths_equal(paths, expected_paths)
+
+        # --
+
+        ax.clear()
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="b"),
+            legend="full",
+        )
+        p.map_style(markers=True)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_facecolors()[0] for h in handles]
+        paths = [h.get_paths()[0] for h in handles]
+        expected_colors = (
+            ["w"] + p._hue_map(p._hue_map.levels)
+            + ["w"] + [".2" for _ in p._style_map.levels]
+        )
+        expected_paths = (
+            [null] + [default_mark for _ in p._hue_map.levels]
+            + [null] + p._style_map(p._style_map.levels, "path")
+        )
+        assert labels == (
+            ["a"] + p._hue_map.levels + ["b"] + p._style_map.levels
+        )
+        assert same_color(colors, expected_colors)
+        assert self.paths_equal(paths, expected_paths)
+
+        # --
+
+        ax.clear()
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", size="a"),
+            legend="full"
+        )
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        colors = [h.get_facecolors()[0] for h in handles]
+        expected_colors = p._hue_map(p._hue_map.levels)
+        sizes = [h.get_sizes()[0] for h in handles]
+        expected_sizes = p._size_map(p._size_map.levels)
+        assert labels == p._hue_map.levels
+        assert labels == p._size_map.levels
+        assert same_color(colors, expected_colors)
+        assert sizes == expected_sizes
+
+        # --
+
+        ax.clear()
+        sizes_list = [10, 100, 200]
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="s"),
+            legend="full",
+        )
+        p.map_size(sizes=sizes_list)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        sizes = [h.get_sizes()[0] for h in handles]
+        expected_sizes = p._size_map(p._size_map.levels)
+        assert labels == [str(l) for l in p._size_map.levels]
+        assert sizes == expected_sizes
+
+        # --
+
+        ax.clear()
+        sizes_dict = {2: 10, 4: 100, 8: 200}
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", size="s"),
+            legend="full"
+        )
+        p.map_size(sizes=sizes_dict)
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        sizes = [h.get_sizes()[0] for h in handles]
+        expected_sizes = p._size_map(p._size_map.levels)
+        assert labels == [str(l) for l in p._size_map.levels]
+        assert sizes == expected_sizes
+
+        # --
+
+        x, y = np.random.randn(2, 40)
+        z = np.tile(np.arange(20), 2)
+
+        p = _ScatterPlotter(
+            variables=dict(x=x, y=y, hue=z),
+        )
+
+        ax.clear()
+        p.legend = "full"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == [str(l) for l in p._hue_map.levels]
+
+        ax.clear()
+        p.legend = "brief"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._hue_map.levels)
+
+        p = _ScatterPlotter(
+            variables=dict(x=x, y=y, size=z),
+        )
+
+        ax.clear()
+        p.legend = "full"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert labels == [str(l) for l in p._size_map.levels]
+
+        ax.clear()
+        p.legend = "brief"
+        p.add_legend_data(ax)
+        handles, labels = ax.get_legend_handles_labels()
+        assert len(labels) < len(p._size_map.levels)
+
+        ax.clear()
+        p.legend = "bad_value"
+        with pytest.raises(ValueError):
+            p.add_legend_data(ax)
+
+    def test_plot(self, long_df, repeated_df):
+
+        f, ax = plt.subplots()
+
+        p = _ScatterPlotter(data=long_df, variables=dict(x="x", y="y"))
+
+        p.plot(ax, {})
+        points = ax.collections[0]
+        assert_array_equal(points.get_offsets(), long_df[["x", "y"]].to_numpy())
+
+        ax.clear()
+        p.plot(ax, {"color": "k", "label": "test"})
+        points = ax.collections[0]
+        assert same_color(points.get_facecolor(), "k")
+        assert points.get_label() == "test"
+
+        p = _ScatterPlotter(
+            data=long_df, variables=dict(x="x", y="y", hue="a")
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        points = ax.collections[0]
+        expected_colors = p._hue_map(p.plot_data["hue"])
+        assert same_color(points.get_facecolors(), expected_colors)
+
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", style="c"),
+        )
+        p.map_style(markers=["+", "x"])
+
+        ax.clear()
+        color = (1, .3, .8)
+        p.plot(ax, {"color": color})
+        points = ax.collections[0]
+        assert same_color(points.get_edgecolors(), [color])
+
+        p = _ScatterPlotter(
+            data=long_df, variables=dict(x="x", y="y", size="a"),
+        )
+
+        ax.clear()
+        p.plot(ax, {})
+        points = ax.collections[0]
+        expected_sizes = p._size_map(p.plot_data["size"])
+        assert_array_equal(points.get_sizes(), expected_sizes)
+
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="a"),
+        )
+        p.map_style(markers=True)
+
+        ax.clear()
+        p.plot(ax, {})
+        points = ax.collections[0]
+        expected_colors = p._hue_map(p.plot_data["hue"])
+        expected_paths = p._style_map(p.plot_data["style"], "path")
+        assert same_color(points.get_facecolors(), expected_colors)
+        assert self.paths_equal(points.get_paths(), expected_paths)
+
+        p = _ScatterPlotter(
+            data=long_df,
+            variables=dict(x="x", y="y", hue="a", style="b"),
+        )
+        p.map_style(markers=True)
+
+        ax.clear()
+        p.plot(ax, {})
+        points = ax.collections[0]
+        expected_colors = p._hue_map(p.plot_data["hue"])
+        expected_paths = p._style_map(p.plot_data["style"], "path")
+        assert same_color(points.get_facecolors(), expected_colors)
+        assert self.paths_equal(points.get_paths(), expected_paths)
+
+        x_str = long_df["x"].astype(str)
+        p = _ScatterPlotter(
+            data=long_df, variables=dict(x="x", y="y", hue=x_str),
+        )
+        ax.clear()
+        p.plot(ax, {})
+
+        p = _ScatterPlotter(
+            data=long_df, variables=dict(x="x", y="y", size=x_str),
+        )
+        ax.clear()
+        p.plot(ax, {})
+
+    def test_axis_labels(self, long_df):
+
+        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
+
+        p = _ScatterPlotter(data=long_df, variables=dict(x="x", y="y"))
+
+        p.plot(ax1, {})
+        assert ax1.get_xlabel() == "x"
+        assert ax1.get_ylabel() == "y"
+
+        p.plot(ax2, {})
+        assert ax2.get_xlabel() == "x"
+        assert ax2.get_ylabel() == "y"
+        assert not ax2.yaxis.label.get_visible()
+
+    def test_scatterplot_axes(self, wide_df):
+
+        f1, ax1 = plt.subplots()
+        f2, ax2 = plt.subplots()
+
+        ax = scatterplot(data=wide_df)
+        assert ax is ax2
+
+        ax = scatterplot(data=wide_df, ax=ax1)
+        assert ax is ax1
+
+    def test_literal_attribute_vectors(self):
+
+        f, ax = plt.subplots()
+
+        x = y = [1, 2, 3]
+        s = [5, 10, 15]
+        c = [(1, 1, 0, 1), (1, 0, 1, .5), (.5, 1, 0, 1)]
+
+        scatterplot(x=x, y=y, c=c, s=s, ax=ax)
+
+        points, = ax.collections
+
+        assert_array_equal(points.get_sizes().squeeze(), s)
+        assert_array_equal(points.get_facecolors(), c)
+
+    def test_supplied_color_array(self, long_df):
+
+        cmap = get_colormap("Blues")
+        norm = mpl.colors.Normalize()
+        colors = cmap(norm(long_df["y"].to_numpy()))
+
+        keys = ["c", "fc", "facecolor", "facecolors"]
+
+        for key in keys:
+
+            ax = plt.figure().subplots()
+            scatterplot(data=long_df, x="x", y="y", **{key: colors})
+            _draw_figure(ax.figure)
+            assert_array_equal(ax.collections[0].get_facecolors(), colors)
+
+        ax = plt.figure().subplots()
+        scatterplot(data=long_df, x="x", y="y", c=long_df["y"], cmap=cmap)
+        _draw_figure(ax.figure)
+        assert_array_equal(ax.collections[0].get_facecolors(), colors)
+
+    def test_hue_order(self, long_df):
+
+        order = categorical_order(long_df["a"])
+        unused = order.pop()
+
+        ax = scatterplot(data=long_df, x="x", y="y", hue="a", hue_order=order)
+        points = ax.collections[0]
+        assert (points.get_facecolors()[long_df["a"] == unused] == 0).all()
+        assert [t.get_text() for t in ax.legend_.texts] == order
+
+    def test_linewidths(self, long_df):
+
+        f, ax = plt.subplots()
+
+        scatterplot(data=long_df, x="x", y="y", s=10)
+        scatterplot(data=long_df, x="x", y="y", s=20)
+        points1, points2 = ax.collections
+        assert (
+            points1.get_linewidths().item() < points2.get_linewidths().item()
+        )
+
+        ax.clear()
+        scatterplot(data=long_df, x="x", y="y", s=long_df["x"])
+        scatterplot(data=long_df, x="x", y="y", s=long_df["x"] * 2)
+        points1, points2 = ax.collections
+        assert (
+            points1.get_linewidths().item() < points2.get_linewidths().item()
+        )
+
+        ax.clear()
+        scatterplot(data=long_df, x="x", y="y", size=long_df["x"])
+        scatterplot(data=long_df, x="x", y="y", size=long_df["x"] * 2)
+        points1, points2, *_ = ax.collections
+        assert (
+            points1.get_linewidths().item() < points2.get_linewidths().item()
+        )
+
+        ax.clear()
+        lw = 2
+        scatterplot(data=long_df, x="x", y="y", linewidth=lw)
+        assert ax.collections[0].get_linewidths().item() == lw
+
+    def test_size_norm_extrapolation(self):
+
+        # https://github.com/mwaskom/seaborn/issues/2539
+        x = np.arange(0, 20, 2)
+        f, axs = plt.subplots(1, 2, sharex=True, sharey=True)
+
+        slc = 5
+        kws = dict(sizes=(50, 200), size_norm=(0, x.max()), legend="brief")
+
+        scatterplot(x=x, y=x, size=x, ax=axs[0], **kws)
+        scatterplot(x=x[:slc], y=x[:slc], size=x[:slc], ax=axs[1], **kws)
+
+        assert np.allclose(
+            axs[0].collections[0].get_sizes()[:slc],
+            axs[1].collections[0].get_sizes()
+        )
+
+        legends = [ax.legend_ for ax in axs]
+        legend_data = [
+            {
+                label.get_text(): handle.get_sizes().item()
+                for label, handle in zip(legend.get_texts(), legend.legendHandles)
+            } for legend in legends
+        ]
+
+        for key in set(legend_data[0]) & set(legend_data[1]):
+            if key == "y":
+                # At some point (circa 3.0) matplotlib auto-added pandas series
+                # with a valid name into the legend, which messes up this test.
+                # I can't track down when that was added (or removed), so let's
+                # just anticipate and ignore it here.
+                continue
+            assert legend_data[0][key] == legend_data[1][key]
+
+    def test_datetime_scale(self, long_df):
+
+        ax = scatterplot(data=long_df, x="t", y="y")
+        # Check that we avoid weird matplotlib default auto scaling
+        # https://github.com/matplotlib/matplotlib/issues/17586
+        ax.get_xlim()[0] > ax.xaxis.convert_units(np.datetime64("2002-01-01"))
+
+    def test_unfilled_marker_edgecolor_warning(self, long_df):  # GH2636
+
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            scatterplot(data=long_df, x="x", y="y", marker="+")
+
+    def test_scatterplot_vs_relplot(self, long_df, long_semantics):
+
+        ax = scatterplot(data=long_df, **long_semantics)
+        g = relplot(data=long_df, kind="scatter", **long_semantics)
+
+        for s_pts, r_pts in zip(ax.collections, g.ax.collections):
+
+            assert_array_equal(s_pts.get_offsets(), r_pts.get_offsets())
+            assert_array_equal(s_pts.get_sizes(), r_pts.get_sizes())
+            assert_array_equal(s_pts.get_facecolors(), r_pts.get_facecolors())
+            assert self.paths_equal(s_pts.get_paths(), r_pts.get_paths())
+
+    def test_scatterplot_smoke(
+        self,
+        wide_df, wide_array,
+        flat_series, flat_array, flat_list,
+        wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,
+        long_df, missing_df, object_df
+    ):
+
+        f, ax = plt.subplots()
+
+        scatterplot(x=[], y=[])
+        ax.clear()
+
+        scatterplot(data=wide_df)
+        ax.clear()
+
+        scatterplot(data=wide_array)
+        ax.clear()
+
+        scatterplot(data=wide_list_of_series)
+        ax.clear()
+
+        scatterplot(data=wide_list_of_arrays)
+        ax.clear()
+
+        scatterplot(data=wide_list_of_lists)
+        ax.clear()
+
+        scatterplot(data=flat_series)
+        ax.clear()
+
+        scatterplot(data=flat_array)
+        ax.clear()
+
+        scatterplot(data=flat_list)
+        ax.clear()
+
+        scatterplot(x="x", y="y", data=long_df)
+        ax.clear()
+
+        scatterplot(x=long_df.x, y=long_df.y)
+        ax.clear()
+
+        scatterplot(x=long_df.x, y="y", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y=long_df.y.to_numpy(), data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", style="a", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", style="b", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", style="a", data=missing_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", style="b", data=missing_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", size="a", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", size="s", data=long_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", size="a", data=missing_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="a", size="s", data=missing_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="f", data=object_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="c", size="f", data=object_df)
+        ax.clear()
+
+        scatterplot(x="x", y="y", hue="f", size="s", data=object_df)
+        ax.clear()
diff --git a/testbed/mwaskom__seaborn/tests/test_statistics.py b/testbed/mwaskom__seaborn/tests/test_statistics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e39127882afd32c9a56d3dc7f0ef8eab931ed4b6
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_statistics.py
@@ -0,0 +1,618 @@
+import numpy as np
+import pandas as pd
+
+try:
+    import statsmodels.distributions as smdist
+except ImportError:
+    smdist = None
+
+import pytest
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+from seaborn._statistics import (
+    KDE,
+    Histogram,
+    ECDF,
+    EstimateAggregator,
+    _validate_errorbar_arg,
+    _no_scipy,
+)
+
+
+class DistributionFixtures:
+
+    @pytest.fixture
+    def x(self, rng):
+        return rng.normal(0, 1, 100)
+
+    @pytest.fixture
+    def y(self, rng):
+        return rng.normal(0, 5, 100)
+
+    @pytest.fixture
+    def weights(self, rng):
+        return rng.uniform(0, 5, 100)
+
+
+class TestKDE:
+
+    def integrate(self, y, x):
+        y = np.asarray(y)
+        x = np.asarray(x)
+        dx = np.diff(x)
+        return (dx * y[:-1] + dx * y[1:]).sum() / 2
+
+    def test_gridsize(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+
+        n = 200
+        kde = KDE(gridsize=n)
+        density, support = kde(x)
+        assert density.size == n
+        assert support.size == n
+
+    def test_cut(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+
+        kde = KDE(cut=0)
+        _, support = kde(x)
+        assert support.min() == x.min()
+        assert support.max() == x.max()
+
+        cut = 2
+        bw_scale = .5
+        bw = x.std() * bw_scale
+        kde = KDE(cut=cut, bw_method=bw_scale, gridsize=1000)
+        _, support = kde(x)
+        assert support.min() == pytest.approx(x.min() - bw * cut, abs=1e-2)
+        assert support.max() == pytest.approx(x.max() + bw * cut, abs=1e-2)
+
+    def test_clip(self, rng):
+
+        x = rng.normal(0, 3, 100)
+        clip = -1, 1
+        kde = KDE(clip=clip)
+        _, support = kde(x)
+
+        assert support.min() >= clip[0]
+        assert support.max() <= clip[1]
+
+    def test_density_normalization(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+        kde = KDE()
+        density, support = kde(x)
+        assert self.integrate(density, support) == pytest.approx(1, abs=1e-5)
+
+    @pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
+    def test_cumulative(self, rng):
+
+        x = rng.normal(0, 3, 1000)
+        kde = KDE(cumulative=True)
+        density, _ = kde(x)
+        assert density[0] == pytest.approx(0, abs=1e-5)
+        assert density[-1] == pytest.approx(1, abs=1e-5)
+
+    def test_cached_support(self, rng):
+
+        x = rng.normal(0, 3, 100)
+        kde = KDE()
+        kde.define_support(x)
+        _, support = kde(x[(x > -1) & (x < 1)])
+        assert_array_equal(support, kde.support)
+
+    def test_bw_method(self, rng):
+
+        x = rng.normal(0, 3, 100)
+        kde1 = KDE(bw_method=.2)
+        kde2 = KDE(bw_method=2)
+
+        d1, _ = kde1(x)
+        d2, _ = kde2(x)
+
+        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()
+
+    def test_bw_adjust(self, rng):
+
+        x = rng.normal(0, 3, 100)
+        kde1 = KDE(bw_adjust=.2)
+        kde2 = KDE(bw_adjust=2)
+
+        d1, _ = kde1(x)
+        d2, _ = kde2(x)
+
+        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()
+
+    def test_bivariate_grid(self, rng):
+
+        n = 100
+        x, y = rng.normal(0, 3, (2, 50))
+        kde = KDE(gridsize=n)
+        density, (xx, yy) = kde(x, y)
+
+        assert density.shape == (n, n)
+        assert xx.size == n
+        assert yy.size == n
+
+    def test_bivariate_normalization(self, rng):
+
+        x, y = rng.normal(0, 3, (2, 50))
+        kde = KDE(gridsize=100)
+        density, (xx, yy) = kde(x, y)
+
+        dx = xx[1] - xx[0]
+        dy = yy[1] - yy[0]
+
+        total = density.sum() * (dx * dy)
+        assert total == pytest.approx(1, abs=1e-2)
+
+    @pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
+    def test_bivariate_cumulative(self, rng):
+
+        x, y = rng.normal(0, 3, (2, 50))
+        kde = KDE(gridsize=100, cumulative=True)
+        density, _ = kde(x, y)
+
+        assert density[0, 0] == pytest.approx(0, abs=1e-2)
+        assert density[-1, -1] == pytest.approx(1, abs=1e-2)
+
+
+class TestHistogram(DistributionFixtures):
+
+    def test_string_bins(self, x):
+
+        h = Histogram(bins="sqrt")
+        bin_kws = h.define_bin_params(x)
+        assert bin_kws["range"] == (x.min(), x.max())
+        assert bin_kws["bins"] == int(np.sqrt(len(x)))
+
+    def test_int_bins(self, x):
+
+        n = 24
+        h = Histogram(bins=n)
+        bin_kws = h.define_bin_params(x)
+        assert bin_kws["range"] == (x.min(), x.max())
+        assert bin_kws["bins"] == n
+
+    def test_array_bins(self, x):
+
+        bins = [-3, -2, 1, 2, 3]
+        h = Histogram(bins=bins)
+        bin_kws = h.define_bin_params(x)
+        assert_array_equal(bin_kws["bins"], bins)
+
+    def test_bivariate_string_bins(self, x, y):
+
+        s1, s2 = "sqrt", "fd"
+
+        h = Histogram(bins=s1)
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert_array_equal(e1, np.histogram_bin_edges(x, s1))
+        assert_array_equal(e2, np.histogram_bin_edges(y, s1))
+
+        h = Histogram(bins=(s1, s2))
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert_array_equal(e1, np.histogram_bin_edges(x, s1))
+        assert_array_equal(e2, np.histogram_bin_edges(y, s2))
+
+    def test_bivariate_int_bins(self, x, y):
+
+        b1, b2 = 5, 10
+
+        h = Histogram(bins=b1)
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert len(e1) == b1 + 1
+        assert len(e2) == b1 + 1
+
+        h = Histogram(bins=(b1, b2))
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert len(e1) == b1 + 1
+        assert len(e2) == b2 + 1
+
+    def test_bivariate_array_bins(self, x, y):
+
+        b1 = [-3, -2, 1, 2, 3]
+        b2 = [-5, -2, 3, 6]
+
+        h = Histogram(bins=b1)
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert_array_equal(e1, b1)
+        assert_array_equal(e2, b1)
+
+        h = Histogram(bins=(b1, b2))
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert_array_equal(e1, b1)
+        assert_array_equal(e2, b2)
+
+    def test_binwidth(self, x):
+
+        binwidth = .5
+        h = Histogram(binwidth=binwidth)
+        bin_kws = h.define_bin_params(x)
+        n_bins = bin_kws["bins"]
+        left, right = bin_kws["range"]
+        assert (right - left) / n_bins == pytest.approx(binwidth)
+
+    def test_bivariate_binwidth(self, x, y):
+
+        w1, w2 = .5, 1
+
+        h = Histogram(binwidth=w1)
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert np.all(np.diff(e1) == w1)
+        assert np.all(np.diff(e2) == w1)
+
+        h = Histogram(binwidth=(w1, w2))
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert np.all(np.diff(e1) == w1)
+        assert np.all(np.diff(e2) == w2)
+
+    def test_binrange(self, x):
+
+        binrange = (-4, 4)
+        h = Histogram(binrange=binrange)
+        bin_kws = h.define_bin_params(x)
+        assert bin_kws["range"] == binrange
+
+    def test_bivariate_binrange(self, x, y):
+
+        r1, r2 = (-4, 4), (-10, 10)
+
+        h = Histogram(binrange=r1)
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert e1.min() == r1[0]
+        assert e1.max() == r1[1]
+        assert e2.min() == r1[0]
+        assert e2.max() == r1[1]
+
+        h = Histogram(binrange=(r1, r2))
+        e1, e2 = h.define_bin_params(x, y)["bins"]
+        assert e1.min() == r1[0]
+        assert e1.max() == r1[1]
+        assert e2.min() == r2[0]
+        assert e2.max() == r2[1]
+
+    def test_discrete_bins(self, rng):
+
+        x = rng.binomial(20, .5, 100)
+        h = Histogram(discrete=True)
+        bin_kws = h.define_bin_params(x)
+        assert bin_kws["range"] == (x.min() - .5, x.max() + .5)
+        assert bin_kws["bins"] == (x.max() - x.min() + 1)
+
+    def test_odd_single_observation(self):
+        # GH2721
+        x = np.array([0.49928])
+        h, e = Histogram(binwidth=0.03)(x)
+        assert len(h) == 1
+        assert (e[1] - e[0]) == pytest.approx(.03)
+
+    def test_binwidth_roundoff(self):
+        # GH2785
+        x = np.array([2.4, 2.5, 2.6])
+        h, e = Histogram(binwidth=0.01)(x)
+        assert h.sum() == 3
+
+    def test_histogram(self, x):
+
+        h = Histogram()
+        heights, edges = h(x)
+        heights_mpl, edges_mpl = np.histogram(x, bins="auto")
+
+        assert_array_equal(heights, heights_mpl)
+        assert_array_equal(edges, edges_mpl)
+
+    def test_count_stat(self, x):
+
+        h = Histogram(stat="count")
+        heights, _ = h(x)
+        assert heights.sum() == len(x)
+
+    def test_density_stat(self, x):
+
+        h = Histogram(stat="density")
+        heights, edges = h(x)
+        assert (heights * np.diff(edges)).sum() == 1
+
+    def test_probability_stat(self, x):
+
+        h = Histogram(stat="probability")
+        heights, _ = h(x)
+        assert heights.sum() == 1
+
+    def test_frequency_stat(self, x):
+
+        h = Histogram(stat="frequency")
+        heights, edges = h(x)
+        assert (heights * np.diff(edges)).sum() == len(x)
+
+    def test_cumulative_count(self, x):
+
+        h = Histogram(stat="count", cumulative=True)
+        heights, _ = h(x)
+        assert heights[-1] == len(x)
+
+    def test_cumulative_density(self, x):
+
+        h = Histogram(stat="density", cumulative=True)
+        heights, _ = h(x)
+        assert heights[-1] == 1
+
+    def test_cumulative_probability(self, x):
+
+        h = Histogram(stat="probability", cumulative=True)
+        heights, _ = h(x)
+        assert heights[-1] == 1
+
+    def test_cumulative_frequency(self, x):
+
+        h = Histogram(stat="frequency", cumulative=True)
+        heights, _ = h(x)
+        assert heights[-1] == len(x)
+
+    def test_bivariate_histogram(self, x, y):
+
+        h = Histogram()
+        heights, edges = h(x, y)
+        bins_mpl = (
+            np.histogram_bin_edges(x, "auto"),
+            np.histogram_bin_edges(y, "auto"),
+        )
+        heights_mpl, *edges_mpl = np.histogram2d(x, y, bins_mpl)
+        assert_array_equal(heights, heights_mpl)
+        assert_array_equal(edges[0], edges_mpl[0])
+        assert_array_equal(edges[1], edges_mpl[1])
+
+    def test_bivariate_count_stat(self, x, y):
+
+        h = Histogram(stat="count")
+        heights, _ = h(x, y)
+        assert heights.sum() == len(x)
+
+    def test_bivariate_density_stat(self, x, y):
+
+        h = Histogram(stat="density")
+        heights, (edges_x, edges_y) = h(x, y)
+        areas = np.outer(np.diff(edges_x), np.diff(edges_y))
+        assert (heights * areas).sum() == pytest.approx(1)
+
+    def test_bivariate_probability_stat(self, x, y):
+
+        h = Histogram(stat="probability")
+        heights, _ = h(x, y)
+        assert heights.sum() == 1
+
+    def test_bivariate_frequency_stat(self, x, y):
+
+        h = Histogram(stat="frequency")
+        heights, (x_edges, y_edges) = h(x, y)
+        area = np.outer(np.diff(x_edges), np.diff(y_edges))
+        assert (heights * area).sum() == len(x)
+
+    def test_bivariate_cumulative_count(self, x, y):
+
+        h = Histogram(stat="count", cumulative=True)
+        heights, _ = h(x, y)
+        assert heights[-1, -1] == len(x)
+
+    def test_bivariate_cumulative_density(self, x, y):
+
+        h = Histogram(stat="density", cumulative=True)
+        heights, _ = h(x, y)
+        assert heights[-1, -1] == pytest.approx(1)
+
+    def test_bivariate_cumulative_frequency(self, x, y):
+
+        h = Histogram(stat="frequency", cumulative=True)
+        heights, _ = h(x, y)
+        assert heights[-1, -1] == len(x)
+
+    def test_bivariate_cumulative_probability(self, x, y):
+
+        h = Histogram(stat="probability", cumulative=True)
+        heights, _ = h(x, y)
+        assert heights[-1, -1] == pytest.approx(1)
+
+    def test_bad_stat(self):
+
+        with pytest.raises(ValueError):
+            Histogram(stat="invalid")
+
+
+class TestECDF(DistributionFixtures):
+
+    def test_univariate_proportion(self, x):
+
+        ecdf = ECDF()
+        stat, vals = ecdf(x)
+        assert_array_equal(vals[1:], np.sort(x))
+        assert_array_almost_equal(stat[1:], np.linspace(0, 1, len(x) + 1)[1:])
+        assert stat[0] == 0
+
+    def test_univariate_count(self, x):
+
+        ecdf = ECDF(stat="count")
+        stat, vals = ecdf(x)
+
+        assert_array_equal(vals[1:], np.sort(x))
+        assert_array_almost_equal(stat[1:], np.arange(len(x)) + 1)
+        assert stat[0] == 0
+
+    def test_univariate_proportion_weights(self, x, weights):
+
+        ecdf = ECDF()
+        stat, vals = ecdf(x, weights=weights)
+        assert_array_equal(vals[1:], np.sort(x))
+        expected_stats = weights[x.argsort()].cumsum() / weights.sum()
+        assert_array_almost_equal(stat[1:], expected_stats)
+        assert stat[0] == 0
+
+    def test_univariate_count_weights(self, x, weights):
+
+        ecdf = ECDF(stat="count")
+        stat, vals = ecdf(x, weights=weights)
+        assert_array_equal(vals[1:], np.sort(x))
+        assert_array_almost_equal(stat[1:], weights[x.argsort()].cumsum())
+        assert stat[0] == 0
+
+    @pytest.mark.skipif(smdist is None, reason="Requires statsmodels")
+    def test_against_statsmodels(self, x):
+
+        sm_ecdf = smdist.empirical_distribution.ECDF(x)
+
+        ecdf = ECDF()
+        stat, vals = ecdf(x)
+        assert_array_equal(vals, sm_ecdf.x)
+        assert_array_almost_equal(stat, sm_ecdf.y)
+
+        ecdf = ECDF(complementary=True)
+        stat, vals = ecdf(x)
+        assert_array_equal(vals, sm_ecdf.x)
+        assert_array_almost_equal(stat, sm_ecdf.y[::-1])
+
+    def test_invalid_stat(self, x):
+
+        with pytest.raises(ValueError, match="`stat` must be one of"):
+            ECDF(stat="density")
+
+    def test_bivariate_error(self, x, y):
+
+        with pytest.raises(NotImplementedError, match="Bivariate ECDF"):
+            ecdf = ECDF()
+            ecdf(x, y)
+
+
+class TestEstimateAggregator:
+
+    def test_func_estimator(self, long_df):
+
+        func = np.mean
+        agg = EstimateAggregator(func)
+        out = agg(long_df, "x")
+        assert out["x"] == func(long_df["x"])
+
+    def test_name_estimator(self, long_df):
+
+        agg = EstimateAggregator("mean")
+        out = agg(long_df, "x")
+        assert out["x"] == long_df["x"].mean()
+
+    def test_custom_func_estimator(self, long_df):
+
+        def func(x):
+            return np.asarray(x).min()
+
+        agg = EstimateAggregator(func)
+        out = agg(long_df, "x")
+        assert out["x"] == func(long_df["x"])
+
+    def test_se_errorbars(self, long_df):
+
+        agg = EstimateAggregator("mean", "se")
+        out = agg(long_df, "x")
+        assert out["x"] == long_df["x"].mean()
+        assert out["xmin"] == (long_df["x"].mean() - long_df["x"].sem())
+        assert out["xmax"] == (long_df["x"].mean() + long_df["x"].sem())
+
+        agg = EstimateAggregator("mean", ("se", 2))
+        out = agg(long_df, "x")
+        assert out["x"] == long_df["x"].mean()
+        assert out["xmin"] == (long_df["x"].mean() - 2 * long_df["x"].sem())
+        assert out["xmax"] == (long_df["x"].mean() + 2 * long_df["x"].sem())
+
+    def test_sd_errorbars(self, long_df):
+
+        agg = EstimateAggregator("mean", "sd")
+        out = agg(long_df, "x")
+        assert out["x"] == long_df["x"].mean()
+        assert out["xmin"] == (long_df["x"].mean() - long_df["x"].std())
+        assert out["xmax"] == (long_df["x"].mean() + long_df["x"].std())
+
+        agg = EstimateAggregator("mean", ("sd", 2))
+        out = agg(long_df, "x")
+        assert out["x"] == long_df["x"].mean()
+        assert out["xmin"] == (long_df["x"].mean() - 2 * long_df["x"].std())
+        assert out["xmax"] == (long_df["x"].mean() + 2 * long_df["x"].std())
+
+    def test_pi_errorbars(self, long_df):
+
+        agg = EstimateAggregator("mean", "pi")
+        out = agg(long_df, "y")
+        assert out["ymin"] == np.percentile(long_df["y"], 2.5)
+        assert out["ymax"] == np.percentile(long_df["y"], 97.5)
+
+        agg = EstimateAggregator("mean", ("pi", 50))
+        out = agg(long_df, "y")
+        assert out["ymin"] == np.percentile(long_df["y"], 25)
+        assert out["ymax"] == np.percentile(long_df["y"], 75)
+
+    def test_ci_errorbars(self, long_df):
+
+        agg = EstimateAggregator("mean", "ci", n_boot=100000, seed=0)
+        out = agg(long_df, "y")
+
+        agg_ref = EstimateAggregator("mean", ("se", 1.96))
+        out_ref = agg_ref(long_df, "y")
+
+        assert out["ymin"] == pytest.approx(out_ref["ymin"], abs=1e-2)
+        assert out["ymax"] == pytest.approx(out_ref["ymax"], abs=1e-2)
+
+        agg = EstimateAggregator("mean", ("ci", 68), n_boot=100000, seed=0)
+        out = agg(long_df, "y")
+
+        agg_ref = EstimateAggregator("mean", ("se", 1))
+        out_ref = agg_ref(long_df, "y")
+
+        assert out["ymin"] == pytest.approx(out_ref["ymin"], abs=1e-2)
+        assert out["ymax"] == pytest.approx(out_ref["ymax"], abs=1e-2)
+
+        agg = EstimateAggregator("mean", "ci", seed=0)
+        out_orig = agg_ref(long_df, "y")
+        out_test = agg_ref(long_df, "y")
+        assert_array_equal(out_orig, out_test)
+
+    def test_custom_errorbars(self, long_df):
+
+        f = lambda x: (x.min(), x.max())  # noqa: E731
+        agg = EstimateAggregator("mean", f)
+        out = agg(long_df, "y")
+        assert out["ymin"] == long_df["y"].min()
+        assert out["ymax"] == long_df["y"].max()
+
+    def test_singleton_errorbars(self):
+
+        agg = EstimateAggregator("mean", "ci")
+        val = 7
+        out = agg(pd.DataFrame(dict(y=[val])), "y")
+        assert out["y"] == val
+        assert pd.isna(out["ymin"])
+        assert pd.isna(out["ymax"])
+
+    def test_errorbar_validation(self):
+
+        method, level = _validate_errorbar_arg(("ci", 99))
+        assert method == "ci"
+        assert level == 99
+
+        method, level = _validate_errorbar_arg("sd")
+        assert method == "sd"
+        assert level == 1
+
+        f = lambda x: (x.min(), x.max())  # noqa: E731
+        method, level = _validate_errorbar_arg(f)
+        assert method is f
+        assert level is None
+
+        bad_args = [
+            ("sem", ValueError),
+            (("std", 2), ValueError),
+            (("pi", 5, 95), ValueError),
+            (95, TypeError),
+            (("ci", "large"), TypeError),
+        ]
+
+        for arg, exception in bad_args:
+            with pytest.raises(exception, match="`errorbar` must be"):
+                _validate_errorbar_arg(arg)
diff --git a/testbed/mwaskom__seaborn/tests/test_utils.py b/testbed/mwaskom__seaborn/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab0e02392c0d76b50abfc7943cabd1567e12dcee
--- /dev/null
+++ b/testbed/mwaskom__seaborn/tests/test_utils.py
@@ -0,0 +1,588 @@
+"""Tests for seaborn utility functions."""
+import re
+import tempfile
+from types import ModuleType
+from urllib.request import urlopen
+from http.client import HTTPException
+
+import numpy as np
+import pandas as pd
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from cycler import cycler
+
+import pytest
+from numpy.testing import (
+    assert_array_equal,
+)
+from pandas.testing import (
+    assert_series_equal,
+    assert_frame_equal,
+)
+
+from seaborn import utils, rcmod
+from seaborn.utils import (
+    get_dataset_names,
+    get_color_cycle,
+    remove_na,
+    load_dataset,
+    _assign_default_kwargs,
+    _draw_figure,
+    _deprecate_ci,
+    _version_predates,
+)
+
+
+a_norm = np.random.randn(100)
+
+
+def _network(t=None, url="https://github.com"):
+    """
+    Decorator that will skip a test if `url` is unreachable.
+
+    Parameters
+    ----------
+    t : function, optional
+    url : str, optional
+
+    """
+    if t is None:
+        return lambda x: _network(x, url=url)
+
+    def wrapper(*args, **kwargs):
+        # attempt to connect
+        try:
+            f = urlopen(url)
+        except (OSError, HTTPException):
+            pytest.skip("No internet connection")
+        else:
+            f.close()
+            return t(*args, **kwargs)
+    return wrapper
+
+
+def test_ci_to_errsize():
+    """Test behavior of ci_to_errsize."""
+    cis = [[.5, .5],
+           [1.25, 1.5]]
+
+    heights = [1, 1.5]
+
+    actual_errsize = np.array([[.5, 1],
+                               [.25, 0]])
+
+    test_errsize = utils.ci_to_errsize(cis, heights)
+    assert_array_equal(actual_errsize, test_errsize)
+
+
+def test_desaturate():
+    """Test color desaturation."""
+    out1 = utils.desaturate("red", .5)
+    assert out1 == (.75, .25, .25)
+
+    out2 = utils.desaturate("#00FF00", .5)
+    assert out2 == (.25, .75, .25)
+
+    out3 = utils.desaturate((0, 0, 1), .5)
+    assert out3 == (.25, .25, .75)
+
+    out4 = utils.desaturate("red", .5)
+    assert out4 == (.75, .25, .25)
+
+
+def test_desaturation_prop():
+    """Test that pct outside of [0, 1] raises exception."""
+    with pytest.raises(ValueError):
+        utils.desaturate("blue", 50)
+
+
+def test_saturate():
+    """Test performance of saturation function."""
+    out = utils.saturate((.75, .25, .25))
+    assert out == (1, 0, 0)
+
+
+@pytest.mark.parametrize(
+    "s,exp",
+    [
+        ("a", "a"),
+        ("abc", "abc"),
+        (b"a", "a"),
+        (b"abc", "abc"),
+        (bytearray("abc", "utf-8"), "abc"),
+        (bytearray(), ""),
+        (1, "1"),
+        (0, "0"),
+        ([], str([])),
+    ],
+)
+def test_to_utf8(s, exp):
+    """Test the to_utf8 function: object to string"""
+    u = utils.to_utf8(s)
+    assert type(u) == str
+    assert u == exp
+
+
+class TestSpineUtils:
+
+    sides = ["left", "right", "bottom", "top"]
+    outer_sides = ["top", "right"]
+    inner_sides = ["left", "bottom"]
+
+    offset = 10
+    original_position = ("outward", 0)
+    offset_position = ("outward", offset)
+
+    def test_despine(self):
+        f, ax = plt.subplots()
+        for side in self.sides:
+            assert ax.spines[side].get_visible()
+
+        utils.despine()
+        for side in self.outer_sides:
+            assert ~ax.spines[side].get_visible()
+        for side in self.inner_sides:
+            assert ax.spines[side].get_visible()
+
+        utils.despine(**dict(zip(self.sides, [True] * 4)))
+        for side in self.sides:
+            assert ~ax.spines[side].get_visible()
+
+    def test_despine_specific_axes(self):
+        f, (ax1, ax2) = plt.subplots(2, 1)
+
+        utils.despine(ax=ax2)
+
+        for side in self.sides:
+            assert ax1.spines[side].get_visible()
+
+        for side in self.outer_sides:
+            assert ~ax2.spines[side].get_visible()
+        for side in self.inner_sides:
+            assert ax2.spines[side].get_visible()
+
+    def test_despine_with_offset(self):
+        f, ax = plt.subplots()
+
+        for side in self.sides:
+            pos = ax.spines[side].get_position()
+            assert pos == self.original_position
+
+        utils.despine(ax=ax, offset=self.offset)
+
+        for side in self.sides:
+            is_visible = ax.spines[side].get_visible()
+            new_position = ax.spines[side].get_position()
+            if is_visible:
+                assert new_position == self.offset_position
+            else:
+                assert new_position == self.original_position
+
+    def test_despine_side_specific_offset(self):
+
+        f, ax = plt.subplots()
+        utils.despine(ax=ax, offset=dict(left=self.offset))
+
+        for side in self.sides:
+            is_visible = ax.spines[side].get_visible()
+            new_position = ax.spines[side].get_position()
+            if is_visible and side == "left":
+                assert new_position == self.offset_position
+            else:
+                assert new_position == self.original_position
+
+    def test_despine_with_offset_specific_axes(self):
+        f, (ax1, ax2) = plt.subplots(2, 1)
+
+        utils.despine(offset=self.offset, ax=ax2)
+
+        for side in self.sides:
+            pos1 = ax1.spines[side].get_position()
+            pos2 = ax2.spines[side].get_position()
+            assert pos1 == self.original_position
+            if ax2.spines[side].get_visible():
+                assert pos2 == self.offset_position
+            else:
+                assert pos2 == self.original_position
+
+    def test_despine_trim_spines(self):
+
+        f, ax = plt.subplots()
+        ax.plot([1, 2, 3], [1, 2, 3])
+        ax.set_xlim(.75, 3.25)
+
+        utils.despine(trim=True)
+        for side in self.inner_sides:
+            bounds = ax.spines[side].get_bounds()
+            assert bounds == (1, 3)
+
+    def test_despine_trim_inverted(self):
+
+        f, ax = plt.subplots()
+        ax.plot([1, 2, 3], [1, 2, 3])
+        ax.set_ylim(.85, 3.15)
+        ax.invert_yaxis()
+
+        utils.despine(trim=True)
+        for side in self.inner_sides:
+            bounds = ax.spines[side].get_bounds()
+            assert bounds == (1, 3)
+
+    def test_despine_trim_noticks(self):
+
+        f, ax = plt.subplots()
+        ax.plot([1, 2, 3], [1, 2, 3])
+        ax.set_yticks([])
+        utils.despine(trim=True)
+        assert ax.get_yticks().size == 0
+
+    def test_despine_trim_categorical(self):
+
+        f, ax = plt.subplots()
+        ax.plot(["a", "b", "c"], [1, 2, 3])
+
+        utils.despine(trim=True)
+
+        bounds = ax.spines["left"].get_bounds()
+        assert bounds == (1, 3)
+
+        bounds = ax.spines["bottom"].get_bounds()
+        assert bounds == (0, 2)
+
+    def test_despine_moved_ticks(self):
+
+        f, ax = plt.subplots()
+        for t in ax.yaxis.majorTicks:
+            t.tick1line.set_visible(True)
+        utils.despine(ax=ax, left=True, right=False)
+        for t in ax.yaxis.majorTicks:
+            assert t.tick2line.get_visible()
+        plt.close(f)
+
+        f, ax = plt.subplots()
+        for t in ax.yaxis.majorTicks:
+            t.tick1line.set_visible(False)
+        utils.despine(ax=ax, left=True, right=False)
+        for t in ax.yaxis.majorTicks:
+            assert not t.tick2line.get_visible()
+        plt.close(f)
+
+        f, ax = plt.subplots()
+        for t in ax.xaxis.majorTicks:
+            t.tick1line.set_visible(True)
+        utils.despine(ax=ax, bottom=True, top=False)
+        for t in ax.xaxis.majorTicks:
+            assert t.tick2line.get_visible()
+        plt.close(f)
+
+        f, ax = plt.subplots()
+        for t in ax.xaxis.majorTicks:
+            t.tick1line.set_visible(False)
+        utils.despine(ax=ax, bottom=True, top=False)
+        for t in ax.xaxis.majorTicks:
+            assert not t.tick2line.get_visible()
+        plt.close(f)
+
+
+def test_ticklabels_overlap():
+
+    rcmod.set()
+    f, ax = plt.subplots(figsize=(2, 2))
+    f.tight_layout()  # This gets the Agg renderer working
+
+    assert not utils.axis_ticklabels_overlap(ax.get_xticklabels())
+
+    big_strings = "abcdefgh", "ijklmnop"
+    ax.set_xlim(-.5, 1.5)
+    ax.set_xticks([0, 1])
+    ax.set_xticklabels(big_strings)
+
+    assert utils.axis_ticklabels_overlap(ax.get_xticklabels())
+
+    x, y = utils.axes_ticklabels_overlap(ax)
+    assert x
+    assert not y
+
+
+def test_locator_to_legend_entries():
+
+    locator = mpl.ticker.MaxNLocator(nbins=3)
+    limits = (0.09, 0.4)
+    levels, str_levels = utils.locator_to_legend_entries(
+        locator, limits, float
+    )
+    assert str_levels == ["0.15", "0.30"]
+
+    limits = (0.8, 0.9)
+    levels, str_levels = utils.locator_to_legend_entries(
+        locator, limits, float
+    )
+    assert str_levels == ["0.80", "0.84", "0.88"]
+
+    limits = (1, 6)
+    levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)
+    assert str_levels == ["2", "4", "6"]
+
+    locator = mpl.ticker.LogLocator(numticks=5)
+    limits = (5, 1425)
+    levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)
+    assert str_levels == ['10', '100', '1000']
+
+    limits = (0.00003, 0.02)
+    _, str_levels = utils.locator_to_legend_entries(locator, limits, float)
+    for i, exp in enumerate([4, 3, 2]):
+        # Use regex as mpl switched to minus sign, not hyphen, in 3.6
+        assert re.match(f"1e.0{exp}", str_levels[i])
+
+
+def test_move_legend_matplotlib_objects():
+
+    fig, ax = plt.subplots()
+
+    colors = "C2", "C5"
+    labels = "first label", "second label"
+    title = "the legend"
+
+    for color, label in zip(colors, labels):
+        ax.plot([0, 1], color=color, label=label)
+    ax.legend(loc="upper right", title=title)
+    utils._draw_figure(fig)
+    xfm = ax.transAxes.inverted().transform
+
+    # --- Test axes legend
+
+    old_pos = xfm(ax.legend_.legendPatch.get_extents())
+
+    new_fontsize = 14
+    utils.move_legend(ax, "lower left", title_fontsize=new_fontsize)
+    utils._draw_figure(fig)
+    new_pos = xfm(ax.legend_.legendPatch.get_extents())
+
+    assert (new_pos < old_pos).all()
+    assert ax.legend_.get_title().get_text() == title
+    assert ax.legend_.get_title().get_size() == new_fontsize
+
+    # --- Test title replacement
+
+    new_title = "new title"
+    utils.move_legend(ax, "lower left", title=new_title)
+    utils._draw_figure(fig)
+    assert ax.legend_.get_title().get_text() == new_title
+
+    # --- Test figure legend
+
+    fig.legend(loc="upper right", title=title)
+    _draw_figure(fig)
+    xfm = fig.transFigure.inverted().transform
+    old_pos = xfm(fig.legends[0].legendPatch.get_extents())
+
+    utils.move_legend(fig, "lower left", title=new_title)
+    _draw_figure(fig)
+
+    new_pos = xfm(fig.legends[0].legendPatch.get_extents())
+    assert (new_pos < old_pos).all()
+    assert fig.legends[0].get_title().get_text() == new_title
+
+
+def test_move_legend_grid_object(long_df):
+
+    from seaborn.axisgrid import FacetGrid
+
+    hue_var = "a"
+    g = FacetGrid(long_df, hue=hue_var)
+    g.map(plt.plot, "x", "y")
+
+    g.add_legend()
+    _draw_figure(g.figure)
+
+    xfm = g.figure.transFigure.inverted().transform
+    old_pos = xfm(g.legend.legendPatch.get_extents())
+
+    fontsize = 20
+    utils.move_legend(g, "lower left", title_fontsize=fontsize)
+    _draw_figure(g.figure)
+
+    new_pos = xfm(g.legend.legendPatch.get_extents())
+    assert (new_pos < old_pos).all()
+    assert g.legend.get_title().get_text() == hue_var
+    assert g.legend.get_title().get_size() == fontsize
+
+    assert g.legend.legendHandles
+    for i, h in enumerate(g.legend.legendHandles):
+        assert mpl.colors.to_rgb(h.get_color()) == mpl.colors.to_rgb(f"C{i}")
+
+
+def test_move_legend_input_checks():
+
+    ax = plt.figure().subplots()
+    with pytest.raises(TypeError):
+        utils.move_legend(ax.xaxis, "best")
+
+    with pytest.raises(ValueError):
+        utils.move_legend(ax, "best")
+
+    with pytest.raises(ValueError):
+        utils.move_legend(ax.figure, "best")
+
+
+def check_load_dataset(name):
+    ds = load_dataset(name, cache=False)
+    assert isinstance(ds, pd.DataFrame)
+
+
+def check_load_cached_dataset(name):
+    # Test the caching using a temporary file.
+    with tempfile.TemporaryDirectory() as tmpdir:
+        # download and cache
+        ds = load_dataset(name, cache=True, data_home=tmpdir)
+
+        # use cached version
+        ds2 = load_dataset(name, cache=True, data_home=tmpdir)
+        assert_frame_equal(ds, ds2)
+
+
+@_network(url="https://github.com/mwaskom/seaborn-data")
+def test_get_dataset_names():
+    names = get_dataset_names()
+    assert names
+    assert "tips" in names
+
+
+@_network(url="https://github.com/mwaskom/seaborn-data")
+def test_load_datasets():
+
+    # Heavy test to verify that we can load all available datasets
+    for name in get_dataset_names():
+        # unfortunately @network somehow obscures this generator so it
+        # does not get in effect, so we need to call explicitly
+        # yield check_load_dataset, name
+        check_load_dataset(name)
+
+
+@_network(url="https://github.com/mwaskom/seaborn-data")
+def test_load_dataset_string_error():
+
+    name = "bad_name"
+    err = f"'{name}' is not one of the example datasets."
+    with pytest.raises(ValueError, match=err):
+        load_dataset(name)
+
+
+def test_load_dataset_passed_data_error():
+
+    df = pd.DataFrame()
+    err = "This function accepts only strings"
+    with pytest.raises(TypeError, match=err):
+        load_dataset(df)
+
+
+@_network(url="https://github.com/mwaskom/seaborn-data")
+def test_load_cached_datasets():
+
+    # Heavy test to verify that we can load all available datasets
+    for name in get_dataset_names():
+        # unfortunately @network somehow obscures this generator so it
+        # does not get in effect, so we need to call explicitly
+        # yield check_load_dataset, name
+        check_load_cached_dataset(name)
+
+
+def test_relative_luminance():
+    """Test relative luminance."""
+    out1 = utils.relative_luminance("white")
+    assert out1 == 1
+
+    out2 = utils.relative_luminance("#000000")
+    assert out2 == 0
+
+    out3 = utils.relative_luminance((.25, .5, .75))
+    assert out3 == pytest.approx(0.201624536)
+
+    rgbs = mpl.cm.RdBu(np.linspace(0, 1, 10))
+    lums1 = [utils.relative_luminance(rgb) for rgb in rgbs]
+    lums2 = utils.relative_luminance(rgbs)
+
+    for lum1, lum2 in zip(lums1, lums2):
+        assert lum1 == pytest.approx(lum2)
+
+
+@pytest.mark.parametrize(
+    "cycler,result",
+    [
+        (cycler(color=["y"]), ["y"]),
+        (cycler(color=["k"]), ["k"]),
+        (cycler(color=["k", "y"]), ["k", "y"]),
+        (cycler(color=["y", "k"]), ["y", "k"]),
+        (cycler(color=["b", "r"]), ["b", "r"]),
+        (cycler(color=["r", "b"]), ["r", "b"]),
+        (cycler(lw=[1, 2]), [".15"]),  # no color in cycle
+    ],
+)
+def test_get_color_cycle(cycler, result):
+    with mpl.rc_context(rc={"axes.prop_cycle": cycler}):
+        assert get_color_cycle() == result
+
+
+def test_remove_na():
+
+    a_array = np.array([1, 2, np.nan, 3])
+    a_array_rm = remove_na(a_array)
+    assert_array_equal(a_array_rm, np.array([1, 2, 3]))
+
+    a_series = pd.Series([1, 2, np.nan, 3])
+    a_series_rm = remove_na(a_series)
+    assert_series_equal(a_series_rm, pd.Series([1., 2, 3], [0, 1, 3]))
+
+
+def test_assign_default_kwargs():
+
+    def f(a, b, c, d):
+        pass
+
+    def g(c=1, d=2):
+        pass
+
+    kws = {"c": 3}
+
+    kws = _assign_default_kwargs(kws, f, g)
+    assert kws == {"c": 3, "d": 2}
+
+
+def test_draw_figure():
+
+    f, ax = plt.subplots()
+    ax.plot(["a", "b", "c"], [1, 2, 3])
+    _draw_figure(f)
+    assert not f.stale
+    # ticklabels are not populated until a draw, but this may change
+    assert ax.get_xticklabels()[0].get_text() == "a"
+
+
+def test_deprecate_ci():
+
+    msg = "\n\nThe `ci` parameter is deprecated. Use `errorbar="
+
+    with pytest.warns(FutureWarning, match=msg + "None"):
+        out = _deprecate_ci(None, None)
+    assert out is None
+
+    with pytest.warns(FutureWarning, match=msg + "'sd'"):
+        out = _deprecate_ci(None, "sd")
+    assert out == "sd"
+
+    with pytest.warns(FutureWarning, match=msg + r"\('ci', 68\)"):
+        out = _deprecate_ci(None, 68)
+    assert out == ("ci", 68)
+
+
+def test_version_predates():
+
+    mock = ModuleType("mock")
+    mock.__version__ = "1.2.3"
+
+    assert _version_predates(mock, "1.2.4")
+    assert _version_predates(mock, "1.3")
+
+    assert not _version_predates(mock, "1.2.3")
+    assert not _version_predates(mock, "0.8")
+    assert not _version_predates(mock, "1")
diff --git a/testbed/open-mmlab__mmengine/.circleci/config.yml b/testbed/open-mmlab__mmengine/.circleci/config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..785dc8196ed4160dc8fce243a38592be7dba4bdf
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.circleci/config.yml
@@ -0,0 +1,32 @@
+version: 2.1
+
+# this allows you to use CircleCI's dynamic configuration feature
+setup: true
+
+# the path-filtering orb is required to continue a pipeline based on
+# the path of an updated fileset
+orbs:
+  path-filtering: circleci/path-filtering@0.1.2
+
+workflows:
+  # the always-run workflow is always triggered, regardless of the pipeline parameters.
+  always-run:
+    jobs:
+      # the path-filtering/filter job determines which pipeline
+      # parameters to update.
+      - path-filtering/filter:
+          name: check-updated-files
+          # 3-column, whitespace-delimited mapping. One mapping per
+          # line:
+          #   
+          mapping: |
+            mmengine/.* lint_only false
+            requirements/.* lint_only false
+            tests/.* lint_only false
+            .circleci/.* lint_only false
+          base-revision: main
+          # this is the path of the configuration we should trigger once
+          # path filtering and pipeline parameter value updates are
+          # complete. In this case, we are using the parent dynamic
+          # configuration itself.
+          config-path: .circleci/test.yml
diff --git a/testbed/open-mmlab__mmengine/.circleci/docker/Dockerfile b/testbed/open-mmlab__mmengine/.circleci/docker/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..7212c32e9cf919479030561a255c4ca0e63e38a6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.circleci/docker/Dockerfile
@@ -0,0 +1,15 @@
+ARG PYTORCH="1.8.1"
+ARG CUDA="10.2"
+ARG CUDNN="7"
+
+FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-devel
+
+# Set MKL_THREADING_LAYER=GNU to fix issue:
+# https://github.com/pytorch/pytorch/issues/37377
+ENV MKL_THREADING_LAYER GNU
+
+# To fix GPG key error when running apt-get update
+RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
+RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+
+RUN apt-get update && apt-get install -y ninja-build libglib2.0-0 libsm6 libxrender-dev libxext6 libgl1-mesa-glx
diff --git a/testbed/open-mmlab__mmengine/.circleci/test.yml b/testbed/open-mmlab__mmengine/.circleci/test.yml
new file mode 100644
index 0000000000000000000000000000000000000000..de87180614a31fff281709d3cc2cf7a83d947276
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.circleci/test.yml
@@ -0,0 +1,202 @@
+version: 2.1
+
+# the default pipeline parameters, which will be updated according to
+# the results of the path-filtering orb
+parameters:
+  lint_only:
+    type: boolean
+    default: true
+
+jobs:
+  lint:
+    docker:
+      - image: cimg/python:3.7.4
+    steps:
+      - checkout
+      - run:
+          name: Install pre-commit hook
+          command: |
+            pip install pre-commit
+            pre-commit install
+      - run:
+          name: Linting
+          command: pre-commit run --all-files
+      - run:
+          name: Check docstring coverage
+          command: |
+            pip install interrogate
+            interrogate -v --ignore-init-method --ignore-module --ignore-nested-functions --ignore-regex "__repr__" --fail-under 80 mmengine
+
+  build_without_torch:
+    parameters:
+      # The python version must match available image tags in
+      # https://circleci.com/developer/images/image/cimg/python
+      python:
+        type: string
+        default: "3.7.4"
+    docker:
+      - image: cimg/python:<< parameters.python >>
+    resource_class: large
+    steps:
+      - checkout
+      - run:
+          name: Upgrade pip
+          command: |
+            pip install pip --upgrade
+            pip --version
+      - run:
+          name: Build MMEngine from source
+          command: pip install -e . -v
+      - run:
+          name: Install unit tests dependencies
+          command: pip install -r requirements/tests.txt
+      - run:
+          name: Run unit tests
+          command: pytest tests/test_config tests/test_registry tests/test_fileio tests/test_logging tests/test_utils --ignore=tests/test_utils/test_dl_utils
+
+  build_cpu:
+    parameters:
+      # The python version must match available image tags in
+      # https://circleci.com/developer/images/image/cimg/python
+      python:
+        type: string
+      torch:
+        type: string
+      torchvision:
+        type: string
+    docker:
+      - image: cimg/python:<< parameters.python >>
+    resource_class: large
+    steps:
+      - checkout
+      - run:
+          name: Install Libraries
+          command: |
+            sudo apt-get update
+            sudo apt-get install -y ninja-build libglib2.0-0 libsm6 libxrender-dev libxext6 libgl1-mesa-glx libjpeg-dev zlib1g-dev libtinfo-dev libncurses5
+      - run:
+          name: Configure Python & pip
+          command: |
+            pip install --upgrade pip
+            pip install wheel
+      - run:
+          name: Install PyTorch
+          command: pip install torch==<< parameters.torch >>+cpu torchvision==<< parameters.torchvision >>+cpu -f https://download.pytorch.org/whl/torch_stable.html
+      - run:
+          name: Build MMEngine from source
+          command: pip install -e . -v
+      - run:
+          name: Install unit tests dependencies
+          command: |
+            pip install -r requirements/tests.txt
+            pip install openmim
+            mim install 'mmcv>=2.0.0rc1'
+      - run:
+          name: Run unittests
+          command: |
+            coverage run --branch --source mmengine -m pytest tests/
+            coverage xml
+            coverage report -m
+
+  build_cuda:
+    parameters:
+      torch:
+        type: string
+      cuda:
+        type: enum
+        enum: ["10.1", "10.2", "11.1"]
+      cudnn:
+        type: integer
+        default: 7
+    machine:
+      image: ubuntu-2004-cuda-11.4:202110-01
+      docker_layer_caching: true
+    resource_class: gpu.nvidia.small
+    steps:
+      - checkout
+      - run:
+          name: Build Docker image
+          command: |
+            docker build .circleci/docker -t mmengine:gpu --build-arg PYTORCH=<< parameters.torch >> --build-arg CUDA=<< parameters.cuda >> --build-arg CUDNN=<< parameters.cudnn >>
+            docker run --gpus all -t -d -v /home/circleci/project:/mmengine -w /mmengine --name mmengine mmengine:gpu
+      - run:
+          name: Build MMEngine from source
+          command: |
+            docker exec mmengine pip install -e . -v
+      - run:
+          name: Install unit tests dependencies
+          command: |
+            docker exec mmengine pip install -r requirements/tests.txt
+            docker exec mmengine pip install openmim
+            docker exec mmengine mim install 'mmcv>=2.0.0rc1'
+      - run:
+          name: Run unittests
+          command: |
+            docker exec mmengine python -m pytest tests/
+
+workflows:
+  pr_stage_lint:
+    when: << pipeline.parameters.lint_only >>
+    jobs:
+      - lint:
+          name: lint
+          filters:
+            branches:
+              ignore:
+                - main
+  pr_stage_test:
+    when:
+      not:
+        << pipeline.parameters.lint_only >>
+    jobs:
+      - lint:
+          name: lint
+          filters:
+            branches:
+              ignore:
+                - main
+      - build_without_torch:
+          name: build without torch
+          requires:
+            - lint
+      - build_cpu:
+          name: minimum_version_cpu
+          torch: 1.6.0
+          torchvision: 0.7.0
+          python: 3.6.9  # The lowest python 3.6.x version available on CircleCI images
+          requires:
+            - lint
+      - build_cpu:
+          name: maximum_version_cpu
+          torch: 1.13.0
+          torchvision: 0.14.0
+          python: 3.9.0
+          requires:
+            - minimum_version_cpu
+      - hold:
+          type: approval
+          requires:
+            - maximum_version_cpu
+      - build_cuda:
+          name: mainstream_version_gpu
+          torch: 1.8.1
+          # Use double quotation mark to explicitly specify its type
+          # as string instead of number
+          cuda: "10.2"
+          requires:
+            - hold
+  merge_stage_test:
+    when:
+      not:
+        << pipeline.parameters.lint_only >>
+    jobs:
+      - build_cuda:
+          name: minimum_version_gpu
+          torch: 1.6.0
+          # Use double quotation mark to explicitly specify its type
+          # as string instead of number
+          cuda: "10.1"
+          filters:
+            branches:
+              only:
+                - main
diff --git a/testbed/open-mmlab__mmengine/.github/CODE_OF_CONDUCT.md b/testbed/open-mmlab__mmengine/.github/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..92afad1c5ab5d5781115dee45c131d3751d3cd31
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/CODE_OF_CONDUCT.md
@@ -0,0 +1,76 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+- Using welcoming and inclusive language
+- Being respectful of differing viewpoints and experiences
+- Gracefully accepting constructive criticism
+- Focusing on what is best for the community
+- Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+- The use of sexualized language or imagery and unwelcome sexual attention or
+  advances
+- Trolling, insulting/derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or electronic
+  address, without explicit permission
+- Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at chenkaidev@gmail.com. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
+
+[homepage]: https://www.contributor-covenant.org
diff --git a/testbed/open-mmlab__mmengine/.github/CONTRIBUTING.md b/testbed/open-mmlab__mmengine/.github/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..433ffc4bca0fc58ed4d1e32eedcc3fd712035f74
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/CONTRIBUTING.md
@@ -0,0 +1 @@
+We appreciate all contributions to improve MMEngine. Please refer to [CONTRIBUTING.md](https://github.com/open-mmlab/mmcv/blob/master/CONTRIBUTING.md) in MMCV for more details about the contributing guideline.
diff --git a/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/1-bug-report.yml b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/1-bug-report.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f77c380fe8c038bf9edaef97f5741bfcddd75840
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/1-bug-report.yml
@@ -0,0 +1,94 @@
+name: "🐞 Bug report"
+description: "Create a report to help us reproduce and fix the bug"
+labels: bug
+title: "[Bug] "
+
+body:
+  - type: markdown
+    attributes:
+      value: |
+        ## Note
+        For general usage questions or idea discussions, please post it to our [**Forum**](https://github.com/open-mmlab/mmengine/discussions)
+        Please fill in as **much** of the following form as you're able to. **The clearer the description, the shorter it will take to solve it.**
+
+  - type: checkboxes
+    attributes:
+      label: Prerequisite
+      description: Please check the following items before creating a new issue.
+      options:
+      - label: I have searched [Issues](https://github.com/open-mmlab/mmengine/issues) and [Discussions](https://github.com/open-mmlab/mmengine/discussions) but cannot get the expected help.
+        required: true
+      - label: The bug has not been fixed in the latest version(https://github.com/open-mmlab/mmengine).
+        required: true
+
+  - type: textarea
+    attributes:
+      label: Environment
+      description: |
+        Please run `python -c "from mmengine.utils.dl_utils import collect_env; print(collect_env())"` to collect necessary environment information and copy-paste it here.
+        You may add additional information that may be helpful for locating the problem, such as
+          - How you installed PyTorch \[e.g., pip, conda, source\]
+          - Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.)
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Reproduces the problem - code sample
+      description: |
+        Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
+      placeholder: |
+        ```python
+        # Sample code to reproduce the problem
+        ```
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Reproduces the problem - command or script
+      description: |
+        What command or script did you run?
+      placeholder: |
+        ```shell
+        The command or script you run.
+        ```
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Reproduces the problem - error message
+      description: |
+        Please provide the error message or logs you got, with the full traceback.
+
+        Tip: You can attach images or log files by dragging them into the text area..
+      placeholder: |
+        ```
+        The error message or logs you got, with the full traceback.
+        ```
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Additional information
+      description: |
+        Tell us anything else you think we should know.
+
+        Tip: You can attach images or log files by dragging them into the text area.
+      placeholder: |
+        1. What's your expected result?
+        2. What dataset did you use?
+        3. What do you think might be the reason?
+
+  - type: markdown
+    attributes:
+      value: |
+        ## Acknowledgement
+        Thanks for taking the time to fill out this report.
+
+        If you have already identified the reason, we strongly appreciate you creating a new PR to fix it [**Here**](https://github.com/open-mmlab/mmengine/pulls)!
+        Please refer to [**Contribution Guide (TODO)**](https://mmengine.readthedocs.io/en/latest/notes/contribution_guide.html) for contributing.
+
+        Welcome to join our [**Community (TODO)**](https://mmengine.readthedocs.io/en/latest/contact.html) to discuss together. 👬
diff --git a/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/2-feature_request.yml b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/2-feature_request.yml
new file mode 100644
index 0000000000000000000000000000000000000000..fe81d86b8d2b7a8a4f22b1f304cc4d6c67a9503f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/2-feature_request.yml
@@ -0,0 +1,39 @@
+name: 🚀 Feature request
+description: Suggest an idea for this project
+labels: [feature-request]
+title: "[Feature] "
+
+body:
+  - type: markdown
+    attributes:
+      value: |
+        ## Note
+        For general usage questions or idea discussions, please post it to our [**Forum**](https://github.com/open-mmlab/mmengine/discussions)
+
+        Please fill in as **much** of the following form as you're able to. **The clearer the description, the shorter it will take to solve it.**
+
+  - type: textarea
+    attributes:
+      label: What is the feature?
+      description: Tell us more about the feature and how this feature can help.
+      placeholder: |
+        E.g., It is inconvenient when \[....\].
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Any other context?
+      description: |
+        Have you considered any alternative solutions or features? If so, what are they? Also, feel free to add any other context or screenshots about the feature request here.
+
+  - type: markdown
+    attributes:
+      value: |
+        ## Acknowledgement
+        Thanks for taking the time to fill out this report.
+
+        We strongly appreciate you creating a new PR to implement it [**Here**](https://github.com/open-mmlab/mmengine/pulls)!
+        Please refer to [**Contribution Guide (TODO)**](https://mmengine.readthedocs.io/en/latest/notes/contribution_guide.html) for contributing.
+
+        Welcome to join our [**Community (TODO)**](https://mmengine.readthedocs.io/en/latest/contact.html) to discuss together. 👬
diff --git a/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/3-documentation.yml b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/3-documentation.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f39da61c039f3f507b7f7ae636fa69fa1cc02760
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/3-documentation.yml
@@ -0,0 +1,37 @@
+name: 📚 Documentation
+description: Report an issue related to the documentation.
+labels: "docs"
+title: "[Docs] "
+
+body:
+  - type: markdown
+    attributes:
+      value: |
+        ## Note
+        For general usage questions or idea discussions, please post it to our [**Forum**](https://github.com/open-mmlab/mmengine/discussions)
+        Please fill in as **much** of the following form as you're able to. **The clearer the description, the shorter it will take to solve it.**
+
+  - type: textarea
+    attributes:
+      label: 📚 The doc issue
+      description: >
+        A clear and concise description the issue.
+    validations:
+      required: true
+
+  - type: textarea
+    attributes:
+      label: Suggest a potential alternative/fix
+      description: >
+        Tell us how we could improve the documentation in this regard.
+
+  - type: markdown
+    attributes:
+      value: |
+        ## Acknowledgement
+        Thanks for taking the time to fill out this report.
+
+        If you have already identified the reason, we strongly appreciate you creating a new PR to fix it [**here**](https://github.com/open-mmlab/mmengine/pulls)!
+        Please refer to [Contribution Guide](https://mmengine.readthedocs.io/en/latest/notes/contributing.html) for contributing.
+
+        Welcome to join our [**Community(TODO)**](https://mmengine.readthedocs.io/en/latest/contact.html) to discuss together. 👬
diff --git a/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/config.yml b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..e022ea6f88940cb1165578d84eecd25389b9eaee
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,12 @@
+blank_issues_enabled: false
+
+contact_links:
+  - name: 💬 Forum
+    url: https://github.com/open-mmlab/mmengine/discussions
+    about: Ask general usage questions and discuss with other mmengine community members
+  - name: MMEngine Documentation
+    url: https://mmengine.readthedocs.io/en/latest/
+    about: Check if your question is answered in docs
+  - name: 🌐 Explore OpenMMLab
+    url: https://openmmlab.com/
+    about: Get know more about OpenMMLab
diff --git a/testbed/open-mmlab__mmengine/.github/pull_request_template.md b/testbed/open-mmlab__mmengine/.github/pull_request_template.md
new file mode 100644
index 0000000000000000000000000000000000000000..8f8e28983ff2798a4a1c05dcfe9159f23b34b1c0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/pull_request_template.md
@@ -0,0 +1,25 @@
+Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.
+
+## Motivation
+
+Please describe the motivation of this PR and the goal you want to achieve through this PR.
+
+## Modification
+
+Please briefly describe what modification is made in this PR.
+
+## BC-breaking (Optional)
+
+Does the modification introduce changes that break the backward-compatibility of the downstream repos?
+If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR.
+
+## Use cases (Optional)
+
+If this PR introduces a new feature, it is better to list some use cases here, and update the documentation.
+
+## Checklist
+
+1. Pre-commit or other linting tools are used to fix the potential lint issues.
+2. The modification is covered by complete unit tests. If not, please add more unit test to ensure the correctness.
+3. If the modification has potential influence on downstream projects, this PR should be tested with downstream projects, like MMDet or MMCls.
+4. The documentation has been modified accordingly, like docstring or example tutorials.
diff --git a/testbed/open-mmlab__mmengine/.github/workflows/deploy.yml b/testbed/open-mmlab__mmengine/.github/workflows/deploy.yml
new file mode 100644
index 0000000000000000000000000000000000000000..13a190baf241882a81a0386e954ddc452fd08316
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/workflows/deploy.yml
@@ -0,0 +1,28 @@
+name: deploy
+
+on: push
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  build-n-publish:
+    runs-on: ubuntu-latest
+    if: startsWith(github.event.ref, 'refs/tags')
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python 3.7
+        uses: actions/setup-python@v2
+        with:
+          python-version: 3.7
+      - name: Install torch
+        run: pip install torch
+      - name: Install wheel
+        run: pip install wheel
+      - name: Build MMEngine
+        run: python setup.py sdist bdist_wheel
+      - name: Publish distribution to PyPI
+        run: |
+          pip install twine
+          twine upload dist/* -u __token__ -p ${{ secrets.pypi_password }}
diff --git a/testbed/open-mmlab__mmengine/.github/workflows/lint.yml b/testbed/open-mmlab__mmengine/.github/workflows/lint.yml
new file mode 100644
index 0000000000000000000000000000000000000000..075baad95c39d7653235d7eec5dd3ab085d043ad
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/workflows/lint.yml
@@ -0,0 +1,27 @@
+name: lint
+
+on: [push, pull_request]
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  lint:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python 3.7
+        uses: actions/setup-python@v2
+        with:
+          python-version: 3.7
+      - name: Install pre-commit hook
+        run: |
+          pip install pre-commit
+          pre-commit install
+      - name: Linting
+        run: pre-commit run --all-files
+      - name: Check docstring coverage
+        run: |
+          pip install interrogate
+          interrogate -v --ignore-init-method --ignore-magic --ignore-module --ignore-nested-functions --ignore-regex "__repr__" --fail-under 80 mmengine
diff --git a/testbed/open-mmlab__mmengine/.github/workflows/merge_stage_test.yml b/testbed/open-mmlab__mmengine/.github/workflows/merge_stage_test.yml
new file mode 100644
index 0000000000000000000000000000000000000000..46ced35075dd6f393a69be7fb8ded73620b32f5a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/workflows/merge_stage_test.yml
@@ -0,0 +1,227 @@
+name: merge_stage_test
+
+on:
+  push:
+    paths-ignore:
+      - ".github/**.md"
+      - "docker/**"
+      - "docs/**"
+      - "README.md"
+      - "README_zh-CN.md"
+      - "CONTRIBUTING.md"
+      - "CONTRIBUTING_zh-CN.md"
+      - ".pre-commit-config.yaml"
+      - ".pre-commit-config-zh-cn.yaml"
+    branches:
+      - main
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  build_cpu_py:
+    runs-on: ubuntu-18.04
+    strategy:
+      matrix:
+        python-version: [3.6, 3.8, 3.9]
+        torch: [1.8.1]
+        include:
+          - torch: 1.8.1
+            torchvision: 0.9.1
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: python -m pip install pip --upgrade
+      - name: Install PyTorch
+        run: pip install torch==${{matrix.torch}}+cpu torchvision==${{matrix.torchvision}}+cpu -f https://download.pytorch.org/whl/torch_stable.html
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+
+  build_cpu_pt:
+    runs-on: ubuntu-18.04
+    strategy:
+      matrix:
+        python-version: [3.7]
+        torch: [1.6.0, 1.7.1, 1.8.1, 1.9.1, 1.10.1, 1.11.0, 1.12.0, 1.13.0]
+        include:
+          - torch: 1.6.0
+            torchvision: 0.7.0
+          - torch: 1.7.1
+            torchvision: 0.8.2
+          - torch: 1.8.1
+            torchvision: 0.9.1
+          - torch: 1.9.1
+            torchvision: 0.10.1
+          - torch: 1.10.1
+            torchvision: 0.11.2
+          - torch: 1.11.0
+            torchvision: 0.12.0
+          - torch: 1.12.0
+            torchvision: 0.13.0
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: python -m pip install pip --upgrade
+      - name: Install PyTorch
+        run: pip install torch==${{matrix.torch}}+cpu torchvision==${{matrix.torchvision}}+cpu -f https://download.pytorch.org/whl/torch_stable.html
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+      # Only upload coverage report for python3.7 && pytorch1.8.1 cpu
+      - name: Upload coverage to Codecov
+        if: ${{matrix.torch == '1.8.1' && matrix.python-version == '3.7'}}
+        uses: codecov/codecov-action@v1.0.14
+        with:
+          file: ./coverage.xml
+          flags: unittests
+          env_vars: OS,PYTHON
+          name: codecov-umbrella
+          fail_ci_if_error: false
+
+  build_cu102:
+    runs-on: ubuntu-18.04
+    container:
+      image: pytorch/pytorch:1.8.1-cuda10.2-cudnn7-devel
+    env:
+      MKL_THREADING_LAYER: GNU
+    strategy:
+      matrix:
+        python-version: [3.7]
+        include:
+          - torch: 1.8.1
+            cuda: 10.2
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: python -m pip install pip --upgrade
+      - name: Fetch GPG keys
+        run: |
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+      - name: Install system dependencies
+        run: apt-get update && apt-get install -y ffmpeg libsm6 libxext6 git ninja-build libglib2.0-0 libsm6 libxrender-dev libxext6
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+
+  build_cu116:
+    runs-on: ubuntu-18.04
+    container:
+      image: pytorch/pytorch:1.13.0-cuda11.6-cudnn8-devel
+    strategy:
+      matrix:
+        python-version: [3.7]
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: python -m pip install pip --upgrade
+      - name: Fetch GPG keys
+        run: |
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+      - name: Install system dependencies
+        run: apt-get update && apt-get install -y git ffmpeg libturbojpeg
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+
+  build_macos:
+    runs-on: macos-latest
+    strategy:
+      matrix:
+        python-version: [3.7]
+        torch: [1.6.0, 1.8.1, 1.13.0]
+        include:
+          - torch: 1.6.0
+            torchvision: 0.7.0
+          - torch: 1.8.1
+            torchvision: 0.9.1
+          - torch: 1.13.0
+            torchvision: 0.14.0
+
+  build_windows:
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        os: [windows-2022]
+        python: [3.7]
+        platform: [cpu, cu111]
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        # Windows CI could fail If we call `pip install pip --upgrade` directly.
+        run: python -m pip install pip --upgrade
+      - name: Install PyTorch
+        run: pip install torch==1.8.1+${{matrix.platform}} torchvision==0.9.1+${{matrix.platform}} -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run CPU unittests
+        run: pytest tests/
+        if: ${{ matrix.platform == 'cpu' }}
+      - name: Run GPU unittests
+        # Skip testing distributed related unit tests since the memory of windows CI is limited
+        run: pytest tests/ --ignore tests/test_dist --ignore tests/test_optim/test_optimizer/test_optimizer_wrapper.py --ignore tests/test_model/test_wrappers/test_model_wrapper.py
+        if: ${{ matrix.platform == 'cu111' }}
diff --git a/testbed/open-mmlab__mmengine/.github/workflows/pr_stage_test.yml b/testbed/open-mmlab__mmengine/.github/workflows/pr_stage_test.yml
new file mode 100644
index 0000000000000000000000000000000000000000..ca0230380fa3c37a0c61399e19666541be8e4f03
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.github/workflows/pr_stage_test.yml
@@ -0,0 +1,128 @@
+name: pr_stage_test
+
+on:
+  pull_request:
+    paths-ignore:
+      - ".github/**.md"
+      - "docker/**"
+      - "docs/**"
+      - "README.md"
+      - "README_zh-CN.md"
+      - "CONTRIBUTING.md"
+      - "CONTRIBUTING_zh-CN.md"
+      - ".pre-commit-config.yaml"
+      - ".pre-commit-config-zh-cn.yaml"
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  build_cpu:
+    runs-on: ubuntu-18.04
+    strategy:
+      matrix:
+        python-version: [3.7]
+        include:
+          - torch: 1.8.1
+            torchvision: 0.9.1
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: python -m pip install pip --upgrade
+      - name: Install PyTorch
+        run: pip install torch==${{matrix.torch}}+cpu torchvision==${{matrix.torchvision}}+cpu -f https://download.pytorch.org/whl/torch_stable.html
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+      # Upload coverage report for python3.7 && pytorch1.8.1 cpu
+      - name: Upload coverage to Codecov
+        uses: codecov/codecov-action@v1.0.14
+        with:
+          file: ./coverage.xml
+          flags: unittests
+          env_vars: OS,PYTHON
+          name: codecov-umbrella
+          fail_ci_if_error: false
+
+  build_cu102:
+    runs-on: ubuntu-18.04
+    container:
+      image: pytorch/pytorch:1.8.1-cuda10.2-cudnn7-devel
+    env:
+      MKL_THREADING_LAYER: GNU
+    strategy:
+      matrix:
+        python-version: [3.7]
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        run: pip install pip --upgrade
+      - name: Fetch GPG keys
+        run: |
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
+          apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+      - name: Install system dependencies
+        run: apt-get update && apt-get install -y ffmpeg libsm6 libxext6 git ninja-build libglib2.0-0 libsm6 libxrender-dev libxext6
+      - name: Build MMEngine from source
+        run: pip install -e . -v
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run unittests and generate coverage report
+        run: |
+          coverage run --branch --source mmengine -m pytest tests/
+          coverage xml
+          coverage report -m
+
+  build_windows:
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        os: [windows-2022]
+        python: [3.7]
+        platform: [cpu, cu111]
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up Python ${{ matrix.python-version }}
+        uses: actions/setup-python@v2
+        with:
+          python-version: ${{ matrix.python-version }}
+      - name: Upgrade pip
+        # Windows CI could fail If we call `pip install pip --upgrade` directly.
+        run: python -m pip install pip --upgrade
+      - name: Install PyTorch
+        run: pip install torch==1.8.1+${{matrix.platform}} torchvision==0.9.1+${{matrix.platform}} -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html
+      - name: Build MMEngine from source
+        run: pip install -e .
+      - name: Install unit tests dependencies
+        run: |
+          pip install -r requirements/tests.txt
+          pip install openmim
+          mim install 'mmcv>=2.0.0rc1'
+      - name: Run CPU unittests
+        run: pytest tests/
+        if: ${{ matrix.platform == 'cpu' }}
+      - name: Run GPU unittests
+        # Skip testing distributed related unit tests since the memory of windows CI is limited
+        run: pytest tests/ --ignore tests/test_dist --ignore tests/test_optim/test_optimizer/test_optimizer_wrapper.py --ignore tests/test_model/test_wrappers/test_model_wrapper.py
+        if: ${{ matrix.platform == 'cu111' }}
diff --git a/testbed/open-mmlab__mmengine/docker/README.md b/testbed/open-mmlab__mmengine/docker/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..3ca417b48d0f3cdef7304bf18b04199a7c0bc0d2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docker/README.md
@@ -0,0 +1,65 @@
+# Docker images
+
+There are two `Dockerfile` files to build docker images, one to build an image with the mmengine package and the other with the mmengine development environment.
+
+```text
+.
+|-- README.md
+|-- dev  # build with mmengine development environment
+|   `-- Dockerfile
+`-- release  # build with mmengine package
+    `-- Dockerfile
+```
+
+## Build docker images
+
+### Build with mmengine package
+
+Build with local repository
+
+```bash
+git clone https://github.com/open-mmlab/mmengine.git && cd mmengine
+docker build -t mmengine -f docker/release/Dockerfile .
+```
+
+Or build with remote repository
+
+```bash
+docker build -t mmengine https://github.com/open-mmlab/mmengine.git#main:docker/release
+```
+
+The [Dockerfile](release/Dockerfile) installs the latest released version of mmengine by default, but you can specify mmengine versions to install expected versions.
+
+```bash
+docker image build -t mmengine -f docker/release/Dockerfile --build-arg MMENGINE=0.1.0 .
+```
+
+If you also want to use other versions of PyTorch and CUDA, you can also pass them when building docker images.
+
+An example to build an image with PyTorch 1.11 and CUDA 11.3.
+
+```bash
+docker build -t mmengine -f docker/release/Dockerfile \
+    --build-arg PYTORCH=1.9.0 \
+    --build-arg CUDA=11.1 \
+    --build-arg CUDNN=8 .
+```
+
+More available versions of PyTorch and CUDA can be found at [dockerhub/pytorch](https://hub.docker.com/r/pytorch/pytorch/tags).
+
+### Build with mmengine development environment
+
+If you want to build an docker image with the mmengine development environment, you can use the following command
+
+```bash
+git clone https://github.com/open-mmlab/mmengine.git && cd mmengine
+docker build -t mmengine -f docker/dev/Dockerfile .
+```
+
+## Run images
+
+```bash
+docker run --gpus all --shm-size=8g -it mmengine
+```
+
+See [docker run](https://docs.docker.com/engine/reference/commandline/run/) for more usages.
diff --git a/testbed/open-mmlab__mmengine/docker/dev/Dockerfile b/testbed/open-mmlab__mmengine/docker/dev/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f63c28436560460bd1ab6445ea5fe9c676a0cce7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docker/dev/Dockerfile
@@ -0,0 +1,24 @@
+ARG PYTORCH="1.8.1"
+ARG CUDA="10.2"
+ARG CUDNN="7"
+
+FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-devel
+
+# To fix GPG key error when running apt-get update
+RUN rm /etc/apt/sources.list.d/cuda.list \
+    && rm /etc/apt/sources.list.d/nvidia-ml.list \
+    && apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub \
+    && apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+
+# Install git and system dependencies for opencv-python
+RUN apt-get update && apt-get install -y git \
+    && apt-get update && apt-get install -y libgl1 libglib2.0-0
+
+# Build mmengine from source with develop mode
+RUN git clone https://github.com/open-mmlab/mmengine.git /mmengine
+WORKDIR /mmengine
+RUN git rev-parse --short HEAD
+RUN pip install --no-cache-dir -e .[all] -v && pip install pre-commit && pre-commit install
+
+# Verify the installation
+RUN python -c 'from mmengine.utils.dl_utils import collect_env;print(collect_env())'
diff --git a/testbed/open-mmlab__mmengine/docker/release/Dockerfile b/testbed/open-mmlab__mmengine/docker/release/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..de099f4c2e0540a2041fc2693a5225f3396f08b3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docker/release/Dockerfile
@@ -0,0 +1,23 @@
+ARG PYTORCH="1.8.1"
+ARG CUDA="10.2"
+ARG CUDNN="7"
+
+FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-devel
+
+# To fix GPG key error when running apt-get update
+RUN rm /etc/apt/sources.list.d/cuda.list \
+    && rm /etc/apt/sources.list.d/nvidia-ml.list \
+    && apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub \
+    && apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub
+
+# Install system dependencies for opencv-python
+RUN apt-get update && apt-get install -y libgl1 libglib2.0-0 \
+    && apt-get clean \
+    && rm -rf /var/lib/apt/lists/*
+
+# Install mmengine
+ARG MMENGINE=""
+RUN if [ "${MMENGINE}" = "" ]; then pip install -U openmim && mim install mmengine; else pip install -U openmim && mim install mmengine==${MMENGINE}; fi
+
+# Verify the installation
+RUN python -c 'from mmengine.utils.dl_utils import collect_env;print(collect_env())'
diff --git a/testbed/open-mmlab__mmengine/docs/en/_static/css/readthedocs.css b/testbed/open-mmlab__mmengine/docs/en/_static/css/readthedocs.css
new file mode 100644
index 0000000000000000000000000000000000000000..ed72f2f554ad276ea57d112dd2daaf08c3e4b93c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/_static/css/readthedocs.css
@@ -0,0 +1,17 @@
+table.colwidths-auto td {
+  width: 50%
+}
+.header-logo {
+    background-image: url("../image/mmengine-logo.png");
+    background-size: 130px 40px;
+    height: 40px;
+    width: 130px;
+}
+.two-column-table-wrapper {
+    width: 50%;
+    max-width: 300px;
+    overflow-x: auto;
+}
+.two-column-table-wrapper .highlight {
+    width: 1500px
+}
diff --git a/testbed/open-mmlab__mmengine/docs/en/_templates/classtemplate.rst b/testbed/open-mmlab__mmengine/docs/en/_templates/classtemplate.rst
new file mode 100644
index 0000000000000000000000000000000000000000..4f74842394ec9807fb1ae2d8f05a8a57e9a2e24c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/_templates/classtemplate.rst
@@ -0,0 +1,14 @@
+.. role:: hidden
+    :class: hidden-section
+.. currentmodule:: {{ module }}
+
+
+{{ name | underline}}
+
+.. autoclass:: {{ name }}
+    :members:
+
+
+..
+  autogenerated from source/_templates/classtemplate.rst
+  note it does not have :inherited-members:
diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/basedataset.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/basedataset.md
new file mode 100644
index 0000000000000000000000000000000000000000..30103fe6ce6702254e6b88e717774e5afd33edf3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/basedataset.md
@@ -0,0 +1,505 @@
+# BaseDataset
+
+## Introduction
+
+The Dataset class in the algorithm toolbox is responsible for providing input data for the model during the training/testing process. The Dataset class in each algorithm toolbox under OpenMMLab projects has some common characteristics and requirements, such as the need for efficient internal data storage format, support for the concatenation of different datasets, dataset repeated sampling, and so on.
+
+Therefore, **MMEngine** implements [BaseDataset](mmengine.dataset.BaseDataset) which provides some basic interfaces and implements some DatasetWrappers with the same interfaces. Most of the Dataset Classes in the OpenMMLab algorithm toolbox meet the interface defined by the `BaseDataset` and use the same DatasetWrappers.
+
+The basic function of the BaseDataset is to load the dataset information. Here, we divide the dataset information into two categories. One is meta information, which represents the information related to the dataset itself and sometimes needs to be obtained by the model or other external components. For example, the meta information of the dataset generally includes the category information `classes` in the image classification task, since the classification model usually needs to record the category information of the dataset. The other is data information, which defines the file path and corresponding label information of specific data info. In addition, another function of the BaseDataset is to continuously send data into the data pipeline for data preprocessing.
+
+### The standard data annotation file
+
+In order to unify the dataset interface of different tasks and facilitate multiple tasks training in one model, OpenMMLab formulate the **OpenMMLab 2.0 dataset format specification**. Dataset annotation files should conform to this specification, and the `BaseDataset` reads and parses data annotation files based on this specification. If the data annotation file provided by the user does not conform to the specified format, the user can choose to convert it to the specified format and use OpenMMLab's algorithm toolbox to conduct algorithm training and testing based on the converted data annotation file.
+
+The OpenMMLab 2.0 dataset format specification states that annotation files must be in the format of `json` or `yaml`, `yml` or `pickle`, `pkl`. The dictionary stored in the annotation file must contain two fields, `metainfo` and `data_list`. The `metainfo` is a dictionary containing meta information about the dataset. The `data_list` is a list in which each element is a dictionary and the dictionary defines a raw data info. Each raw data info contains one or more training/test samples.
+
+Here is an example of a JSON annotation file (where each raw data info contains only one training/test sample):
+
+```json
+
+{
+    'metainfo':
+        {
+            'classes': ('cat', 'dog'),
+            ...
+        },
+    'data_list':
+        [
+            {
+                'img_path': "xxx/xxx_0.jpg",
+                'img_label': 0,
+                ...
+            },
+            {
+                'img_path': "xxx/xxx_1.jpg",
+                'img_label': 1,
+                ...
+            },
+            ...
+        ]
+}
+```
+
+We assume that the data is stored in the following path:
+
+```text
+data
+├── annotations
+│   ├── train.json
+├── train
+│   ├── xxx/xxx_0.jpg
+│   ├── xxx/xxx_1.jpg
+│   ├── ...
+```
+
+### The initialization process of the BaseDataset
+
+The initialization process of the `BaseDataset` is shown as follows:
+
+
+ +
+ +1. `load metainfo`: Obtain the meta information of the dataset. The meta information can be obtained from three sources with the priority from high to low: + +- The dict of `metainfo` passed by the user in the `__init__()` function. The priority is high since the user can pass this argument when the `BaseDataset` is instantiated; + +- The dict of `BaseDataset.METAINFO` in the class attributes of BaseDataset. The priority is medium since the user can change the class attributes `BaseDataset.METAINFO` in the custom dataset class; + +- The dict of `metainfo` included in the annotation file. The priority is low since the annotation file is generally not changed. + +If three sources have the same field, the source with the highest priority determines the value of the field. The priority comparison of these fields is: The fields in the `metainfo` dictionary passed by the user > The fields in the `BaseDataset.METAINFO` of BaseDataset > the fields in the `metainfo` of annotation file. + +2. `join path`: Process the path of datainfo and annotating files; + +3. `build pipeline`: Build data pipeline for the data preprocessing and data preparation; + +4. `full init`: Fully initializes the BaseDataset. This step mainly includes the following operations: + +- `load data list`: Read and parse the annotation files that meet the OpenMMLab 2.0 dataset format specification. In this step, the `parse_data_info()` method is called. This method is responsible for parsing each raw data info in the annotation file; + +- `filter data` (optional): Filters unnecessary data based on `filter_cfg`, such as data samples that do not contain annotations. By default, there is no filtering operation, and downstream subclasses can override it according to their own needs. + +- `get subset` (optional): Sample a subset of dataset based on a given index or an integer value, such as only the first 10 samples for training/testing. By default, all data samples are used. + +- `serialize data` (optional): Serialize all data samples to save memory. Please see [Save memory](#save-memory) for more details. we serialize all data samples by default. + +The `parse_data_info()` method in the BaseDataset is used to process a raw data info in the annotation file into one or more training/test data samples. The user needs to implement the `parse_data_info()` method if they want to customize dataset class. + +### The interface of BaseDataset + +Once the BaseDataset is initialized, it supports `__getitem__` method to index a data info and `__len__` method to get the length of dataset, just like `torch.utils.data.Dataset`. The Basedataset provides the following interfaces: + +- `metainfo`: Return the meta information with a dictionary value. + +- `get_data_info(idx)`: Return the full data information of the given `idx`, and the return value is a dictionary. + +- `__getitem__(idx)`: Return the results of data pipeline(The input data of model) of the given 'idx', and the return value is a dictionary. + +- `__len__()`: Return the length of the dataset. The return value is an integer. + +- `get_subset_(indices)`: Modify the original dataset class **in inplace** according to `indices`. If `indices` is `int`, then the original dataset class contains only the first few data samples. If `indices` is `Sequence[int]`, the raw dataset class contains data samples specified according to `Sequence[int]`. + +- `get_subset(indices)`: Return a **new** sub-dataset class according to indices, i.e., re-copies a sub-dataset. If `indices` is `int`, the returned sub-dataset object contains only the first few data samples. If `indices` is `Sequence[int]`, the returned sub-dataset object contains the data samples specified according to `Sequence[int]`. + +## Customize dataset class based on BaseDataset + +We can customize the dataset class based on BaseDataset, after we understand the initialization process of BaseDataset and the provided interfaces of BaseDataset. + +### Annotation files that meet the OpenMMLab 2.0 dataset format specification + +As mentioned above, users can overload `parse_data_info()` to load annotation files that meet the OpenMMLab 2.0 dataset format specification. Here is an example of using BaseDataset to implement a specific dataset. + +```python +import os.path as osp + +from mmengine.dataset import BaseDataset + + +class ToyDataset(BaseDataset): + + # Take the above annotation file as example. The raw_data_info represents a dictionary in the data_list list: + # { + # 'img_path': "xxx/xxx_0.jpg", + # 'img_label': 0, + # ... + # } + def parse_data_info(self, raw_data_info): + data_info = raw_data_info + img_prefix = self.data_prefix.get('img_path', None) + if img_prefix is not None: + data_info['img_path'] = osp.join( + img_prefix, data_info['img_path']) + return data_info + +``` + +#### Using Customized dataset class + +The `ToyDataset` can be instantiated with the following configuration, once it has been defined: + +```python + +class LoadImage: + + def __call__(self, results): + results['img'] = cv2.imread(results['img_path']) + return results + +class ParseImage: + + def __call__(self, results): + results['img_shape'] = results['img'].shape + return results + +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline) +``` + +At the same time, the external interface provided by the BaseDataset can be used to access specific data sample information: + +```python +toy_dataset.metainfo +# dict(classes=('cat', 'dog')) + +toy_dataset.get_data_info(0) +# { +# 'img_path': "data/train/xxx/xxx_0.jpg", +# 'img_label': 0, +# ... +# } + +len(toy_dataset) +# 2 + +toy_dataset[0] +# { +# 'img_path': "data/train/xxx/xxx_0.jpg", +# 'img_label': 0, +# 'img': a ndarray with shape (H, W, 3), which denotes the value of the image, +# 'img_shape': (H, W, 3) , +# ... +# } + +# The `get_subset` interface does not modify the original dataset class, i.e. make a complete copy of it +sub_toy_dataset = toy_dataset.get_subset(1) +len(toy_dataset), len(sub_toy_dataset) +# 2, 1 + +# The `get_subset_` interface modify the original dataset class in inplace +toy_dataset.get_subset_(1) +len(toy_dataset) +# 1 +``` + +Following the above steps, we can see how to customize a dataset based on the BaseDataset and how to use the customized dataset. + +#### Customize dataset for videos + +In the above examples, each raw data info of the annotation file contains only one training/test sample (usually in the image field). If each raw data info contains several training/test samples (usually in the video domain), we only need to ensure that the return value of `parse_data_info()` is `list[dict]`: + +```python +from mmengine.dataset import BaseDataset + + +class ToyVideoDataset(BaseDataset): + + # raw_data_info is still a dict, but it contains multiple samples + def parse_data_info(self, raw_data_info): + data_list = [] + + ... + + for ... : + + data_info = dict() + + ... + + data_list.append(data_info) + + return data_list + +``` + +The usage of `ToyVideoDataset` is similar to that of `ToyDataset`, which will not be repeated here. + +### Annotation files that do not meet the OpenMMLab 2.0 dataset format specification + +For annotated files that do not meet the OpenMMLab 2.0 dataset format specification, there are two ways to use: + +1. Convert the annotation files that do not meet the specifications into the annotation files that do meet the specifications, and then use the BaseDataset in the above way. + +2. Implement a new dataset class that inherits from the `BaseDataset` and overloads the `load_data_list(self):` function of the `BaseDataset` to handle annotation files that don't meet the specification and guarantee a return value of `list[dict]`, where each `dict` represents a data sample. + +## Other features of BaseDataset + +The BaseDataset also contains the following features: + +### lazy init + +When the BaseDataset is instantiated, the annotation file needs to be read and parsed, therefore it will take some time. However, in some cases, such as the visualization of prediction, only the meta information of the BaseDataset is required, and reading and parsing the annotation file may not be necessary. To save time on instantiating the BaseDataset in this case, the BaseDataset supports lazy init: + +```python +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline, + # Pass the lazy_init variable in here + lazy_init=True) +``` + +When `lazy_init=True`, the initialization of ToyDataset's only performs steps 1, 2, and 3 of the BaseDataset initialization process. At this time, `toy_dataset` was not fully initialized, since `toy_dataset` will not read and parse the annotation file. The `toy_dataset` only set the meta information of the dataset (`metainfo`). + +Naturally, if you need to access specific data information later, you can manually call the `toy_dataset.full_init()` interface to perform the complete initialization process, during which the data annotation file will be read and parsed. Calling the `get_data_info (independence idx)`, `__len__ ()`, `__getitem__ (independence idx)`, ` get_subset_ (indices)` and `get_subset(indices)` interface will also automatically call the `full_init()` interface to perform the full initialization process (only on the first call, later calls will not call the `full_init()` interface repeatedly): + +```python +# Full initialization +toy_dataset.full_init() + +# After initialization, you can now get the data info +len(toy_dataset) +# 2 +toy_dataset[0] +# { +# 'img_path': "data/train/xxx/xxx_0.jpg", +# 'img_label': 0, +# 'img': a ndarray with shape (H, W, 3), which denotes the value the image, +# 'img_shape': (H, W, 3) , +# ... +# } +``` + +**Notice:** + +Performing full initialization by calling the `__getitem__()` interface directly carries some risks: If a dataset object is not fully initialized by setting `lazy_init=True` firstly, then it is directly sent to the dataloader. Different dataloader workers will read and parse the annotation file at the same time in the subsequent data reading process. Although this may work normally, it consumes a lot of time and memory. **Therefore, it is recommended to manually call the `full_init()` interface to perform the full initialization process before you need to access specific data.** + +The above is not fully initialized by setting `lazy_init=True`, and then complete initialization according to the demand, called lazy init. + +### Save memory + +In the specific process of reading data, the dataloader will usually prefetch data from multiple dataloader workers, and multiple workers have complete dataset object backup, so there will be multiple copies of the same `data_list` in the memory. In order to save this part of memory consumption, The `BaseDataset` can serialize `data_list` into memory in advance, so that multiple workers can share the same copy of `data_list`, so as to save memory. + +By default, the BaseDataset stores the serialization of `data_list` into memory. It is also possible to control whether the data will be serialized into memory ahead of time by using the `serialize_data` argument (default is `True`) : + +```python +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline, + # Pass the serialize data argument in here + serialize_data=False) +``` + +The above example does not store the `data_list` serialization into memory in advance, so it is not recommended to instantiate the dataset class, when using the dataloader to open multiple dataloader workers to load the data. + +## DatasetWrappers + +In addition to BaseDataset, MMEngine also provides several DatasetWrappers: `ConcatDataset`, `RepeatDataset`, `ClassBalancedDataset`. These dataset wrappers also support lazy init and have memory-saving features. + +### ConcatDataset + +MMEngine provides a `ConcatDataset` wrapper to concatenate datasets in the following way: + +```python +from mmengine.dataset import ConcatDataset + +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset_1 = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline) + +toy_dataset_2 = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='val/'), + ann_file='annotations/val.json', + pipeline=pipeline) + +toy_dataset_12 = ConcatDataset(datasets=[toy_dataset_1, toy_dataset_2]) + +``` + +The above example combines the `train` set and the `val` set of the dataset into one large dataset. + +### RepeatDataset + +MMEngine provides `RepeatDataset` wrapper to repeat a dataset several times, as follows: + +```python +from mmengine.dataset import RepeatDataset + +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline) + +toy_dataset_repeat = RepeatDataset(dataset=toy_dataset, times=5) + +``` + +The above example samples the `train` set of the dataset five times. + +### ClassBalancedDataset + +MMEngine provides `ClassBalancedDataset` wrapper to repeatedly sample the corresponding samples based on the frequency of category occurrence in the dataset. + +**Notice:** + +The `ClassBalancedDataset` wrapper assumes that the wrapped dataset class supports the `get_cat_ids(idx)` method, which returns a list. The list contains the categories of `data_info` given by 'idx'. The usage is as follows: + +```python +from mmengine.dataset import BaseDataset, ClassBalancedDataset + +class ToyDataset(BaseDataset): + + def parse_data_info(self, raw_data_info): + data_info = raw_data_info + img_prefix = self.data_prefix.get('img_path', None) + if img_prefix is not None: + data_info['img_path'] = osp.join( + img_prefix, data_info['img_path']) + return data_info + + # The necessary method that needs to return the category of data sample + def get_cat_ids(self, idx): + data_info = self.get_data_info(idx) + return [int(data_info['img_label'])] + +pipeline = [ + LoadImage(), + ParseImage(), +] + +toy_dataset = ToyDataset( + data_root='data/', + data_prefix=dict(img_path='train/'), + ann_file='annotations/train.json', + pipeline=pipeline) + +toy_dataset_repeat = ClassBalancedDataset(dataset=toy_dataset, oversample_thr=1e-3) + +``` + +The above example resamples the `train` set of the dataset with `oversample_thr=1e-3`. Specifically, for categories whose frequency is less than `1e-3` in the dataset, samples corresponding to this category will be sampled repeatedly; otherwise, samples will not be sampled repeatedly. Please refer to the API documentation of `ClassBalancedDataset` for specific sampling policies. + +### Customize DatasetWrapper + +Since the BaseDataset support lazy init, some rules need to be followed when customizing the DatasetWrapper. Here is an example to show how to customize the DatasetWrapper: + +```python +from mmengine.dataset import BaseDataset +from mmengine.registry import DATASETS + + +@DATASETS.register_module() +class ExampleDatasetWrapper: + + def __init__(self, dataset, lazy_init=False, ...): + # Build the source dataset(self.dataset) + if isinstance(dataset, dict): + self.dataset = DATASETS.build(dataset) + elif isinstance(dataset, BaseDataset): + self.dataset = dataset + else: + raise TypeError( + 'elements in datasets sequence should be config or ' + f'`BaseDataset` instance, but got {type(dataset)}') + # Record the meta information of source dataset + self._metainfo = self.dataset.metainfo + + ''' + 1. Implement some code here to record some of the hyperparameters used to wrap the dataset. + ''' + + self._fully_initialized = False + if not lazy_init: + self.full_init() + + def full_init(self): + if self._fully_initialized: + return + + # Initialize the source dataset completely + self.dataset.full_init() + + ''' + 2. Implement some code here to wrap the source dataset. + ''' + + self._fully_initialized = True + + @force_full_init + def _get_ori_dataset_idx(self, idx: int): + + ''' + 3. Implement some code here to map the wrapped index `idx` to the index of the source dataset 'ori_idx'. + ''' + ori_idx = ... + + return ori_idx + + # Provide the same external interface as `self.dataset `. + @force_full_init + def get_data_info(self, idx): + sample_idx = self._get_ori_dataset_idx(idx) + return self.dataset.get_data_info(sample_idx) + + # Provide the same external interface as `self.dataset `. + def __getitem__(self, idx): + if not self._fully_initialized: + warnings.warn('Please call `full_init` method manually to ' + 'accelerate the speed.') + self.full_init() + + sample_idx = self._get_ori_dataset_idx(idx) + return self.dataset[sample_idx] + + # Provide the same external interface as `self.dataset `. + @force_full_init + def __len__(self): + + ''' + 4. Implement some code here to calculate the length of the wrapped dataset. + ''' + len_wrapper = ... + + return len_wrapper + + # Provide the same external interface as `self.dataset `. + @property + def metainfo(self) + return copy.deepcopy(self._metainfo) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/config.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/config.md new file mode 100644 index 0000000000000000000000000000000000000000..f86319e5644b06e26021894ac7f796cc643f7041 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/config.md @@ -0,0 +1,598 @@ +# Config + +MMEngine implements an abstract configuration class (`Config`) to provide a unified configuration access interface for users. `Config` supports different type of configuration file, including `python`, `json` and `yaml`, and you can choose the type according to your preference. `Config` overrides some magic method, which could help you access the data stored in `Config` just like getting values from `dict`, or getting attributes from instances. Besides, `Config` also provides an inheritance mechanism, which could help you better organize and manage the configuration files. + +Before starting the tutorial, let's download the configuration files needed in the tutorial (it is recommended to execute them in a temporary directory to facilitate deleting these files latter.): + +```bash +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/config_sgd.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/cross_repo.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/custom_imports.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/demo_train.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/example.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/learn_read_config.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/my_module.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/optimizer_cfg.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/predefined_var.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/refer_base_var.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_delete_key.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_lr0.01.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_runtime.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/runtime_cfg.py +wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/modify_base_var.py +``` + +## Read the configuration file + +`Config` provides a uniform interface `Config.fromfile()` to read and parse configuration files. + +A valid configuration file should define a set of key-value pairs, and here are a few examples: + +Python: + +```Python +test_int = 1 +test_list = [1, 2, 3] +test_dict = dict(key1='value1', key2=0.1) +``` + +Json: + +```json +{ + "test_int": 1, + "test_list": [1, 2, 3], + "test_dict": {"key1": "value1", "key2": 0.1} +} +``` + +YAML: + +```yaml +test_int: 1 +test_list: [1, 2, 3] +test_dict: + key1: "value1" + key2: 0.1 +``` + +For the above three formats, assuming the file names are `config.py`, `config.json`, and `config.yml`. Loading these files with `Config.fromfile('config.xxx')` will return the same result, which contain `test_int`, `test_list` and `test_dict` 3 variables. + +Let's take `config.py` as an example: + +```python +from mmengine.config import Config + +cfg = Config.fromfile('learn_read_config.py') +print(cfg) +``` + +``` +Config (path: learn_read_config.py): {'test_int': 1, 'test_list': [1, 2, 3], 'test_dict': {'key1': 'value1', 'key2': 0.1}} +``` + +## How to use `Config` + +After loading the configuration file, we can access the data stored in `Config` instance just like getting/setting values from `dict`, or getting/setting attributes from instances. + +```python +print(cfg.test_int) +print(cfg.test_list) +print(cfg.test_dict) +cfg.test_int = 2 + +print(cfg['test_int']) +print(cfg['test_list']) +print(cfg['test_dict']) +cfg['test_list'][1] = 3 +print(cfg['test_list']) +``` + +``` +1 +[1, 2, 3] +{'key1': 'value1', 'key2': 0.1} +2 +[1, 2, 3] +{'key1': 'value1', 'key2': 0.1} +[1, 3, 3] +``` + +```{note} +The `dict` object parsed by `Config` will be converted to `ConfigDict`, and then we can access the value of the `dict` the same as accessing the attribute of an instance. +``` + +We can use the `Config` combination with the [Registry](./registry.md) to build registered instance easily. + +Here is an example of defining optimizers in a configuration file. + +`config_sgd.py`: + +```python +optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001) +``` + +Suppose we have defined a registry `OPTIMIZERS`, which includes various optimizers. Then we can build the optimizer as below + +```python +from mmengine import Config, optim +from mmengine.registry import OPTIMIZERS + +import torch.nn as nn + +cfg = Config.fromfile('config_sgd.py') + +model = nn.Conv2d(1, 1, 1) +cfg.optimizer.params = model.parameters() +optimizer = OPTIMIZERS.build(cfg.optimizer) +print(optimizer) +``` + +``` +SGD ( +Parameter Group 0 + dampening: 0 + foreach: None + lr: 0.1 + maximize: False + momentum: 0.9 + nesterov: False + weight_decay: 0.0001 +) +``` + +## Inheritance between configuration files + +Sometimes, the difference between two different configuration files is so small that only one field may be changed. Therefore, it's unwise to copy and paste everything only to modify one line, which makes it hard for us to locate the specific difference after a long time. + +In another case, multiple configuration files may have the same batch of fields, and we have to copy and paste them in different configuration files. It will also be hard to maintain these fields in a long time. + +We address these issues with inheritance mechanism, detailed as below. + +### Overview of inheritance mechanism + +Here is an example to illustrate the inheritance mechanism. + +`optimizer_cfg.py`: + +```python +optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) +``` + +`resnet50.py`: + +```python +_base_ = ['optimizer_cfg.py'] +model = dict(type='ResNet', depth=50) +``` + +Although we don't define `optimizer` in `resnet50.py`, since we wrote `_base_ = ['optimizer_cfg.py']`, it will inherit the fields defined in `optimizer_cfg.py`. + +```python +cfg = Config.fromfile('resnet50.py') +print(cfg.optimizer) +``` + +``` +{'type': 'SGD', 'lr': 0.02, 'momentum': 0.9, 'weight_decay': 0.0001} +``` + +`_base_` is a reserved field for the configuration file. It specifies the inherited base files for the current file. Inheriting multiple files will get all the fields at the same time, but it requires that there are no repeated fields defined in all base files. + +`runtime_cfg.py`: + +```python +gpu_ids = [0, 1] +``` + +`resnet50_runtime.py`: + +```python +_base_ = ['optimizer_cfg.py', 'runtime_cfg.py'] +model = dict(type='ResNet', depth=50) +``` + +In this case, reading the `resnet50_runtime.py` will give you 3 fields `model`, `optimizer`, and `gpu_ids`. + +```python +cfg = Config.fromfile('resnet50_runtime.py') +print(cfg.optimizer) +``` + +``` +{'type': 'SGD', 'lr': 0.02, 'momentum': 0.9, 'weight_decay': 0.0001} +``` + +By this way, we can disassemble the configuration file, define some general configuration files, and inherit them in the specific configuration file. This could avoid defining a lot of duplicated contents in multiple configuration files. + +### Modify the inherited fields + +Sometimes, we want to modify some of the fields in the inherited files. For example we want to modify the learning rate from 0.02 to 0.01 after inheriting `optimizer_cfg.py`. + +In this case, you can simply redefine the fields in the new configuration file. Note that since the optimizer field is a dictionary, we only need to redefine the modified fields. This rule also applies to adding fields. + +`resnet50_lr0.01.py`: + +```python +_base_ = ['optimizer_cfg.py', 'runtime_cfg.py'] +model = dict(type='ResNet', depth=50) +optimizer = dict(lr=0.01) +``` + +After reading this configuration file, you can get the desired result. + +```python +cfg = Config.fromfile('resnet50_lr0.01.py') +print(cfg.optimizer) +``` + +``` +{'type': 'SGD', 'lr': 0.01, 'momentum': 0.9, 'weight_decay': 0.0001} +``` + +For non-dictionary fields, such as integers, strings, lists, etc., they can be completely overwritten by redefining them. For example, the code block below will change the value of the `gpu_ids` to `[0]`. + +```python +_base_ = ['optimizer_cfg.py', 'runtime_cfg.py'] +model = dict(type='ResNet', depth=50) +gpu_ids = [0] +``` + +### Delete key in `dict` + +Sometimes we not only want to modify or add the keys, but also want to delete them. In this case, we need to set `_delete_=True` in the target field(`dict`) to delete all the keys that do not appear in the newly defined dictionary. + +`resnet50_delete_key.py`: + +```python +_base_ = ['optimizer_cfg.py', 'runtime_cfg.py'] +model = dict(type='ResNet', depth=50) +optimizer = dict(_delete_=True, type='SGD', lr=0.01) +``` + +At this point, `optimizer` will only have the keys `type` and `lr`. `momentum` and `weight_decay` will no longer exist. + +```python +cfg = Config.fromfile('resnet50_delete_key.py') +print(cfg.optimizer) +``` + +``` +{'type': 'SGD', 'lr': 0.01} +``` + +### Reference of the inherited file + +Sometimes we want to reuse the field defined in `_base_`, we can get a copy of the corresponding variable by using `{{_base_.xxxx}}`: + +`refer_base_var.py` + +```python +_base_ = ['resnet50.py'] +a = {{_base_.model}} +``` + +After parsing, the value of `a` becomes `model` defined in `resnet50.py` + +```python +cfg = Config.fromfile('refer_base_var.py') +print(cfg.a) +``` + +``` +{'type': 'ResNet', 'depth': 50} +``` + +We can use this way to get the variables defined in `_base_` in the `json`, `yaml`, and `python` configuration files. + +Although this way is general for all types of files, there are some syntactic limitations that prevent us from taking full advantage of the dynamic nature of the `python` configuration file. For example, if we want to modify a variable defined in `_base_`: + +```python +_base_ = ['resnet50.py'] +a = {{_base_.model}} +a['type'] = 'MobileNet' +``` + +The `Config` is not able to parse such a configuration file (it will raise an error when parsing). The `Config` provides a more `pythonic` way to modify base variables for `python` configuration files. + +`modify_base_var.py`: + +```python +_base_ = ['resnet50.py'] +a = _base_.model +a.type = 'MobileNet' +``` + +```python +cfg = Config.fromfile('modify_base_var.py') +print(cfg.a) +``` + +``` +{'type': 'MobileNet', 'depth': 50} +``` + +## Dump the configuration file + +The user may pass some parameters to modify some fields of the configuration file at the entry point of the training script. Therefore, we provide the `dump` method to export the changed configuration file. + +Similar to reading the configuration file, the user can choose the format of the dumped file by using `cfg.dump('config.xxx')`. `dump` can also export configuration files with inheritance relationships, and the dumped files can be used independently without the files defined in `_base_`. + +Based on the `resnet50.py` defined above, we can load and dump it like this: + +```python +cfg = Config.fromfile('resnet50.py') +cfg.dump('resnet50_dump.py') +``` + +`resnet50_dump.py` + +```python +optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) +model = dict(type='ResNet', depth=50) +``` + +Similarly, we can dump configuration files in `json`, `yaml` format: + +`resnet50_dump.yaml` + +```yaml +model: + depth: 50 + type: ResNet +optimizer: + lr: 0.02 + momentum: 0.9 + type: SGD + weight_decay: 0.0001 +``` + +`resnet50_dump.json` + +````json +{"optimizer": {"type": "SGD", "lr": 0.02, "momentum": 0.9, "weight_decay": 0.0001}, "model": {"type": "ResNet", "depth": 50}} + +In addition, `dump` can also dump `cfg` loaded from a dictionary. + +```python +cfg = Config(dict(a=1, b=2)) +cfg.dump('dump_dict.py') +```` + +`dump_dict.py` + +```python +a=1 +b=2 +``` + +## Advanced usage + +In this section, we'll introduce some advanced usage of the `Config`, and some tips that could make it easier for users to develop and use downstream repositories. + +### Predefined fields + +Sometimes we need some fields in the configuration file, which are related to the path to the workspace. For example, we define a working directory in the configuration file that holds the models and logs for this set of experimental configurations. We expect to have different working directories for different configuration files. A common choice is to use the configuration file name directly as part of the working directory name. +Taking `predefined_var.py` as an example: + +```Python +work_dir = './work_dir/{{fileBasenameNoExtension}}' +``` + +Here `{{fileBasenameNoExtension}}` means the filename without suffix `.py` of the config file, and the variable in `{{}}` will be interpreted as `predefined_var` + +```python +cfg = Config.fromfile('./predefined_var.py') +print(cfg.work_dir) +``` + +```shell +./work_dir/predefined_var +``` + +Currently, there are 4 predefined fields referenced from the relevant fields defined in [VS Code](https://code.visualstudio.com/docs/editor/variables-reference). + +- `{{fileDirname}}` - the directory name of the current file, e.g. `/home/your-username/your-project/folder` +- `{{fileBasename}}` - the filename of the current file, e.g. `file.py` +- `{{fileBasenameNoExtension}}` - the filename of the current file without the extension, e.g. `file` +- `{{fileExtname}}` - the extension of the current file, e.g. `.py` + +### Modify the fields in command line + +Sometimes we only want to modify part of the configuration and do not want to modify the configuration file itself. For example, if we want to change the learning rate during the experiment but do not want to write a new configuration file, the common practice is to pass the parameters at the command line to override the relevant configuration. + +If we want to modify some internal parameters, such as the learning rate of the optimizer, the number of channels in the convolution layer etc., `Config` provides a standard procedure that allows us to modify the parameters at any level easily from the command line. + +**Training script:** + +`demo_train.py` + +```python +import argparse + +from mmengine.config import Config, DictAction + + +def parse_args(): + parser = argparse.ArgumentParser(description='Train a model') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + print(cfg) + + +if __name__ == '__main__': + main() +``` + +The sample configuration file is as follows. + +`example.py` + +```python +model = dict(type='CustomModel', in_channels=[1, 2, 3]) +optimizer = dict(type='SGD', lr=0.01) +``` + +We can modify the internal fields from the command line by `.` For example, if we want to modify the learning rate, we only need to execute the script like this: + +```bash +python demo_train.py ./example.py --cfg-options optimizer.lr=0.1 +``` + +``` +Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 2, 3]}, 'optimizer': {'type': 'SGD', 'lr': 0.1}} +``` + +We successfully modified the learning rate from 0.01 to 0.1. If we want to change a list or a tuple, such as `in_channels` in the above example. We need to put double quotes around `()`, `[]` when assigning the value on the command line. + +```bash +python demo_train.py ./example.py --cfg-options model.in_channels="[1, 1, 1]" +``` + +``` +Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 1, 1]}, 'optimizer': {'type': 'SGD', 'lr': 0.01}} +``` + +```{note} +The standard procedure only supports modifying String, Integer, Floating Point, Boolean, None, List, and Tuple fields from the command line. For the elements of list and tuple instance, each of them must be one of the above seven types. +``` + +:::{note} +The behavior of `DictAction` is similar with `"extend"`. It stores a list, and extends each argument value to the list, like: + +```bash +python demo_train.py ./example.py --cfg-options optimizer.type="Adam" --cfg-options model.in_channels="[1, 1, 1]" +``` + +``` +Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 1, 1]}, 'optimizer': {'type': 'Adam', 'lr': 0.01}} +``` + +::: + +### import the custom module + +If we customize a module and register it into the corresponding registry, could we directly build it from the configuration file as the previous [section](#how-to-use-config) does? The answer is "I don't know" since I'm not sure the registration process has been triggered. To solve this "unknown" case, `Config` provides the `custom_imports` function, to make sure your module could be registered as expected. + +For example, we customize an optimizer: + +```python +from mmengine.registry import OPTIMIZERS + +@OPTIMIZERS.register_module() +class CustomOptim: + pass +``` + +A matched config file: + +`my_module.py` + +```python +optimizer = dict(type='CustomOptim') +``` + +To make sure `CustomOptim` will be registered, we should set the `custom_imports` field like this: + +`custom_imports.py` + +```python +custom_imports = dict(imports=['my_module'], allow_failed_imports=False) +optimizer = dict(type='CustomOptim') +``` + +And then, once the `custom_imports` can be loaded successfully, we can build the `CustomOptim` from the `custom_imports.py`. + +```python +cfg = Config.fromfile('custom_imports.py') + +from mmengine.registry import OPTIMIZERS + +custom_optim = OPTIMIZERS.build(cfg.optimizer) +print(custom_optim) +``` + +``` + +``` + +### Inherit configuration files across repository + +It is annoying to copy a large number of configuration files when developing a new repository based on some existing repositories. To address this issue, `Config` support inherit configuration files from other repositories. For example, based on MMDetection, we want to develop a repository, we can use the MMDetection configuration file like this: + +`cross_repo.py` + +```python +_base_ = [ + 'mmdet::_base_/schedules/schedule_1x.py', + 'mmdet::_base_/datasets/coco_instance.py', + 'mmdet::_base_/default_runtime.py', + 'mmdet::_base_/models/faster_rcnn_r50_fpn.py', +] +``` + +```python +cfg = Config.fromfile('cross_repo.py') +print(cfg.train_cfg) +``` + +``` +{'type': 'EpochBasedTrainLoop', 'max_epochs': 12, 'val_interval': 1, '_scope_': 'mmdet'} +``` + +`Config` will parse `mmdet::` to find mmdet package and inherits the specified configuration file. Actually, as long as the `setup.py` of the repository(package) conforms to [MMEngine Installation specification](todo), `Config` can use `{package_name}::` to inherit the specific configuration file. + +### Get configuration files across repository + +`Config` also provides `get_config` and `get_model` to get the configuration file and the trained model from the downstream repositories. + +The usage of `get_config` and `get_model` are similar to the previous section: + +An example of `get_config`: + +```python +from mmengine.hub import get_config + +cfg = get_config( + 'mmdet::faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py', pretrained=True) +print(cfg.model_path) +``` + +``` +https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth +``` + +An example of `get_model`: + +```python +from mmengine.hub import get_model + +model = get_model( + 'mmdet::faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py', pretrained=True) +print(type(model)) +``` + +``` +http loads checkpoint from path: https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth + +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/cross_library.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/cross_library.md new file mode 100644 index 0000000000000000000000000000000000000000..26f7d00b69c9b7001a0c9006ceb838aff03da43a --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/cross_library.md @@ -0,0 +1,103 @@ +# Use modules from other libraries + +Based on MMEngine's [Registry](registry.md) and [Config](config.md), users can build modules across libraries. +For example, use [MMClassification](https://github.com/open-mmlab/mmclassification)'s backbones in [MMDetection](https://github.com/open-mmlab/mmdetection), or [MMDetection](https://github.com/open-mmlab/mmdetection)'s data transforms in [MMRotate](https://github.com/open-mmlab/mmrotate), or using [MMDetection](https://github.com/open-mmlab/mmdetection)'s detectors in [MMTracking](https://github.com/open-mmlab/mmtracking). + +Modules registered in the same registry tree can be called across libraries by adding the **package name prefix** before the module's type in the config. Here are some common examples: + +## Use backbone across libraries + +Taking the example of using MMClassification's ConvNeXt in MMDetection: + +Firstly, adding the `custom_imports` field to the config to register the backbones of MMClassification to the registry. + +Secondly, adding the package name of MMClassification `mmcls` to the `type` of the backbone as a prefix: `mmcls.ConvNeXt` + +```python +# Use custom_imports to register mmcls models to the registry +custom_imports = dict(imports=['mmcls.models'], allow_failed_imports=False) + +model = dict( + type='MaskRCNN', + data_preprocessor=dict(...), + backbone=dict( + type='mmcls.ConvNeXt', # Add mmcls prefix to enable cross-library mechanism + arch='tiny', + out_indices=[0, 1, 2, 3], + drop_path_rate=0.4, + layer_scale_init_value=1.0, + gap_before_final_norm=False, + init_cfg=dict( + type='Pretrained', + checkpoint= + 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-tiny_3rdparty_32xb128-noema_in1k_20220301-795e9634.pth', + prefix='backbone.')), + neck=dict(...), + rpn_head=dict(...)) +``` + +## Use data transform across libraries + +As with the example of backbone above, cross-library calls can be simply achieved by adding custom_imports and prefix in the config: + +```python +# Use custom_imports to register mmdet transforms to the registry +custom_imports = dict(imports=['mmdet.datasets.transforms'], allow_failed_imports=False) + +# Add mmdet prefix to enable cross-library mechanism +train_pipeline=[ + dict(type='mmdet.LoadImageFromFile'), + dict(type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'), + dict(type='ConvertBoxType', box_type_mapping=dict(gt_bboxes='rbox')), + dict(type='mmdet.Resize', scale=(1024, 2014), keep_ratio=True), + dict(type='mmdet.RandomFlip', prob=0.5), + dict(type='mmdet.PackDetInputs') +] +``` + +## Use detector across libraries + +Using an algorithm from another library is a little bit complex. + +An algorithm contains multiple submodules. Each submodule needs to add a prefix to its `type`. Take using MMDetection's YOLOX in MMTracking as an example: + +```python +# Use custom_imports to register mmdet models to the registry +custom_imports = dict(imports=['mmdet.models'], allow_failed_imports=False) + +model = dict( + type='mmdet.YOLOX', + backbone=dict(type='mmdet.CSPDarknet', deepen_factor=1.33, widen_factor=1.25), + neck=dict( + type='mmdet.YOLOXPAFPN', + in_channels=[320, 640, 1280], + out_channels=320, + num_csp_blocks=4), + bbox_head=dict( + type='mmdet.YOLOXHead', num_classes=1, in_channels=320, feat_channels=320), + train_cfg=dict(assigner=dict(type='mmdet.SimOTAAssigner', center_radius=2.5))) +``` + +To prevent adding prefix to all of the submodules manually, the `_scope_` keyword is introduced. When the `_scope_` keyword is added to the config of a module, all submodules' scope will be changed by the `_scope_` keyword. Here is an example config: + +```python +# Use custom_imports to register mmdet models to the registry +custom_imports = dict(imports=['mmdet.models'], allow_failed_imports=False) + +model = dict( + _scope_='mmdet', # use the _scope_ keyword to avoid adding prefix to all submodules + type='YOLOX', + backbone=dict(type='CSPDarknet', deepen_factor=1.33, widen_factor=1.25), + neck=dict( + type='YOLOXPAFPN', + in_channels=[320, 640, 1280], + out_channels=320, + num_csp_blocks=4), + bbox_head=dict( + type='YOLOXHead', num_classes=1, in_channels=320, feat_channels=320), + train_cfg=dict(assigner=dict(type='SimOTAAssigner', center_radius=2.5))) +``` + +These two examples are equivalent to each other. + +If you want to know more about the registry and config, please refer to [Config Tutorial](config.md) and [Registry Tutorial](registry.md) diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_element.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_element.md new file mode 100644 index 0000000000000000000000000000000000000000..d07560b7ef3128ce0aadfb8648272a11ca068a8a --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_element.md @@ -0,0 +1,3 @@ +# Abstract Data Element + +Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/data_element.html). diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_transform.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_transform.md new file mode 100644 index 0000000000000000000000000000000000000000..0eb4d22710db5f96ff62685735e62cb7d9545b19 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/data_transform.md @@ -0,0 +1,156 @@ +# Data transform + +In the OpenMMLab repositories, dataset construction and data preparation are decoupled from each other. +Usually, the dataset construction only parses the dataset and records the basic information of each sample, +while the data preparation is performed by a series of data transforms, such as data loading, preprocessing, +and formatting based on the basic information of the samples. + +## To use Data Transforms + +In MMEngine, we use various callable data transforms classes to perform data manipulation. These data +transformation classes can accept several configuration parameters for instantiation and then process the +input data dictionary by calling. Also, all data transforms accept a dictionary as input and output the +processed data as a dictionary. A simple example is as belows: + +```{note} +In MMEngine, we don't have the implementations of data transforms. you can find the base data transform class +and many other data transforms in MMCV. So you need to install MMCV before learning this tutorial, see the +{external+mmcv:doc}`MMCV installation guild `. +``` + +```python +>>> import numpy as np +>>> from mmcv.transforms import Resize +>>> +>>> transform = Resize(scale=(224, 224)) +>>> data_dict = {'img': np.random.rand(256, 256, 3)} +>>> data_dict = transform(data_dict) +>>> print(data_dict['img'].shape) +(224, 224, 3) +``` + +## To use in Config Files + +In config files, we can compose multiple data transforms as a list, called a data pipeline. And the data +pipeline is an argument of the dataset. + +Usually, a data pipeline consists of the following parts: + +1. Data loading, use [`LoadImageFromFile`](mmcv.transforms.LoadImageFromFile) to load image files. +2. Label loading, use [`LoadAnnotations`](mmcv.transforms.LoadAnnotations) to load the bboxes, semantic segmentation and keypoint annotations. +3. Data processing and augmentation, like [`RandomResize`](mmcv.transforms.RandomResize). +4. Data formatting, we use different data transforms for different tasks. And the data transform for specified + task is implemented in the corresponding repository. For example, the data formatting transform for image + classification task is `PackClsInputs` and it's in MMClassification. + +Here, taking the classification task as an example, we show a typical data pipeline in the figure below. For +each sample, the basic information stored in the dataset is a dictionary as shown on the far left side of the +figure, after which, every blue block represents a data transform, and in every data transform, we add some new fields (marked in green) or update some existing fields (marked in orange) in the data dictionary. + +
+ +
+ +If want to use the above data pipeline in our config file, use the below settings: + +```python +test_dataloader = dict( + batch_size=32, + dataset=dict( + type='ImageNet', + data_root='data/imagenet', + pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', size=256, keep_ratio=True), + dict(type='CenterCrop', crop_size=224), + dict(type='PackClsInputs'), + ] + ) +) +``` + +## Common Data Transforms + +According to the functionality, the data transform classes can be divided into data loading, data +pre-processing & augmentation and data formatting. + +### Data Loading + +To support loading large-scale dataset, usually we won't load all dense data during dataset construction, but +only load the file path of these data. Therefore, we need to load these data in the data pipeline. + +| Data Transforms | Functionality | +| :------------------------------------------------------: | :-----------------------------------------------------------------------------------: | +| [`LoadImageFromFile`](mmcv.transforms.LoadImageFromFile) | Load images according to the path. | +| [`LoadAnnotations`](mmcv.transforms.LoadImageFromFile) | Load and format annotations information, including bbox, segmentation map and others. | + +### Data Pre-processing & Augmentation + +Data transforms for pre-processing and augmentation usually manipulate the image and annotation data, like +cropping, padding, resizing and others. + +| Data Transforms | Functionality | +| :--------------------------------------------------------: | :------------------------------------------------------------: | +| [`Pad`](mmcv.transforms.Pad) | Pad the margin of images. | +| [`CenterCrop`](mmcv.transforms.CenterCrop) | Crop the image and keep the center part. | +| [`Normalize`](mmcv.transforms.Normalize) | Normalize the image pixels. | +| [`Resize`](mmcv.transforms.Resize) | Resize images to the specified scale or ratio. | +| [`RandomResize`](mmcv.transforms.RandomResize) | Resize images to a random scale in the specified range. | +| [`RandomChoiceResize`](mmcv.transforms.RandomChoiceResize) | Resize images to a random scale from several specified scales. | +| [`RandomGrayscale`](mmcv.transforms.RandomGrayscale) | Randomly grayscale images. | +| [`RandomFlip`](mmcv.transforms.RandomFlip) | Randomly flip images. | + +### Data Formatting + +Data formatting transforms will convert the data to some specified type. + +| Data Transforms | Functionality | +| :----------------------------------------------: | :---------------------------------------------------: | +| [`ToTensor`](mmcv.transforms.ToTensor) | Convert the data of specified field to `torch.Tensor` | +| [`ImageToTensor`](mmcv.transforms.ImageToTensor) | Convert images to `torch.Tensor` in PyTorch format. | + +## Custom Data Transform Classes + +To implement a new data transform class, the class needs to inherit `BaseTransform` and implement `transform` +method. Here, we use a simple flip transforms (`MyFlip`) as example: + +```python +import random +import mmcv +from mmcv.transforms import BaseTransform, TRANSFORMS + +@TRANSFORMS.register_module() +class MyFlip(BaseTransform): + def __init__(self, direction: str): + super().__init__() + self.direction = direction + + def transform(self, results: dict) -> dict: + img = results['img'] + results['img'] = mmcv.imflip(img, direction=self.direction) + return results +``` + +Then, we can instantiate a `MyFlip` object and use it to process our data dictionary. + +```python +import numpy as np + +transform = MyFlip(direction='horizontal') +data_dict = {'img': np.random.rand(224, 224, 3)} +data_dict = transform(data_dict) +processed_img = data_dict['img'] +``` + +Or, use it in the data pipeline by modifying our config file: + +```python +pipeline = [ + ... + dict(type='MyFlip', direction='horizontal'), + ... +] +``` + +Please note that to use the class in our config file, we need to confirm the `MyFlip` class will be imported +during running. diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/distributed.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/distributed.md new file mode 100644 index 0000000000000000000000000000000000000000..8edae584faa218f9542f0f9cd7a05571473288d2 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/distributed.md @@ -0,0 +1,57 @@ +# Distribution Communication + +In distributed training, different processes sometimes need to apply different logics depending on their ranks, local_ranks, etc. +They also need to communicate with each other and do synchronizations on data. +These demands rely on distributed communication. +PyTorch provides a set of basic distributed communication primitives. +Based on these primitives, MMEngine provides some higher level APIs to meet more diverse demands. +Using these APIs provided by MMEngine, modules can: + +- ignore the differences between distributed/non-distributed environment +- deliver data in various types apart from Tensor +- ignore the frameworks or backends used for communication + +These APIs are roughly categorized into 3 types: + +- Initialization: `init_dist` for setting up distributed environment for the runner +- Query & control: functions including `get_world_size` for querying `world_size`, `rank` and other distributed information +- Collective communication: collective communication functions such as `all_reduce` + +We will detail on these APIs in the following chapters. + +## Initialization + +- [init_dist](mmengine.dist.init_dist): Launch function of distributed training. Currently it supports 3 launchers including pytorch, slurm and MPI. It also setup the given communication backends, defaults to NCCL. + +## Query and control + +The query and control functions are all argument free. +They can be used in both distributed and non-distributed environment. +Their functionalities are listed below: + +- [get_world_size](mmengine.dist.get_world_size): Returns the number of processes in current process group. Returns 1 when non-distributed +- [get_rank](mmengine.dist.get_rank): Returns the global rank of current process in current process group. Returns 0 when non-distributed +- [get_backend](mmengine.dist.get_backend): Returns the communication backends used by current process group. Returns `None` when non-distributed +- [get_local_rank](mmengine.dist.get_local_rank): Returns the local rank of current process in current process group. Returns 0 when non-distributed +- [get_local_size](mmengine.dist.get_local_size): Returns the number of processes which are both in current process group and on the same machine as the current process. Returns 1 when non-distributed +- [get_dist_info](mmengine.dist.get_dist_info): Returns the world_size and rank of the current process group. Returns world_size = 1, rank = 0 when non-distributed +- [is_main_process](mmengine.dist.is_main_process): Returns `True` if current process is rank 0 in current process group, otherwise `False` . Always returns `True` when non-distributed +- [master_only](mmengine.dist.master_only): A function decorator. Functions decorated by `master_only` will only execute on rank 0 process. +- [barrier](mmengine.dist.barrier): A synchronization primitive. Every process will hold until all processes in the current process group reach the same barrier location + +## Collective communication + +Collective communication functions are used for data transfer between processes in the same process group. +We provide the following APIs based on PyTorch native functions including all_reduce, all_gather, gather, broadcast. +These APIs are compatible with non-distributed environment and support more data types apart from Tensor. + +- [all_reduce](mmengine.dist.all_reduce): AllReduce operation on Tensors in the current process group +- [all_gather](mmengine.dist.all_gather): AllGather operation on Tensors in the current process group +- [gather](mmengine.dist.gather): Gather Tensors in the current process group to a destinated rank +- [broadcast](mmengine.dist.broadcast): Broadcast a Tensor to all processes in the current process group +- [sync_random_seed](mmengine.dist.sync_random_seed): Synchronize random seed between processes in the current process group +- [broadcast_object_list](mmengine.dist.broadcast_object_list): Broadcast a list of Python objects. It requires the object can be serialized by Pickle. +- [all_reduce_dict](mmengine.dist.all_reduce_dict): AllReduce operation on dict. It is based on broadcast and all_reduce. +- [all_gather_object](mmengine.dist.all_gather_object): AllGather operations on any Python object than can be serialized by Pickle. It is based on all_gather +- [gather_object](mmengine.dist.gather_object): Gather Python objects that can be serialized by Pickle +- [collect_results](mmengine.dist.collect_results): Unified API for collecting a list of data in current process group. It support both CPU and GPU communication diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/fileio.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/fileio.md new file mode 100644 index 0000000000000000000000000000000000000000..9de13553d2da2b5f66c11e5684f71ba4432093ff --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/fileio.md @@ -0,0 +1,213 @@ +# File IO + +`MMEngine` implements a unified set of file reading and writing interfaces in `fileio` module. With the `fileio` module, we can use the same function to handle different file formats, such as `json`, `yaml` and `pickle`. Other file formats can also be easily extended. + +The `fileio` module also supports reading and writing files from a variety of file storage backends, including disk, Petrel (for internal use), Memcached, LMDB, and HTTP. + +## Load and dump data + +`MMEngine` provides a universal API for loading and dumping data, currently supported formats are `json`, `yaml`, and `pickle`. + +### Load from disk or dump to disk + +```python +from mmengine import load, dump + +# load data from a file +data = load('test.json') +data = load('test.yaml') +data = load('test.pkl') +# load data from a file-like object +with open('test.json', 'r') as f: + data = load(f, file_format='json') + +# dump data to a string +json_str = dump(data, file_format='json') + +# dump data to a file with a filename (infer format from file extension) +dump(data, 'out.pkl') + +# dump data to a file with a file-like object +with open('test.yaml', 'w') as f: + data = dump(data, f, file_format='yaml') +``` + +### Load from other backends or dump to other backends + +```python +from mmengine import load, dump + +# load data from a file +data = load('s3://bucket-name/test.json') +data = load('s3://bucket-name/test.yaml') +data = load('s3://bucket-name/test.pkl') + +# dump data to a file with a filename (infer format from file extension) +dump(data, 's3://bucket-name/out.pkl') +``` + +It is also very convenient to extend the API to support more file formats. All you need to do is to write a file handler inherited from `BaseFileHandler` and register it with one or several file formats. + +```python +from mmengine import register_handler, BaseFileHandler + +# To register multiple file formats, a list can be used as the argument. +# @register_handler(['txt', 'log']) +@register_handler('txt') +class TxtHandler1(BaseFileHandler): + + def load_from_fileobj(self, file): + return file.read() + + def dump_to_fileobj(self, obj, file): + file.write(str(obj)) + + def dump_to_str(self, obj, **kwargs): + return str(obj) +``` + +Here is an example of `PickleHandler`. + +```python +from mmengine import BaseFileHandler +import pickle + +class PickleHandler(BaseFileHandler): + + def load_from_fileobj(self, file, **kwargs): + return pickle.load(file, **kwargs) + + def load_from_path(self, filepath, **kwargs): + return super(PickleHandler, self).load_from_path( + filepath, mode='rb', **kwargs) + + def dump_to_str(self, obj, **kwargs): + kwargs.setdefault('protocol', 2) + return pickle.dumps(obj, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + kwargs.setdefault('protocol', 2) + pickle.dump(obj, file, **kwargs) + + def dump_to_path(self, obj, filepath, **kwargs): + super(PickleHandler, self).dump_to_path( + obj, filepath, mode='wb', **kwargs) +``` + +## Load a text file as a list or dict + +For example `a.txt` is a text file with 5 lines. + +``` +a +b +c +d +e +``` + +### Load from disk + +Use `list_from_file` to load the list from `a.txt`. + +```python +from mmengine import list_from_file + +print(list_from_file('a.txt')) +# ['a', 'b', 'c', 'd', 'e'] +print(list_from_file('a.txt', offset=2)) +# ['c', 'd', 'e'] +print(list_from_file('a.txt', max_num=2)) +# ['a', 'b'] +print(list_from_file('a.txt', prefix='/mnt/')) +# ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e'] +``` + +For example `b.txt` is a text file with 3 lines. + +``` +1 cat +2 dog cow +3 panda +``` + +Then use `dict_from_file` to load the dict from `b.txt`. + +```python +from mmengine import dict_from_file + +print(dict_from_file('b.txt')) +# {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'} +print(dict_from_file('b.txt', key_type=int)) +# {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'} +``` + +### Load from other backends + +Use `list_from_file` to load the list from `s3://bucket-name/a.txt`. + +```python +from mmengine import list_from_file + +print(list_from_file('s3://bucket-name/a.txt')) +# ['a', 'b', 'c', 'd', 'e'] +print(list_from_file('s3://bucket-name/a.txt', offset=2)) +# ['c', 'd', 'e'] +print(list_from_file('s3://bucket-name/a.txt', max_num=2)) +# ['a', 'b'] +print(list_from_file('s3://bucket-name/a.txt', prefix='/mnt/')) +# ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e'] +``` + +Use `dict_from_file` to load the dict from `s3://bucket-name/b.txt`. + +```python +from mmengine import dict_from_file + +print(dict_from_file('s3://bucket-name/b.txt')) +# {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'} +print(dict_from_file('s3://bucket-name/b.txt', key_type=int)) +# {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'} +``` + +## Load and dump checkpoints + +We can read the checkpoints from disk or internet in the following way. + +```python +import torch + +filepath1 = '/path/of/your/checkpoint1.pth' +filepath2 = 'http://path/of/your/checkpoint3.pth' + +# read filepath1 from disk +checkpoint = torch.load(filepath1) +# save checkpoints to disk +torch.save(checkpoint, filepath1) + +# read filepath2 from internet +checkpoint = torch.utils.model_zoo.load_url(filepath2) +``` + +In `MMEngine`, reading and writing checkpoints in different storage forms can be uniformly implemented with `load_checkpoint` and `save_checkpoint`. + +```python +from mmengine import load_checkpoint, save_checkpoint + +filepath1 = '/path/of/your/checkpoint1.pth' +filepath2 = 's3://bucket-name/path/of/your/checkpoint1.pth' +filepath3 = 'http://path/of/your/checkpoint3.pth' + +# read checkpoints from disk +checkpoint = load_checkpoint(filepath1) +# save checkpoints from disk +save_checkpoint(checkpoint, filepath1) + +# read checkpoints from s3 +checkpoint = load_checkpoint(filepath2) +# save checkpoints from s3 +save_checkpoint(checkpoint, filepath2) + +# read checkpoints from internet +checkpoint = load_checkpoint(filepath3) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/initialize.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/initialize.md new file mode 100644 index 0000000000000000000000000000000000000000..b14fa3900e7bba2972e399a83020de9acece08de --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/initialize.md @@ -0,0 +1,325 @@ +# Initialization + +Usually, we'll customize our module based on [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module), which is implemented by Native PyTorch. Also, [torch.nn.init](https://pytorch.org/docs/stable/nn.init.html) could help us initialize the parameters of the model easily. To simplify the process of model construction and initialization, MMEngine designed the [BaseModule](mmengine.model.BaseModule) to help us define and initialize the model from config easily. + +## Initialize the model from config + +The core function of `BaseModule` is that it could help us to initialize the model from config. Subclasses inherited from `BaseModule` could define the `init_cfg` in the `__init__` function, and we can choose the method of initialization by configuring `init_cfg`. + +Currently, we support the following initialization methods: + +| Initializer | Registered name | Function | +| :-------------------------------------------------------------------------------------------------------- | :-------------: | :--------------------------------------------------------------------------------------------------------------------------------------- | +| [ConstantInit](../api/generated/mmengine.model.ConstantInit.html#mmengine.model.ConstantInit) | Constant | Initialize the weight and bias with a constant, commonly used for Convolution | +| [XavierInit](../api/generated/mmengine.model.XavierInit.html#mmengine.model.XavierInit) | Xavier | Initialize the weight by `Xavier` initialization, and initialize the bias with a constant | +| [NormalInit](../api/generated/mmengine.model.NormalInit.html#mmengine.model.NormalInit) | Normal | Initialize the weight by normal distribution, and initialize the bias with a constant | +| [TruncNormalInit](../api/generated/mmengine.model.TruncNormalInit.html#mmengine.model.TruncNormalInit) | TruncNormal | Initialize the weight by truncated normal distribution, and initialize the bias with a constant,commonly used for Transformer | +| [UniformInit](../api/generated/mmengine.model.UniformInit.html#mmengine.model.UniformInit) | Uniform | Initialize the weight by uniform distribution, and initialize the bias with a constant,commonly used for convolution | +| [KaimingInit](../api/generated/mmengine.model.KaimingInit.html#mmengine.model.KaimingInit) | Kaiming | Initialize the weight by `Kaiming` initialization, and initialize the bias with a constant. Commonly used for convolution | +| [Caffe2XavierInit](../api/generated/mmengine.model.Caffe2XavierInit.html#mmengine.model.Caffe2XavierInit) | Caffe2Xavier | `Xavier` initialization in Caffe2, and `Kaiming` initialization in PyTorh with `fan_in` and `normal` mode. Commonly used for convolution | +| [PretrainedInit](../api/generated/mmengine.model.PretrainedInit.html#mmengine.model.PretrainedInit) | Pretrained | Initialize the model with the pretrained model | + +### Initialize the model with pretrained model + +Defining the `ToyNet` as below: + +```python +import torch +import torch.nn as nn + +from mmengine.model import BaseModule + + +class ToyNet(BaseModule): + + def __init__(self, init_cfg=None): + super().__init__(init_cfg) + self.conv1 = nn.Linear(1, 1) + + +# Save the checkpoint. +toy_net = ToyNet() +torch.save(toy_net.state_dict(), './pretrained.pth') +pretrained = './pretrained.pth' + +toy_net = ToyNet(init_cfg=dict(type='Pretrained', checkpoint=pretrained)) +``` + +and then we can configure the `init_cfg` to make it load the pretrained model by calling `initi_weights()` after its construction. + +```python +# Initialize the model with the saved checkpoint. +toy_net.init_weights() +``` + +``` +08/19 16:50:24 - mmengine - INFO - load model from: ./pretrained.pth +08/19 16:50:24 - mmengine - INFO - local loads checkpoint from path: ./pretrained.pth +``` + +If `init_cfg` is a `dict`, `type` means a kind of initializer registered in `WEIGHT_INITIALIZERS`. The `Pretrained` means `PretrainedInit`, which could help us to load the target checkpoint. +All initializers have the same mapping relationship like `Pretrained` -> `PretrainedInit`, which strips the suffix `Init` of the class name. The `checkpoint` argument of `PretrainedInit` means the path of the checkpoint. It could be a local path or a URL. + +### Commonly used initialization methods + +Similarly, we could use the `Kaiming` initialization just like `Pretrained` initializer. For example, we could make `init_cfg=dict(type='Kaiming', layer='Conv2d')` to initialize all `Conv2d` module with `Kaiming` initialization. + +Sometimes we need to initialize the model with different initialization methods for different modules. For example, we could initialize the `Conv2d` module with `Kaiming` initialization and initialize the `Linear` module with `Xavier` initialization. We could make `init_cfg=dict(type='Kaiming', layer='Conv2d')`: + +```python +import torch.nn as nn + +from mmengine.model import BaseModule + + +class ToyNet(BaseModule): + + def __init__(self, init_cfg=None): + super().__init__(init_cfg) + self.linear = nn.Linear(1, 1) + self.conv = nn.Conv2d(1, 1, 1) + + +# Apply `Kaiming` initialization to `Conv2d` module and `Xavier` initialization to `Linear` module. +toy_net = ToyNet( + init_cfg=[ + dict(type='Kaiming', layer='Conv2d'), + dict(type='Xavier', layer='Linear') + ], ) +toy_net.init_weights() +``` + +``` +08/19 16:50:24 - mmengine - INFO - +linear.weight - torch.Size([1, 1]): +XavierInit: gain=1, distribution=normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +linear.bias - torch.Size([1]): +XavierInit: gain=1, distribution=normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv.weight - torch.Size([1, 1, 1, 1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 +``` + +`layer` could also be a list, each element of which means a type of applied module. + +```python +# Apply Kaiming initialization to `Conv2d` and `Linear` module. +toy_net = ToyNet(init_cfg=[dict(type='Kaiming', layer=['Conv2d', 'Linear'])], ) +toy_net.init_weights() +``` + +``` +08/19 16:50:24 - mmengine - INFO - +linear.weight - torch.Size([1, 1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +linear.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv.weight - torch.Size([1, 1, 1, 1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 +``` + +### More fine-grained initialization + +Sometimes we need to initialize the same type of module with different types of initialization. For example, we've defined `conv1` and `conv2` submodules, and we want to initialize the `conv1` with `Kaiming` initialization and `conv2` with `Xavier` initialization. We could configure the init_cfg with `override`: + +```python +import torch.nn as nn + +from mmengine.model import BaseModule + + +class ToyNet(BaseModule): + + def __init__(self, init_cfg=None): + super().__init__(init_cfg) + self.conv1 = nn.Conv2d(1, 1, 1) + self.conv2 = nn.Conv2d(1, 1, 1) + + +# Apllly `Kaiming` initialization to `conv1` and `Xavier` initialization to `conv2`. +toy_net = ToyNet( + init_cfg=[ + dict( + type='Kaiming', + layer=['Conv2d'], + override=dict(name='conv2', type='Xavier')), + ], ) +toy_net.init_weights() +``` + +``` +08/19 16:50:24 - mmengine - INFO - +conv1.weight - torch.Size([1, 1, 1, 1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv1.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv2.weight - torch.Size([1, 1, 1, 1]): +XavierInit: gain=1, distribution=normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv2.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 +``` + +`override` could be understood as an nested `init_cfg`, which could also be a `list` or `dict`, and we should also set "`type`" for it. The difference is that we must set `name` in `override` to specify the applied scope for submodule. As the example above, we set `name='conv2'` to specify that the `Xavier` initialization is applied to all submodules of `toy_net.conv2`. + +### Customize the initialization method + +Although the `init_cfg` could control the initialization method for different modules, we would have to register a new initialization method to `WEIGHT_INITIALIZERS` if we want to customize initialization process. It is not convenient right? Actually, we could also override the `init_weights` method to customize the initialization process. + +Assuming we've defined the following modules: + +- `ToyConv` inherit from `nn.Module`, implements `init_weights`which initialize `custom_weight`(`parameter` of `ToyConv`) with 1 and initialize `custom_bias` with 0 + +- `ToyNet` defines a `ToyConv` submodule. + +`ToyNet.init_weights` will call `init_weights` of all submodules sequentially. + +```python +import torch +import torch.nn as nn + +from mmengine.model import BaseModule + + +class ToyConv(nn.Module): + + def __init__(self): + super().__init__() + self.custom_weight = nn.Parameter(torch.empty(1, 1, 1, 1)) + self.custom_bias = nn.Parameter(torch.empty(1)) + + def init_weights(self): + with torch.no_grad(): + self.custom_weight = self.custom_weight.fill_(1) + self.custom_bias = self.custom_bias.fill_(0) + + +class ToyNet(BaseModule): + + def __init__(self, init_cfg=None): + super().__init__(init_cfg) + self.conv1 = nn.Conv2d(1, 1, 1) + self.conv2 = nn.Conv2d(1, 1, 1) + self.custom_conv = ToyConv() + + +toy_net = ToyNet( + init_cfg=[ + dict( + type='Kaiming', + layer=['Conv2d'], + override=dict(name='conv2', type='Xavier')) + ]) + +toy_net.init_weights() +``` + +``` +08/19 16:50:24 - mmengine - INFO - +conv1.weight - torch.Size([1, 1, 1, 1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv1.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv2.weight - torch.Size([1, 1, 1, 1]): +XavierInit: gain=1, distribution=normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +conv2.bias - torch.Size([1]): +KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0 + +08/19 16:50:24 - mmengine - INFO - +custom_conv.custom_weight - torch.Size([1, 1, 1, 1]): +Initialized by user-defined `init_weights` in ToyConv + +08/19 16:50:24 - mmengine - INFO - +custom_conv.custom_bias - torch.Size([1]): +Initialized by user-defined `init_weights` in ToyConv +``` + +### Conclusion + +**1. Configure `init_cfg` to initialize model** + +- Commonly used for the initialization of `Conv2d`, `Linear` and other underlying module. All initialization methods should be managed by `WEIGHT_INITIALIZERS` +- Dynamic initialization controlled by `init_cfg` + +**2. Customize `init_weights`** + +- Compared to configuring the `init_cfg`, implementing the `init_weights` is simpler and does not require registration. However, it is not as flexible as `init_cfg`, and it is not possible to initialize the module dynamically. + +```{note} +- The priorify of init_weights is higher than `init_cfg` +- Runner will call `init_weights` in Runner.train() +``` + +### Ininitailize module with function + +As mentioned in prior [section](#customize-the-initialization-method), we could customize our initialization in `init_weights`. To make it more convenient to initialize modules, MMEngine provides a series of **module initialization functions** to initialize the whole module based on `torch.nn.init`. For example, we want to initialize the weights of the convolutional layer with normal distribution and initialize the bias of the convolutional layer with a constant. The implementation of `torch.nn.init` is as follows: + +```python +from torch.nn.init import normal_, constant_ +import torch.nn as nn + +model = nn.Conv2d(1, 1, 1) +normal_(model.weight, mean=0, std=0.01) +constant_(model.bias, val=0) +``` + +``` +Parameter containing: +tensor([0.], requires_grad=True) +``` + +The above process is actually a standard process for initializing a convolutional module with normal distribution, so MMEngine simplifies this by implementing a series of common **module** initialization functions. Compared with `torch.nn.init`, the module initialization functions could accept the convolution module directly: + +```python +from mmengine.model import normal_init + +normal_init(model, mean=0, std=0.01, bias=0) +``` + +Similarly, we could also use [Kaiming](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf) initialization and [Xavier](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf) initialization: + +```python +from mmengine.model import kaiming_init, xavier_init + +kaiming_init(model) +xavier_init(model) +``` + +Currently, MMEngine provide the following initialization function: + +| initialization function | function | +| :----------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- | +| [constant_init](../api/generated/mmengine.model.constant_init.html#mmengine.model.constant_init) | Initialize the weight and bias with a constant, commonly used for Convolution | +| [xavier_init](../api/generated/mmengine.model.xavier_init.html#mmengine.model.xavier_init) | Initialize the weight by `Xavier` initialization, and initialize the bias with a constant | +| [normal_init](../api/generated/mmengine.model.normal_init.html#mmengine.model.normal_init) | Initialize the weight by normal distribution, and initialize the bias with a constant | +| [trunc_normal_init](../api/generated/mmengine.model.trunc_normal_init.html#mmengine.model.trunc_normal_init) | Initialize the weight by truncated normal distribution, and initialize the bias with a constant,commonly used for Transformer | +| [uniform_init](../api/generated/mmengine.model.uniform_init.html#mmengine.model.uniform_init) | Initialize the weight by uniform distribution, and initialize the bias with a constant,commonly used for convolution | +| [kaiming_init](../api/generated/mmengine.model.kaiming_init.html#mmengine.model.kaiming_init) | Initialize the weight by `Kaiming` initialization, and initialize the bias with a constant. Commonly used for convolution | +| [caffe2_xavier_init](../api/generated/mmengine.model.caffe2_xavier_init.html#mmengine.model.caffe2_xavier_init) | `Xavier` initialization in Caffe2, and `Kaiming` initialization in PyTorh with `fan_in` and `normal` mode. Commonly used for convolution | +| [bias_init_with_prob](../api/generated/mmengine.model.bias_init_with_prob.html#mmengine.model.bias_init_with_prob) | Initialize the bias with the probability | diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/logging.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..c11c71f012afeb6acc4b932d050a384d8b149d6d --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/logging.md @@ -0,0 +1,312 @@ +# Logging + +[Runner](../tutorials/runner.md) will produce a lot of logs during the running process, such as loss, iteration time, learning rate, etc. MMEngine implements a flexible logging system that allows us to choose different types of log statistical methods when configuring the runner. It could help us set/get the recorded log at any location in the code. + +## Flexible Logging System + +Logging system is configured by passing a [LogProcessor](mmengine.logging.LogProcessor) to the runner. If no log processor is passed, the runner will use the default log processor, which is equivalent to: + +```python +log_processor = dict(window_size=10, by_epoch=True, custom_cfg=None, num_digits=4) +``` + +The format of the output log is as follows: + +```python +import torch +import torch.nn as nn +from torch.utils.data import DataLoader + +from mmengine.runner import Runner +from mmengine.model import BaseModel + +train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50 +train_dataloader = DataLoader(train_dataset, batch_size=2) + + +class ToyModel(BaseModel): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + return dict(loss1=loss1, loss2=loss2) + +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)) +) +runner.train() +``` + +``` +08/21 02:58:41 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0019 data_time: 0.0004 loss1: 0.8381 loss2: 0.9007 loss: 1.7388 +08/21 02:58:41 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0029 data_time: 0.0010 loss1: 0.1978 loss2: 0.4312 loss: 0.6290 +``` + +LogProcessor will output the log in the following format: + +- The prefix of the log: + - epoch mode(`by_epoch=True`): `Epoch(train) [{current_epoch}/{current_iteration}]/{dataloader_length}` + - iteration mode(`by_epoch=False`): `Iter(train) [{current_iteration}/{max_iteration}]`) +- Learning rate (`lr`): The learning rate of the last iteration. +- Time: + - `time`: The averaged time for infernce of the last `window_size` iterations. + - `data_time`: The averaged time for loading data of the last `window_size` iterations. + - `eta`: The estimated time of arrival to finish the training. +- Loss: The averaged loss output by model of the last `window_size` iterations. + +```{note} +`window_size=10` by default. + +The significant digits(`num_digits`) of the log is 4 by default. + +Output the value of all custom logsthe at last iteration by default. +``` + +```{warnning} +log_processor outputs the epoch based log by default(`by_epoch=True`). To get an expected log matched with the `train_cfg`, we should set the same value for `by_epoch` in `train_cfg` and `log_processor`. +``` + +Based on the rules above, the code snippet will count the average value of the `loss1` and `loss2` every 10 iterations. + +If we want to count the global average value of `loss1`, we can set `custom_cfg` like this: + +```python +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)), + log_processor=dict( + custom_cfg=[ + dict(data_src='loss1', # original loss name:loss1 + method_name='mean', # statistical method:mean + window_size='global')]) # window_size:global +) +runner.train() +``` + +``` +08/21 02:58:49 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0026 data_time: 0.0007 loss1: 0.7381 loss2: 0.8446 loss: 1.5827 +08/21 02:58:49 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0030 data_time: 0.0012 loss1: 0.4521 loss2: 0.3939 loss: 0.5600 +``` + +`data_src` means the original loss name, `method_name` means the statistic method, `window_size` means the window size of the statistic method. Since we want to count the global average value of `loss1`, we set `window_size` to `global`. + +Currently, MMEngine supports the following statistical methods: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
statistic methodargumentsfunction
meanwindow_sizestatistic the average log of the last `window_size`
minwindow_sizestatistic the minimum log of the last `window_size`
maxwindow_sizestatistic the maximum log of the last `window_size`
current/statistic the latest
+ +`window_size` mentioned above could be: + +- int number: The window size of the statistic method. +- `global`: Equivalent to `window_size=cur_iteration`. +- `epoch`: Equivalent to `window_size=len(dataloader)`. + +If we want to statistic the average value of `loss1` of the last 10 iterations, and also want to statistic the global average value of `loss1`. We need to set `log_name` additionally: + +```python +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)), + log_processor=dict( + custom_cfg=[ + # log_name means the second name of loss1 + dict(data_src='loss1', log_name='loss1_global', method_name='mean', window_size='global')]) +) +runner.train() +``` + +``` +08/21 18:39:32 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0016 data_time: 0.0004 loss1: 0.1512 loss2: 0.3751 loss: 0.5264 loss1_global: 0.1512 +08/21 18:39:32 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0051 data_time: 0.0036 loss1: 0.0113 loss2: 0.0856 loss: 0.0970 loss1_global: 0.0813 +``` + +Similarly, we can also statistic the global/local maximum value of `loss` at the same time. + +```python +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)), + log_processor=dict(custom_cfg=[ + # statistic loss1 with the local maximum value + dict(data_src='loss1', + log_name='loss1_local_max', + window_size=10, + method_name='max'), + # statistic loss1 with the global maximum value + dict( + data_src='loss1', + log_name='loss1_global_max', + method_name='max', + window_size='global') + ])) +runner.train() +``` + +``` +08/21 03:17:26 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0021 data_time: 0.0006 loss1: 1.8495 loss2: 1.3427 loss: 3.1922 loss1_local_max: 2.8872 loss1_global_max: 2.8872 +08/21 03:17:26 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0024 data_time: 0.0010 loss1: 0.5464 loss2: 0.7251 loss: 1.2715 loss1_local_max: 2.8872 loss1_global_max: 2.8872 +``` + +More examples can be found in [log_processor](mmengine.logging.LogProcessor). + +## Customize log + +The logging system could not only log the `loss`, `lr`, .etc but also collect and output the custom log. For example, if we want to statistic the intermediate `loss`: + +```python +from mmengine.logging import MessageHub + + +class ToyModel(BaseModel): + + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + feat = self.linear(img) + loss_tmp = (feat - label).abs() + loss = loss_tmp.pow(2) + + message_hub = MessageHub.get_current_instance() + # update the intermediate `loss_tmp` in the message hub + message_hub.update_scalar('train/loss_tmp', loss_tmp.sum()) + return dict(loss=loss) + + +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)), + log_processor=dict( + custom_cfg=[ + # statistic the loss_tmp with the averaged value + dict( + data_src='loss_tmp', + window_size=10, + method_name='mean') + ] + ) +) +runner.train() +``` + +``` +08/21 03:40:31 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0026 data_time: 0.0008 loss_tmp: 0.0097 loss: 0.0000 +08/21 03:40:31 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0028 data_time: 0.0013 loss_tmp: 0.0065 loss: 0.0000 +``` + +The custom log will be recorded by updating the [messagehub](mmengine.logging.MessageHub): + +1. Calling `MessageHub.get_current_instance()` to get the message of runner +2. Calling `MessageHub.update_scalar` to update the custom log. The first argument means the log name with the mode prefix(`train/val/test`). The output log will only retain the log name without the mode prefix. +3. Configure statistic method of `loss_tmp` in `log_processor`. If it is not configured, only the latest value of `loss_tmp` will be logged. + +## Export the debug log + +Set `log_level=DEBUG` for runner, and the debug log will be exported to the `work_dir`: + +```python +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + log_level='DEBUG', + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01))) +runner.train() +``` + +``` +08/21 18:16:22 - mmengine - DEBUG - Get class `LocalVisBackend` from "vis_backend" registry in "mmengine" +08/21 18:16:22 - mmengine - DEBUG - An `LocalVisBackend` instance is built from registry, its implementation can be found in mmengine.visualization.vis_backend +08/21 18:16:22 - mmengine - DEBUG - Get class `RuntimeInfoHook` from "hook" registry in "mmengine" +08/21 18:16:22 - mmengine - DEBUG - An `RuntimeInfoHook` instance is built from registry, its implementation can be found in mmengine.hooks.runtime_info_hook +08/21 18:16:22 - mmengine - DEBUG - Get class `IterTimerHook` from "hook" registry in "mmengine" +... +``` + +Besides, logs of different ranks will be saved in `debug` mode if you are training your model with the shared storage. The hierarchy of the log is as follows: + +```text +./tmp +├── tmp.log +├── tmp_rank1.log +├── tmp_rank2.log +├── tmp_rank3.log +├── tmp_rank4.log +├── tmp_rank5.log +├── tmp_rank6.log +└── tmp_rank7.log +... +└── tmp_rank63.log +``` + +The log of Multiple machine with independent storage: + +```text +# device: 0: +work_dir/ +└── exp_name_logs + ├── exp_name.log + ├── exp_name_rank1.log + ├── exp_name_rank2.log + ├── exp_name_rank3.log + ... + └── exp_name_rank7.log + +# device: 7: +work_dir/ +└── exp_name_logs + ├── exp_name_rank56.log + ├── exp_name_rank57.log + ├── exp_name_rank58.log + ... + └── exp_name_rank63.log +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/manager_mixin.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/manager_mixin.md new file mode 100644 index 0000000000000000000000000000000000000000..15f3ef84bde918891154e2813433a7a239b373bb --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/manager_mixin.md @@ -0,0 +1,74 @@ +# Global manager (ManagerMixin) + +During the training process, it is inevitable that we need to access some variables globally. Here are some examples: + +- Accessing the [logger](mmengine.logging.MMLogger) in model to print some initialization information +- Accessing the [Visualizer](mmengine.config.Config) anywhere to visualize the predictions and feature maps. +- Accessing the scope in [Registry](mmengine.registry.Registry) to get the current scope. + +In order to unify the mechanism to get the global variable built from different classes, MMEngine designs the [ManagerMixin](mmengine.utils.ManagerMixin). + +## Interface introduction + +- get_instance(name='', \*\*kwargs): Create or get the instance by name. +- get_current_instance(): Get the currently built instance. +- instance_name: Get the name of the instance. + +## How to use + +1. Define a class inherited from `ManagerMixin` + +```python +from mmengine.utils import ManagerMixin + + +class GlobalClass(ManagerMixin): + def __init__(self, name, value): + super().__init__(name) + self.value = value +``` + +```{note} +Subclasses of `ManagerMixin` must accept `name` argument in `__init__`. The `name` argument is used to identify the instance, and you can get the instance by `get_instance(name)`. +``` + +2. Instantiate the instance anywhere. let's take the hook as an example: + +```python +from mmengine import Hook + +class CustomHook(Hook): + def before_run(self, runner): + GlobalClass.get_instance('mmengine', value=50) + GlobalClass.get_instance(runner.experiment_name, value=100) +``` + +`GlobalClass.get_instance({name})` will first check whether the instance with the name `{name}` has been built. If not, it will build a new instance with the name `{name}`, otherwise it will return the existing instance. As the above example shows, when we call `GlobalClass.get_instance('mmengine')` at the first time, it will build a new instance with the name `mmengine`. Then we call `GlobalClass.get_instance(runner.experiment_name)`, it will also build a new instance with a different name. + +Here we build two instances for the convenience of the subsequent introduction of `get_current_instance`. + +3. Accessing the instance anywhere + +```python +import torch.nn as nn + + +class CustomModule(nn.Module): + def forward(self, x): + value = GlobalClass.get_current_instance().value + # Since the name of the latest built instance is + # `runner.experiment_name`, value will be 100. + + value = GlobalClass.get_instance('mmengine').value + # The value of instance with the name mmengine is 50. + + value = GlobalClass.get_instance('mmengine', 1000).value + # `mmengine` instance has been built, an error will be raised + # if `get_instance` accepts other parameters. +``` + +We can get the instance with the specified name by `get_instance(name)`, or get the currently built instance by `get_current_instance` anywhere. + +```{warning} +If the instance with the specified name has already been built, `get_instance` will raise an error if it accepts its construct parameters. +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/registry.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/registry.md new file mode 100644 index 0000000000000000000000000000000000000000..eb875961de9183d6ea17bf08d64547253c642d71 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/registry.md @@ -0,0 +1,302 @@ +# Registry + +OpenMMLab supports a rich collection of algorithms and datasets, therefore, many modules with similar functionality are implemented. For example, the implementations of `ResNet` and `SE-ResNet` are based on the classes `ResNet` and `SEResNet`, respectively, which have similar functions and interfaces and belong to the model components of the algorithm library. To manage these functionally similar modules, MMEngine implements the [registry](mmengine.registry.registry). Most of the algorithm libraries in OpenMMLab use `registry` to manage their modules, including [MMDetection](https://github.com/open-mmlab/mmdetection), [MMDetection3D](https://github.com/open-mmlab/mmdetection3d), [MMClassification](https://github.com/open-mmlab/mmclassification) and [MMEditing](https://github.com/open-mmlab/mmediting), etc. + +## What is a registry + +The [registry](mmengine.registry.Registry) in MMEngine can be considered as a union of a mapping table and a build function of modules. The mapping table maintains a mapping from strings to **classes or functions**, allowing the user to find the corresponding class or function with its name/notation. For example, the mapping from the string `"ResNet"` to the `ResNet` class. The module build function defines how to find the corresponding class or function based on a string and how to instantiate the class or call the function. For example, finding `nn.BatchNorm2d` and instantiating the `BatchNorm2d` module by the string `"bn"`, or finding the `build_batchnorm2d` function by the string `"build_batchnorm2d"` and then returning the result. The registries in MMEngine use the [build_from_cfg](mmengine.registry.build_from_cfg) function by default to find and instantiate the class or function corresponding to the string. + +The classes or functions managed by a registry usually have similar interfaces and functionality, so the registry can be treated as an abstraction of those classes or functions. For example, the registry `MODELS` can be treated as an abstraction of all models, which manages classes such as `ResNet`, `SEResNet` and `RegNetX` and constructors such as `build_ResNet`, `build_SEResNet` and `build_RegNetX`. + +## Getting started + +There are three steps required to use the registry to manage modules in the codebase. + +1. Create a registry. +2. Create a build method for instantiating the class (optional because in most cases you can just use the default method). +3. Add the module to the registry + +Suppose we want to implement a series of activation modules and want to be able to switch to different modules by just modifying the configuration without modifying the code. + +Let's create a regitry first. + +```python +from mmengine import Registry +# scope represents the domain of the registry. If not set, the default value is the package name. +# e.g. in mmdetection, the scope is mmdet +ACTIVATION = Registry('activation', scope='mmengine') +``` + +Then we can implement different activation modules, such as `Sigmoid`, `ReLU`, and `Softmax`. + +```python +import torch.nn as nn + +# use the register_module +@ACTIVATION.register_module() +class Sigmoid(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x): + print('call Sigmoid.forward') + return x + +@ACTIVATION.register_module() +class ReLU(nn.Module): + def __init__(self, inplace=False): + super().__init__() + + def forward(self, x): + print('call ReLU.forward') + return x + +@ACTIVATION.register_module() +class Softmax(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x): + print('call Softmax.forward') + return x +``` + +The key of using the registry module is to register the implemented modules into the `ACTIVATION` registry. With the `@ACTIVATION.register_module()` decorator added before the implemented module, the mapping between strings and classes or functions can be built and maintained by `ACTIVATION`. We can achieve the same functionality with `ACTIVATION.register_module(module=ReLU)` as well. + +By registering, we can create a mapping between strings and classes or functions via `ACTIVATION`. + +```python +print(ACTIVATION.module_dict) +# { +# 'Sigmoid': __main__.Sigmoid, +# 'ReLU': __main__.ReLU, +# 'Softmax': __main__.Softmax +# } +``` + +```{note} +The registry mechanism will only be triggered when the corresponded module file is imported, so we need to import the file somewhere or dynamically import the module using the ``custom_imports`` field to trigger the mechanism. Please refer to [Importing custom Python modules](config.md#import-the-custom-module) for more details. +``` + +Once the implemented module is successfully registered, we can use the activation module in the configuration file. + +```python +import torch + +input = torch.randn(2) + +act_cfg = dict(type='Sigmoid') +activation = ACTIVATION.build(act_cfg) +output = activation(input) +# call Sigmoid.forward +print(output) +``` + +We can switch to `ReLU` by just changing this configuration. + +```python +act_cfg = dict(type='ReLU', inplace=True) +activation = ACTIVATION.build(act_cfg) +output = activation(input) +# call ReLU.forward +print(output) +``` + +If we want to check the type of input parameters (or any other operations) before creating an instance, we can implement a build method and pass it to the registry to implement a custom build process. + +Create a `build_activation` function. + +```python +def build_activation(cfg, registry, *args, **kwargs): + cfg_ = cfg.copy() + act_type = cfg_.pop('type') + print(f'build activation: {act_type}') + act_cls = registry.get(act_type) + act = act_cls(*args, **kwargs, **cfg_) + return act +``` + +Pass the `buid_activation` to `build_func`. + +```python +ACTIVATION = Registry('activation', build_func=build_activation, scope='mmengine') + +@ACTIVATION.register_module() +class Tanh(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x): + print('call Tanh.forward') + return x + +act_cfg = dict(type='Tanh') +activation = ACTIVATION.build(act_cfg) +output = activation(input) +# build activation: Tanh +# call Tanh.forward +print(output) +``` + +```{note} +In the above example, we demonstrate how to customize the method of building an instance of a class using the `build_func`. +This is similar to the default `build_from_cfg` method. In most cases, using the default method will be fine. +``` + +MMEngine's registry can register classes as well as functions. + +```python +FUNCTION = Registry('function', scope='mmengine') + +@FUNCTION.register_module() +def print_args(**kwargs): + print(kwargs) + +func_cfg = dict(type='print_args', a=1, b=2) +func_res = FUNCTION.build(func_cfg) +``` + +## Advanced usage + +The registry in MMEngine supports hierarchical registration, which enables cross-project calls, meaning that modules from one project can be used in another project. Though there are other ways to implement this, the registry provides a much easier solution. + +To easily make cross-library calls, MMEngine provides twenty root registries, including: + +- RUNNERS: the registry for Runner. +- RUNNER_CONSTRUCTORS: the constructors for Runner. +- LOOPS: manages training, validation and testing processes, such as `EpochBasedTrainLoop`. +- HOOKS: the hooks, such as `CheckpointHook`, and `ParamSchedulerHook`. +- DATASETS: the datasets. +- DATA_SAMPLERS: `Sampler` of `DataLoader`, used to sample the data. +- TRANSFORMS: various data preprocessing methods, such as `Resize`, and `Reshape`. +- MODELS: various modules of the model. +- MODEL_WRAPPERS: model wrappers for parallelizing distributed data, such as `MMDistributedDataParallel`. +- WEIGHT_INITIALIZERS: the tools for weight initialization. +- OPTIMIZERS: registers all `Optimizers` and custom `Optimizers` in PyTorch. +- OPTIM_WRAPPER: the wrapper for Optimizer-related operations such as `OptimWrapper`, and `AmpOptimWrapper`. +- OPTIM_WRAPPER_CONSTRUCTORS: the constructors for optimizer wrappers. +- PARAM_SCHEDULERS: various parameter schedulers, such as `MultiStepLR`. +- METRICS: the evaluation metrics for computing model accuracy, such as `Accuracy`. +- EVALUATOR: one or more evaluation metrics used to calculate the model accuracy. +- TASK_UTILS: the task-intensive components, such as `AnchorGenerator`, and `BboxCoder`. +- VISUALIZERS: the management drawing module that draws prediction boxes on images, such as `DetVisualizer`. +- VISBACKENDS: the backend for storing training logs, such as `LocalVisBackend`, and `TensorboardVisBackend`. +- LOG_PROCESSORS: controls the log statistics window and statistics methods, by default we use `LogProcessor`. You may customize `LogProcessor` if you have special needs. + +### Use the module of the parent node + +Let's define a `RReLU` module in `MMEngine` and register it to the `MODELS` root registry. + +```python +import torch.nn as nn +from mmengine import Registry, MODELS + +@MODELS.register_module() +class RReLU(nn.Module): + def __init__(self, lower=0.125, upper=0.333, inplace=False): + super().__init__() + + def forward(self, x): + print('call RReLU.forward') + return x +``` + +Now suppose there is a project called `MMAlpha`, which also defines a `MODELS` and sets its parent node to the `MODELS` of `MMEngine`, which creates a hierarchical structure. + +```python +from mmengine import Registry, MODELS as MMENGINE_MODELS + +MODELS = Registry('model', parent=MMENGINE_MODELS, scope='mmalpha') +``` + +The following figure shows the hierarchy of `MMEngine` and `MMAlpha`. + +
+ +
+ +The [count_registered_modules](mmengine.registry.count_registered_modules) function can be used to print the modules that have been registered to MMEngine and their hierarchy. + +```python +from mmengine.registry import count_registered_modules + +count_registered_modules() +``` + +We define a customized `LogSoftmax` module in `MMAlpha` and register it to the `MODELS` in `MMAlpha`. + +```python +@MODELS.register_module() +class LogSoftmax(nn.Module): + def __init__(self, dim=None): + super().__init__() + + def forward(self, x): + print('call LogSoftmax.forward') + return x +``` + +Here we use the `LogSoftmax` in the configuration of `MMAlpha`. + +```python +model = MODELS.build(cfg=dict(type='LogSoftmax')) +``` + +We can also use the modules of the parent node `MMEngine` here in the `MMAlpha`. + +```python +model = MODELS.build(cfg=dict(type='RReLU', lower=0.2)) +# scope is optional +model = MODELS.build(cfg=dict(type='mmengine.RReLU')) +``` + +If no prefix is added, the `build` method will first find out if the module exists in the current node and return it if there is one. Otherwise, it will continue to look up the parent nodes or even the ancestor node until it finds the module. If the same module exists in both the current node and the parent nodes, we need to specify the `scope` prefix to indicate that we want to use the module of the parent nodes. + +```python +import torch + +input = torch.randn(2) +output = model(input) +# call RReLU.forward +print(output) +``` + +### Use the module of a sibling node + +In addition to using the module of the parent nodes, users can also call the module of a sibling node. + +Suppose there is another project called `MMBeta`, which, like `MMAlpha`, defines `MODELS` and set its parent node to `MMEngine`. + +```python +from mmengine import Registry, MODELS as MMENGINE_MODELS + +MODELS = Registry('model', parent=MMENGINE_MODELS, scope='mmbeta') +``` + +The following figure shows the registry structure of `MMAlpha` and `MMBeta`. + +
+ +
+ +Now we call the modules of `MMAlpha` in `MMBeta`. + +```python +model = MODELS.build(cfg=dict(type='mmalpha.LogSoftmax')) +output = model(input) +# call LogSoftmax.forward +print(output) +``` + +Calling a module of a sibling node requires the `scope` prefix to be specified in `type`, so the above configuration requires the prefix `mmalpha`. + +However, if you need to call several modules of a sibling node, each with a prefix, this requires a lot of modification. Therefore, `MMEngine` introduces the [DefaultScope](mmengine.registry.DefaultScope), with which `Registry` can easily support temporary switching of the current node to the specified node. + +If you need to switch the current node to the specified node temporarily, just set `_scope_` to the scope of the specified node in `cfg`. + +```python +model = MODELS.build(cfg=dict(type='LogSoftmax', _scope_='mmalpha')) +output = model(input) +# call LogSoftmax.forward +print(output) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/visualization.md b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..270f74212583b6f4c68643819f9c7384e0240fb6 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/advanced_tutorials/visualization.md @@ -0,0 +1,390 @@ +# Visualization + +Visualization provides an intuitive explanation of the training and testing process of the deep learning model. + +MMEngine provides `Visualizer` to visualize and store the state and intermediate results of the model training and testing process, with the following features: + +- It supports basic drawing interface and feature map visualization +- It enables recording training states (such as loss and lr), performance evaluation metrics, and visualization results to a specified or multiple backends, including local device, TensorBoard, and WandB. +- It can be used in any location in the code base. + +## Basic Drawing APIs + +`Visualizer` provides drawing APIs for common objects such as **detection bboxes, points, text, lines, circles, polygons, and binary masks**. + +These APIs have the following features: + +- Can be called multiple times to achieve overlay drawing requirements. +- All support multiple input types such as Tensor, Numpy array, etc. + +Typical usages are as follows. + +1. Draw detection bboxes, masks, text, etc. + +```python +import torch +import mmcv +from mmengine.visualization import Visualizer + +image = mmcv.imread('docs/en/_static/image/cat_dog.png', channel_order='rgb') +visualizer = Visualizer(image=image) +# single bbox formatted as [xyxy] +visualizer.draw_bboxes(torch.tensor([72, 13, 179, 147])) +# draw multiple bboxes +visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]])) +visualizer.show() +``` + +
+ +
+ +```python +visualizer.set_image(image=image) +visualizer.draw_texts("cat and dog", torch.tensor([10, 20])) +visualizer.show() +``` + +
+ +
+ +You can also customize things like color and width using the parameters in each API. + +```python +visualizer.set_image(image=image) +visualizer.draw_bboxes(torch.tensor([72, 13, 179, 147]), edge_colors='r', line_widths=3) +visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220]]),line_styles='--') +visualizer.show() +``` + +
+ +
+ +2. Overlay display + +These APIs can be called multiple times to get an overlay result. + +```python +visualizer.set_image(image=image) +visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]])) +visualizer.draw_texts("cat and dog", + torch.tensor([10, 20])).draw_circles(torch.tensor([40, 50]), torch.tensor([20])) +visualizer.show() +``` + +
+ +
+ +## Feature Map Visualization + +Feature map visualization has many functions. Currently, we only support single feature map visualization. + +```python +@staticmethod +def draw_featmap(featmap: torch.Tensor, # input format must be CHW + overlaid_image: Optional[np.ndarray] = None, # if image data is input at the same time, the feature map will be overlaid on the image + channel_reduction: Optional[str] = 'squeeze_mean', # strategy to reduce multiple channels into a single channel + topk: int = 10, # topk feature maps to show + arrangement: Tuple[int, int] = (5, 2), # the layout when multiple channels are expanded into multiple images + resize_shape:Optional[tuple] = None, # scale the feature map + alpha: float = 0.5) -> np.ndarray: # overlay ratio between input image and generated feature map +``` + +The main features can be concluded as follows: + +- As the input Tensor usually includes multiple channels, `channel_reduction` can reduce them into a single channel and overlay the result to the image. + + - `squeeze_mean` reduces the input channel C into a single channel using the mean function, so the output dimension becomes (1, H, W) + - `select_max` select the channel with the maximum activation, where 'activation' refers to the sum across spatial dimensions of a channel. + - `None` indicates that no reduction is needed, which allows the user to select the top k feature maps with the highest activation degree through the `topk` parameter. + +- `topk` is only valid when the `channel_reduction` is `None`. It selects the top k channels according to the activation degree and then displays them overlaid with the image. The display layout can be specified using the `--arrangement` parameter. + + - If `topk` is not -1, `topk` channels with the largest activation will be selected for display. + - If `topk` is -1, channel number C must be either 1 or 3 to indicate if the input is a picture. Otherwise, an error will be raised to prompt the user to reduce the channel with `channel_reduction`. + +- Considering that the input feature map is usually very small, the function can upsample the feature map through `resize_shape` before the visualization. + +For example, we would like to get the feature map from the layer4 output of a pre-trained ResNet18 model and visualize it. + +1. Reduce the multi-channel feature map into a single channel using `select_max` and display it. + +```python +import numpy as np +from torchvision.models import resnet18 +from torchvision.transforms import Compose, Normalize, ToTensor + +def preprocess_image(img, mean, std): + preprocessing = Compose([ + ToTensor(), + Normalize(mean=mean, std=std) + ]) + return preprocessing(img.copy()).unsqueeze(0) + +model = resnet18(pretrained=True) + +def _forward(x): + x = model.conv1(x) + x = model.bn1(x) + x = model.relu(x) + x = model.maxpool(x) + + x1 = model.layer1(x) + x2 = model.layer2(x1) + x3 = model.layer3(x2) + x4 = model.layer4(x3) + return x4 + +model.forward = _forward + +image_norm = np.float32(image) / 255 +input_tensor = preprocess_image(image_norm, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) +feat = model(input_tensor)[0] + +visualizer = Visualizer() +drawn_img = visualizer.draw_featmap(feat, channel_reduction='select_max') +visualizer.show(drawn_img) +``` + +
+ +
+ +Since the output feat feature map size is 7x7, the visualization effect is not good if we directly work on it. Users can scale the feature map by overlaying the input image or the `resize_shape` parameter. If the size of the incoming image is not the same as the size of the feature map, the feature map will be forced to be resampled to the same spatial size as the input image. + +```python +drawn_img = visualizer.draw_featmap(feat, image, channel_reduction='select_max') +visualizer.show(drawn_img) +``` + +
+ +
+ +2. Select the top five channels with the highest activation in the multi-channel feature map by setting `topk=5`, then format them into a 2x3 layout. + +```python +drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(2, 3)) +visualizer.show(drawn_img) +``` + +
+ +
+ +Users can set their own desired layout through `arrangement`. + +```python +drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(4, 2)) +visualizer.show(drawn_img) +``` + +
+ +
+ +## Basic Storage APIs + +Once the drawing is completed, users can choose to display the result directly or save it to different backends. The backends currently supported by MMEngine include local storage, `Tensorboard` and `WandB`. The data supported include drawn pictures, scalars, and configurations. + +1. Save the result image + +Suppose you want to save to your local device. + +```python +visualizer = Visualizer(image=image, vis_backends=[dict(type='LocalVisBackend')], save_dir='temp_dir') + +visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]])) +visualizer.draw_texts("cat and dog", torch.tensor([10, 20])) +visualizer.draw_circles(torch.tensor([40, 50]), torch.tensor([20])) + +# temp_dir/vis_data/vis_image/demo_0.png will be generated +visualizer.add_image('demo', visualizer.get_image()) +``` + +The zero in the result file name is used to distinguish different steps. + +```python +# temp_dir/vis_data/vis_image/demo_1.png will be generated +visualizer.add_image('demo', visualizer.get_image(), step=1) +# temp_dir/vis_data/vis_image/demo_3.png will be generated +visualizer.add_image('demo', visualizer.get_image(), step=3) +``` + +If you want to switch to other backends, you can change the configuration file like this: + +```python +# TensorboardVisBackend +visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend')], save_dir='temp_dir') +# WandbVisBackend +visualizer = Visualizer(image=image, vis_backends=[dict(type='WandbVisBackend')], save_dir='temp_dir') +``` + +2. Store feature maps + +```python +visualizer = Visualizer(vis_backends=[dict(type='LocalVisBackend')], save_dir='temp_dir') +drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(2, 3)) +# temp_dir/vis_data/vis_image/feat_0.png will be generated +visualizer.add_image('feat', drawn_img) +``` + +3. Save scalar data such as loss + +```python +# temp_dir/vis_data/scalars.json will be generated +# save loss +visualizer.add_scalar('loss', 0.2, step=0) +visualizer.add_scalar('loss', 0.1, step=1) +# save acc +visualizer.add_scalar('acc', 0.7, step=0) +visualizer.add_scalar('acc', 0.8, step=1) +``` + +Multiple scalar data can also be saved at once. + +```python +# New contents will be added to the temp_dir/vis_data/scalars.json +visualizer.add_scalars({'loss': 0.3, 'acc': 0.8}, step=3) +``` + +4. Save configurations + +```python +from mmengine import Config +cfg=Config.fromfile('tests/data/config/py_config/config.py') +# temp_dir/vis_data/config.py will be saved +visualizer.add_config(cfg) +``` + +## Various Storage Backends + +Any `Visualizer` can be configured with any number of storage backends. `Visualizer` will loop through all the configured backends and save the results to each one. + +```python +visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend'), + dict(type='LocalVisBackend')], + save_dir='temp_dir') +# temp_dir/vis_data/events.out.tfevents.xxx files will be generated +visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]])) +visualizer.draw_texts("cat and dog", torch.tensor([10, 20])) +visualizer.draw_circles(torch.tensor([40, 50]), torch.tensor([20])) + +visualizer.add_image('demo', visualizer.get_image()) +``` + +Note: If there are multiple backends used at the same time, the `name` field must be specified. Otherwise, it is impossible to distinguish which backend it is. + +```python +visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend', name='tb_1', save_dir='temp_dir_1'), + dict(type='TensorboardVisBackend', name='tb_2', save_dir='temp_dir_2'), + dict(type='LocalVisBackend', name='local')], + save_dir='temp_dir') +``` + +## Visualize at Anywhere + +During the development, users may need to add visualization functions somewhere in their codes and save the results to different backends, which is very common for analysis and debugging. `Visualizer` in MMEngine can obtain the data from the same visualizers and then visualize them. + +Users only need to instantiate the visualizer through `get_instance` during initialization. The visualizer obtained this way is unique and globally accessible. Then it can be accessed anywhere in the code through `Visualizer.get_current_instance()`. + +```python +# call during the initialization stage +visualizer1 = Visualizer.get_instance(name='vis', vis_backends=[dict(type='LocalVisBackend')]) + +# call anywhere +visualizer2 = Visualizer.get_current_instance() +visualizer2.add_scalar('map', 0.7, step=0) + +assert id(visualizer1) == id(visualizer2) +``` + +It can also be initialized globally through the config field. + +```python +from mmengine.registry import VISUALIZERS + +visualizer_cfg=dict( + type='Visualizer', + name='vis_new', + vis_backends=[dict(type='LocalVisBackend')]) +VISUALIZERS.build(visualizer_cfg) +``` + +## Customize Storage Backends and Visualizers + +1. Call a specific storage backend + +The storage backend only provides basic functions such as saving configurations and scalars. However, users may want to utilize other powerful backend features like WandB and Tensorboard. Therefore, the storage backend provides the `experiment` attribute to facilitate users to obtain backend objects and meet various customized functions. + +For example, WandB provides an API to display tables. Users can obtain the WandB objects through the `experiment` attribute and then call a specific API to save the data as a table to show. + +```python +visualizer = Visualizer(image=image, vis_backends=[dict(type='WandbVisBackend')], + save_dir='temp_dir') + +# get WandB object +wandb = visualizer.get_backend('WandbVisBackend').experiment +# add data to the table +table = wandb.Table(columns=["step", "mAP"]) +table.add_data(1, 0.2) +table.add_data(2, 0.5) +table.add_data(3, 0.9) +# save +wandb.log({"table": table}) +``` + +2. Customize storage backends + +Users only need to inherit `BaseVisBackend` and implement various `add_xx` methods to customize the storage backend easily. + +```python +from mmengine.registry import VISBACKENDS +from mmengine.visualization import BaseVisBackend + +@VISBACKENDS.register_module() +class DemoVisBackend(BaseVisBackend): + def add_image(self, **kwargs): + pass + +visualizer = Visualizer(vis_backends=[dict(type='DemoVisBackend')], save_dir='temp_dir') +visualizer.add_image('demo',image) +``` + +3. Customize visualizers + +Similarly, users can easily customize the visualizer by inheriting `Visualizer` and implementing the functions they want to override. + +In most cases, users need to override `add_datasample`. The data usually includes detection bboxes and instance masks from annotations or model predictions. This interface is for drawing `datasample` data for various downstream libraries. Taking MMDetection as an example, the `datasample` data usually includes labeled bboxs, labeled masks, predicted bboxs, or predicted masks. MMDetection will inherit `Visualizer` and implement the `add_datasample` interface, drawing the data related to the detection task. + +```python +from mmengine.registry import VISUALIZERS + +@VISUALIZERS.register_module() +class DetLocalVisualizer(Visualizer): + def add_datasample(self, + name, + image: np.ndarray, + data_sample: Optional['BaseDataElement'] = None, + draw_gt: bool = True, + draw_pred: bool = True, + show: bool = False, + wait_time: int = 0, + step: int = 0) -> None: + pass + +visualizer_cfg = dict( + type='DetLocalVisualizer', vis_backends=[dict(type='WandbVisBackend')], name='visualizer') + +# global initialize +VISUALIZERS.build(visualizer_cfg) + +# call anywhere in your code +det_local_visualizer = Visualizer.get_current_instance() +det_local_visualizer.add_datasample('det', image, data_sample) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/api/config.rst b/testbed/open-mmlab__mmengine/docs/en/api/config.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6c066e67466e3bb81e83fb9fe9053d682927e21 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/config.rst @@ -0,0 +1,16 @@ +.. role:: hidden + :class: hidden-section + +mmengine.config +=================================== + +.. currentmodule:: mmengine.config + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Config + ConfigDict + DictAction diff --git a/testbed/open-mmlab__mmengine/docs/en/api/dataset.rst b/testbed/open-mmlab__mmengine/docs/en/api/dataset.rst new file mode 100644 index 0000000000000000000000000000000000000000..84ea849101b42aebfc797420dc705a3f21c7b229 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/dataset.rst @@ -0,0 +1,57 @@ +.. role:: hidden + :class: hidden-section + +mmengine.dataset +=================================== + +.. contents:: mmengine.dataset + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.dataset + +Dataset +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseDataset + Compose + +Dataset Wrapper +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + ClassBalancedDataset + ConcatDataset + RepeatDataset + +Sampler +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + DefaultSampler + InfiniteSampler + +Utils +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + default_collate + pseudo_collate + worker_init_fn diff --git a/testbed/open-mmlab__mmengine/docs/en/api/device.rst b/testbed/open-mmlab__mmengine/docs/en/api/device.rst new file mode 100644 index 0000000000000000000000000000000000000000..4a16c7383789322908127c8780c3be9b54f11c20 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/device.rst @@ -0,0 +1,18 @@ +.. role:: hidden + :class: hidden-section + +mmengine.device +=================================== + +.. currentmodule:: mmengine.device + +.. autosummary:: + :toctree: generated + :nosignatures: + + get_device + get_max_cuda_memory + is_cuda_available + is_npu_available + is_mlu_available + is_mps_available diff --git a/testbed/open-mmlab__mmengine/docs/en/api/dist.rst b/testbed/open-mmlab__mmengine/docs/en/api/dist.rst new file mode 100644 index 0000000000000000000000000000000000000000..1d1bd2e846253cf59071b96991109bc6259d181c --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/dist.rst @@ -0,0 +1,58 @@ +.. role:: hidden + :class: hidden-section + +mmengine.dist +=================================== + +.. contents:: mmengine.dist + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.dist + +dist +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + gather + gather_object + all_gather + all_gather_object + all_reduce + all_reduce_dict + all_reduce_params + broadcast + sync_random_seed + broadcast_object_list + collect_results + collect_results_cpu + collect_results_gpu + +utils +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + get_dist_info + init_dist + init_local_group + get_backend + get_world_size + get_rank + get_local_size + get_local_rank + is_main_process + master_only + barrier + is_distributed + get_local_group + get_default_group + get_data_device + get_comm_device + cast_data_device diff --git a/testbed/open-mmlab__mmengine/docs/en/api/evaluator.rst b/testbed/open-mmlab__mmengine/docs/en/api/evaluator.rst new file mode 100644 index 0000000000000000000000000000000000000000..65dfeba940b09ac5c7d1edc4a4a5a7036fad0b48 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/evaluator.rst @@ -0,0 +1,43 @@ +.. role:: hidden + :class: hidden-section + +mmengine.evaluator +=================================== + +.. contents:: mmengine.evaluator + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.evaluator + +Evaluator +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Evaluator + +Metric +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseMetric + + DumpResults + +Utils +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + get_metric_value diff --git a/testbed/open-mmlab__mmengine/docs/en/api/fileio.rst b/testbed/open-mmlab__mmengine/docs/en/api/fileio.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b8c14b42ab2b66a4c3eb3232549608dd70a6637 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/fileio.rst @@ -0,0 +1,95 @@ +.. role:: hidden + :class: hidden-section + +mmengine.fileio +=================================== + +.. contents:: mmengine.fileio + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.fileio + +File Backend +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseStorageBackend + FileClient + HardDiskBackend + LocalBackend + HTTPBackend + LmdbBackend + MemcachedBackend + PetrelBackend + +.. autosummary:: + :toctree: generated + :nosignatures: + + register_backend + +File Handler +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseFileHandler + JsonHandler + PickleHandler + YamlHandler + +.. autosummary:: + :toctree: generated + :nosignatures: + + register_handler + +File IO +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + dump + load + copy_if_symlink_fails + copyfile + copyfile_from_local + copyfile_to_local + copytree + copytree_from_local + copytree_to_local + exists + generate_presigned_url + get + get_file_backend + get_local_path + get_text + isdir + isfile + join_path + list_dir_or_file + put + put_text + remove + rmtree + +Parse File +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + dict_from_file + list_from_file diff --git a/testbed/open-mmlab__mmengine/docs/en/api/hooks.rst b/testbed/open-mmlab__mmengine/docs/en/api/hooks.rst new file mode 100644 index 0000000000000000000000000000000000000000..c061246b90554f3cdb02c3f41c3867d1109a791c --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/hooks.rst @@ -0,0 +1,24 @@ +.. role:: hidden + :class: hidden-section + +mmengine.hooks +=================================== + +.. currentmodule:: mmengine.hooks + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Hook + CheckpointHook + EMAHook + LoggerHook + NaiveVisualizationHook + ParamSchedulerHook + RuntimeInfoHook + DistSamplerSeedHook + IterTimerHook + SyncBuffersHook + EmptyCacheHook diff --git a/testbed/open-mmlab__mmengine/docs/en/api/hub.rst b/testbed/open-mmlab__mmengine/docs/en/api/hub.rst new file mode 100644 index 0000000000000000000000000000000000000000..335da9de50dbecc8138280c67e20ec945e66f11b --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/hub.rst @@ -0,0 +1,14 @@ +.. role:: hidden + :class: hidden-section + +mmengine.hub +=================================== + +.. currentmodule:: mmengine.hub + +.. autosummary:: + :toctree: generated + :nosignatures: + + get_config + get_model diff --git a/testbed/open-mmlab__mmengine/docs/en/api/logging.rst b/testbed/open-mmlab__mmengine/docs/en/api/logging.rst new file mode 100644 index 0000000000000000000000000000000000000000..1f674c72e67ba2d19a44d0635048e5e3a960928f --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/logging.rst @@ -0,0 +1,22 @@ +.. role:: hidden + :class: hidden-section + +mmengine.logging +=================================== + +.. currentmodule:: mmengine.logging + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + MMLogger + MessageHub + HistoryBuffer + +.. autosummary:: + :toctree: generated + :nosignatures: + + print_log diff --git a/testbed/open-mmlab__mmengine/docs/en/api/model.rst b/testbed/open-mmlab__mmengine/docs/en/api/model.rst new file mode 100644 index 0000000000000000000000000000000000000000..321c39ed4680839e06e06b57a1ae01f04b67f4fe --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/model.rst @@ -0,0 +1,116 @@ +.. role:: hidden + :class: hidden-section + +mmengine.model +=================================== + +.. contents:: mmengine.model + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.model + +Module +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseModule + ModuleDict + ModuleList + Sequential + +Model +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseModel + BaseDataPreprocessor + ImgDataPreprocessor + BaseTTAModel + +EMA +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseAveragedModel + ExponentialMovingAverage + MomentumAnnealingEMA + StochasticWeightAverage + +Model Wrapper +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + MMDistributedDataParallel + MMSeparateDistributedDataParallel + MMFullyShardedDataParallel + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + is_model_wrapper + +Weight Initialization +---------------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseInit + Caffe2XavierInit + ConstantInit + KaimingInit + NormalInit + PretrainedInit + TruncNormalInit + UniformInit + XavierInit + +.. autosummary:: + :toctree: generated + :nosignatures: + + bias_init_with_prob + caffe2_xavier_init + constant_init + initialize + kaiming_init + normal_init + trunc_normal_init + uniform_init + update_init_info + xavier_init + +Utils +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + detect_anomalous_params + merge_dict + stack_batch + revert_sync_batchnorm + convert_sync_batchnorm diff --git a/testbed/open-mmlab__mmengine/docs/en/api/optim.rst b/testbed/open-mmlab__mmengine/docs/en/api/optim.rst new file mode 100644 index 0000000000000000000000000000000000000000..634884c9f522d437fbe8e50c2515d9218848c8b7 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/optim.rst @@ -0,0 +1,65 @@ +.. role:: hidden + :class: hidden-section + +mmengine.optim +=================================== + +.. contents:: mmengine.optim + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.optim + +Optimizer +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + AmpOptimWrapper + OptimWrapper + OptimWrapperDict + DefaultOptimWrapperConstructor + ZeroRedundancyOptimizer + +.. autosummary:: + :toctree: generated + :nosignatures: + + build_optim_wrapper + +Scheduler +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + _ParamScheduler + ConstantLR + ConstantMomentum + ConstantParamScheduler + CosineAnnealingLR + CosineAnnealingMomentum + CosineAnnealingParamScheduler + ExponentialLR + ExponentialMomentum + ExponentialParamScheduler + LinearLR + LinearMomentum + LinearParamScheduler + MultiStepLR + MultiStepMomentum + MultiStepParamScheduler + OneCycleLR + OneCycleParamScheduler + PolyLR + PolyMomentum + PolyParamScheduler + StepLR + StepMomentum + StepParamScheduler diff --git a/testbed/open-mmlab__mmengine/docs/en/api/registry.rst b/testbed/open-mmlab__mmengine/docs/en/api/registry.rst new file mode 100644 index 0000000000000000000000000000000000000000..84bbba8cc32427a0e30ed42af6fa3356949dcf94 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/registry.rst @@ -0,0 +1,26 @@ +.. role:: hidden + :class: hidden-section + +mmengine.registry +=================================== + +.. currentmodule:: mmengine.registry + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Registry + DefaultScope + +.. autosummary:: + :toctree: generated + :nosignatures: + + build_from_cfg + build_model_from_cfg + build_runner_from_cfg + build_scheduler_from_cfg + count_registered_modules + traverse_registry_tree diff --git a/testbed/open-mmlab__mmengine/docs/en/api/runner.rst b/testbed/open-mmlab__mmengine/docs/en/api/runner.rst new file mode 100644 index 0000000000000000000000000000000000000000..3217d17b92dea68a6bd7123d7e2b9cecf5ef69c3 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/runner.rst @@ -0,0 +1,87 @@ +.. role:: hidden + :class: hidden-section + +mmengine.runner +=================================== + +.. contents:: mmengine.runner + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.runner + +Runner +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Runner + +Loop +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseLoop + EpochBasedTrainLoop + IterBasedTrainLoop + ValLoop + TestLoop + +Checkpoints +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + CheckpointLoader + +.. autosummary:: + :toctree: generated + :nosignatures: + + find_latest_checkpoint + get_deprecated_model_names + get_external_models + get_mmcls_models + get_state_dict + get_torchvision_models + load_checkpoint + load_state_dict + save_checkpoint + weights_to_cpu + +AMP +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + autocast + +Miscellaneous +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + LogProcessor + Priority + +.. autosummary:: + :toctree: generated + :nosignatures: + + get_priority diff --git a/testbed/open-mmlab__mmengine/docs/en/api/structures.rst b/testbed/open-mmlab__mmengine/docs/en/api/structures.rst new file mode 100644 index 0000000000000000000000000000000000000000..bfb651be30d12ca16c9a1d226627276c1ea61a43 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/structures.rst @@ -0,0 +1,22 @@ +.. role:: hidden + :class: hidden-section + +mmengine.structures +=================================== + +.. contents:: mmengine.structures + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.structures + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseDataElement + InstanceData + LabelData + PixelData diff --git a/testbed/open-mmlab__mmengine/docs/en/api/utils.dl_utils.rst b/testbed/open-mmlab__mmengine/docs/en/api/utils.dl_utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..8f40f18da1d45c06ed97fec030b51a727a4742ee --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/utils.dl_utils.rst @@ -0,0 +1,29 @@ +.. role:: hidden + :class: hidden-section + +mmengine.utils.dl_utils +=================================== + +.. currentmodule:: mmengine.utils.dl_utils + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + TimeCounter + +.. autosummary:: + :toctree: generated + :nosignatures: + + collect_env + load_url + has_batch_norm + is_norm + mmcv_full_available + tensor2imgs + TORCH_VERSION + set_multi_processing + torch_meshgrid + is_jit_tracing diff --git a/testbed/open-mmlab__mmengine/docs/en/api/utils.rst b/testbed/open-mmlab__mmengine/docs/en/api/utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..681e15d2c0115979e756a147a2f72366e33bf255 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/utils.rst @@ -0,0 +1,118 @@ +.. role:: hidden + :class: hidden-section + +mmengine.utils +=================================== + +.. contents:: mmengine.utils + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.utils + +Manager +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + ManagerMeta + ManagerMixin + +Path +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + check_file_exist + fopen + is_abs + is_filepath + mkdir_or_exist + scandir + symlink + +Package +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + call_command + install_package + get_installed_path + is_installed + +Version +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + digit_version + get_git_hash + +Progress Bar +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + ProgressBar + +.. autosummary:: + :toctree: generated + :nosignatures: + + track_iter_progress + track_parallel_progress + track_progress + + +Miscellaneous +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Timer + TimerError + +.. autosummary:: + :toctree: generated + :nosignatures: + + is_list_of + is_tuple_of + is_seq_of + is_str + iter_cast + list_cast + tuple_cast + concat_list + slice_list + to_1tuple + to_2tuple + to_3tuple + to_4tuple + to_ntuple + check_prerequisites + deprecated_api_warning + deprecated_function + has_method + is_method_overridden + import_modules_from_strings + requires_executable + requires_package + check_time diff --git a/testbed/open-mmlab__mmengine/docs/en/api/visualization.rst b/testbed/open-mmlab__mmengine/docs/en/api/visualization.rst new file mode 100644 index 0000000000000000000000000000000000000000..5265dc6edbd427c0b89cbd43944d96e08016980b --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/api/visualization.rst @@ -0,0 +1,35 @@ +.. role:: hidden + :class: hidden-section + +mmengine.visualization +=================================== + +.. contents:: mmengine.visualization + :depth: 2 + :local: + :backlinks: top + +.. currentmodule:: mmengine.visualization + +Visualizer +---------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + Visualizer + +visualization Backend +--------------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: classtemplate.rst + + BaseVisBackend + LocalVisBackend + TensorboardVisBackend + WandbVisBackend diff --git a/testbed/open-mmlab__mmengine/docs/en/design/evaluation.md b/testbed/open-mmlab__mmengine/docs/en/design/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..11f180487f296076c3aae839cd7a45937f75af3d --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/design/evaluation.md @@ -0,0 +1,3 @@ +# Evaluation + +Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/design/evaluation.html). diff --git a/testbed/open-mmlab__mmengine/docs/en/design/hook.md b/testbed/open-mmlab__mmengine/docs/en/design/hook.md new file mode 100644 index 0000000000000000000000000000000000000000..854e444d8a71dfe07df2189cda852081cb325554 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/design/hook.md @@ -0,0 +1,204 @@ +# Hook + +Hook programming is a programming pattern in which a mount point is set in one or more locations of a program. When the program runs to a mount point, all methods registered to it at runtime are automatically called. Hook programming can increase the flexibility and extensibility of the program since users can register custom methods to the mount point to be called without modifying the code in the program. + +## Examples + +Here is an example of how it works. + +```python +pre_hooks = [(print, 'hello')] +post_hooks = [(print, 'goodbye')] + +def main(): + for func, arg in pre_hooks: + func(arg) + print('do something here') + for func, arg in post_hooks: + func(arg) + +main() +``` + +Output of the above example. + +``` +hello +do something here +goodbye +``` + +As we can see, the `main` function calls `print` defined in hooks in two locations without making any changes. + +Hook is also used everywhere in PyTorch, for example in the neural network module (nn.Module) to get the forward input and output of the module as well as the reverse input and output. For example, the [`register_forward_hook`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook) method registers a forward hook with the module, and the hook can get the forward input and output of the module. + +The following is an example of the `register_forward_hook` usage. + +```python +import torch +import torch.nn as nn + +def forward_hook_fn( + module, # object to be registered hooks + input, # forward input of module + output, # forward output of module +): + print(f'"forward_hook_fn" is invoked by {module.name}') + print('weight:', module.weight.data) + print('bias:', module.bias.data) + print('input:', input) + print('output:', output) + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.fc = nn.Linear(3, 1) + + def forward(self, x): + y = self.fc(x) + return y + +model = Model() +# Register forward_hook_fn to each submodule of model +for module in model.children(): + module.register_forward_hook(forward_hook_fn) + +x = torch.Tensor([[0.0, 1.0, 2.0]]) +y = model(x) +``` + +Output of the above example. + +```python +"forward_hook_fn" is invoked by Linear(in_features=3, out_features=1, bias=True) +weight: tensor([[-0.4077, 0.0119, -0.3606]]) +bias: tensor([-0.2943]) +input: (tensor([[0., 1., 2.]]),) +output: tensor([[-1.0036]], grad_fn=) +``` + +We can see that the `forward_hook_fn` hook registered to the `nn.Linear` module is called, and in that hook the weights, biases, module inputs, and outputs of the Linear module are printed. For more information on the use of PyTorch hooks you can read [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). + +## Design on MMEngine + +Before introducing the design of the `Hook` in MMEngine, let's briefly introduce the basic steps of model training using PyTorch (copied from [PyTorch Tutorials](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py)). + +```python +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +import torchvision.transforms as transforms +from torch.utils.data import Dataset, DataLoader + +class CustomDataset(Dataset): + pass + +class Net(nn.Module): + pass + +def main(): + transform = transforms.ToTensor() + train_dataset = CustomDataset(transform=transform, ...) + val_dataset = CustomDataset(transform=transform, ...) + test_dataset = CustomDataset(transform=transform, ...) + train_dataloader = DataLoader(train_dataset, ...) + val_dataloader = DataLoader(val_dataset, ...) + test_dataloader = DataLoader(test_dataset, ...) + + net = Net() + criterion = nn.CrossEntropyLoss() + optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) + + for i in range(max_epochs): + for inputs, labels in train_dataloader: + optimizer.zero_grad() + outputs = net(inputs) + loss = criterion(outputs, labels) + loss.backward() + optimizer.step() + + with torch.no_grad(): + for inputs, labels in val_dataloader: + outputs = net(inputs) + loss = criterion(outputs, labels) + + with torch.no_grad(): + for inputs, labels in test_dataloader: + outputs = net(inputs) + accuracy = ... +``` + +The above pseudo-code is the basic step to train a model. If we want to add custom operations to the above code, we need to modify and extend the `main` function continuously. To increase the flexibility and extensibility of the `main` function, we can insert mount points into the `main` function and implement the logic of calling hooks at the corresponding mount points. In this case, we only need to insert hooks into these locations to implement custom logic, such as loading model weights, updating model parameters, etc. + +```python +def main(): + ... + call_hooks('before_run', hooks) + call_hooks('after_load_checkpoint', hooks) + call_hooks('before_train', hooks) + for i in range(max_epochs): + call_hooks('before_train_epoch', hooks) + for inputs, labels in train_dataloader: + call_hooks('before_train_iter', hooks) + outputs = net(inputs) + loss = criterion(outputs, labels) + call_hooks('after_train_iter', hooks) + loss.backward() + optimizer.step() + call_hooks('after_train_epoch', hooks) + + call_hooks('before_val_epoch', hooks) + with torch.no_grad(): + for inputs, labels in val_dataloader: + call_hooks('before_val_iter', hooks) + outputs = net(inputs) + loss = criterion(outputs, labels) + call_hooks('after_val_iter', hooks) + call_hooks('after_val_epoch', hooks) + + call_hooks('before_save_checkpoint', hooks) + call_hooks('after_train', hooks) + + call_hooks('before_test_epoch', hooks) + with torch.no_grad(): + for inputs, labels in test_dataloader: + call_hooks('before_test_iter', hooks) + outputs = net(inputs) + accuracy = ... + call_hooks('after_test_iter', hooks) + call_hooks('after_test_epoch', hooks) + + call_hooks('after_run', hooks) +``` + +In MMEngine, we encapsulates the training process into an executor (`Runner`). The `Runner` calls hooks at specific mount points to complete the customization logic. For more information about `Runner`, please read the [Runner documentation](../tutorials/runner.md). + +To facilitate management, MMEngine defines mount points as methods and integrates them into [Base Hook](mmengine.hooks.Hook). We just need to inherit the base hook and implement custom logic at specific location according to our needs, then register the hooks to the `Runner`. Those hooks will be called automatically. + +There are 22 mount points in the [Base Hook](mmengine.hooks.Hook). + +- before_run +- after_run +- before_train +- after_train +- before_train_epoch +- after_train_epoch +- before_train_iter +- after_train_iter +- before_val +- after_val +- before_test_epoch +- after_test_epoch +- before_val_iter +- after_val_iter +- before_test +- after_test +- before_test_epoch +- after_test_epoch +- before_test_iter +- after_test_iter +- before_save_checkpoint +- after_load_checkpoint + +Further readings: [Hook tutorial](../tutorials/hook.md) and [Hook API documentations](mmengine.hooks) diff --git a/testbed/open-mmlab__mmengine/docs/en/design/logging.md b/testbed/open-mmlab__mmengine/docs/en/design/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..2e28cd0a9a2dcde402af140b3fe1e486bfa2548e --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/design/logging.md @@ -0,0 +1,450 @@ +# Logging + +## Overview + +[Runner](./runner.md) produces amounts of logs during execution. These logs include dataset information, model initialization, learning rates, losses, etc. In order to make these logs easily accessed by users, MMEngine designs [MessageHub](mmengine.logging.MessageHub), [HistoryBuffer](mmengine.logging.HistoryBuffer), [LogProcessor](mmengine.runner.LogProcessor) and [MMLogger](mmengine.logging.MMLogger), which enable: + +- Configure statistical methods in config files. For example, losses can be globally averaged or smoothed by a sliding window. +- Query training states (iterations, epochs, etc.) in any module +- Configure whether save the multi-process log or not during distributed training. + +![image](https://user-images.githubusercontent.com/57566630/163441489-47999f3a-3259-44ab-949c-77a8a599faa5.png) + +Each scalar (losses, learning rates, etc.) during training is encapsulated by HistoryBuffer, managed by MessageHub in key-value pairs, formatted by LogProcessor and then exported to various visualization backends by [LoggerHook](mmengine.hook.LoggerHook). **In most cases, statistical methods of these scalars can be configured through the LogProcessor without understanding the data flow.** Before diving into the design of the logging system, please read through [logging tutorial](../advanced_tutorials/logging.md) first for familiarizing basic use cases. + +## HistoryBuffer + +`HistoryBuffer` records the history of the corresponding scalar such as losses, learning rates, and iteration time in an array. As an internal class, it works with [MessageHub](mmengine.logging.MessageHub), LoggerHook and [LogProcessor](mmengine.runner.LogProcessor) to make training log configurable. Meanwhile, HistoryBuffer can also be used alone, which enables users to manage their training logs and do various statistics in an easy manner. + +We will first introduce the usage of HistoryBuffer in the following section. The association between HistoryBuffer and MessageHub will be introduced later in the MessageHub section. + +### HistoryBuffer Initialization + +HistoryBuffer accepts `log_history`, `count_history` and `max_length` for initialization. + +- `log_history` records the history of the scaler. For example, if the loss in the previous 3 iterations is 0.3, 0.2, 0.1 respectively, there will be `log_history=[0.3, 0.2, 0.1]`. +- `count_history` controls the statistical granularity and will be used when counting the average. Take the above example, if we count the average loss across iterations, we have `count_history=[1, 1, 1]`. Instead, if we count the average loss across images with `batch_size=8`, then we have `count_history=[8, 8, 8]`. +- `max_length` controls the maximum length of the history. If the length of `log_history` and `count_history` exceeds `max_length`, the earliest elements will be removed. + +Besides, we can access the history of the data through `history_buffer.data`. + +```python +from mmengine.logging import HistoryBuffer + +history_buffer = HistoryBuffer() # Default initialization +log_history, count_history = history_buffer.data +# [] [] +history_buffer = HistoryBuffer([1, 2, 3], [1, 2, 3]) # Init with lists +log_history, count_history = history_buffer.data +# [1 2 3] [1 2 3] +history_buffer = HistoryBuffer([1, 2, 3], [1, 2, 3], max_length=2) +# The length of history buffer(3) exceeds the max_length(2), the first few elements will be ignored. +log_history, count_history = history_buffer.data +# [2 3] [2 3] +``` + +### HistoryBuffer Update + +We can update the `log_history` and `count_history` through `HistoryBuffer.update(log_history, count_history)`. + +```python +history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1]) +history_buffer.update(4) # count default to 1 +log_history, count_history = history_buffer.data +# [1, 2, 3, 4] [1, 1, 1, 1] +history_buffer.update(5, 2) +log_history, count_history = history_buffer.data +# [1, 2, 3, 4, 5] [1, 1, 1, 1, 2] +``` + +### Basic Statistical Methods + +HistoryBuffer provides some basic statistical methods: + +- `current()`: Get the latest data. +- `mean(window_size=None)`: Count the mean value of the previous `window_size` data. Defaults to None, as global mean. +- `max(window_size=None)`: Count the max value of the previous `window_size` data. Defaults to None, as global maximum. +- `min(window_size=None)`: Count the min value of the previous `window_size` data. Defaults to None, as global minimum. + +```python +history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1]) +history_buffer.min(2) +# 2, the minimum in [2, 3] +history_buffer.min() +# 1, the global minimum + +history_buffer.max(2) +# 3,the maximum in [2, 3] +history_buffer.min() +# 3, the global maximum +history_buffer.mean(2) +# 2.5,the mean value in [2, 3], (2 + 3) / (1 + 1) +history_buffer.mean() +# 2, the global mean, (1 + 2 + 3) / (1 + 1 + 1) +history_buffer = HistoryBuffer([1, 2, 3], [2, 2, 2]) # Cases when counts are not 1 +history_buffer.mean() +# 1, (1 + 2 + 3) / (2 + 2 + 2) +history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1]) +history_buffer.update(4, 1) +history_buffer.current() +# 4 +``` + +### Statistical Methods Invoking + +Statistical methods can be accessed through `HistoryBuffer.statistics` with method name and arguments. The `name` parameter should be a registered method name (i.e. built-in methods like `min` and `max`), while arguments should be the corresponding method's arguments. + +```python +history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1]) +history_buffer.statistics('mean') +# 2, as global mean +history_buffer.statistics('mean', 2) +# 2.5, as the mean of [2, 3] +history_buffer.statistics('mean', 2, 3) +# Error! mismatch arguments given to `mean(window_size)` +history_buffer.statistics('data') +# Error! `data` method not registered +``` + +### Statistical Methods Registration + +Custom statistical methods can be registered through `@HistoryBuffer.register_statistics`. + +```python +from mmengine.logging import HistoryBuffer +import numpy as np + + +@HistoryBuffer.register_statistics +def weighted_mean(self, window_size, weight): + assert len(weight) == window_size + return (self._log_history[-window_size:] * np.array(weight)).sum() / \ + self._count_history[-window_size:] + + +history_buffer = HistoryBuffer([1, 2], [1, 1]) +history_buffer.statistics('weighted_mean', 2, [2, 1]) # get (2 * 1 + 1 * 2) / (1 + 1) +``` + +### Use Cases + +```Python +logs = dict(lr=HistoryBuffer(), loss=HistoryBuffer()) # different keys for different logs +max_iter = 10 +log_interval = 5 +for iter in range(1, max_iter+1): + lr = iter / max_iter * 0.1 # linear scaling of lr + loss = 1 / iter # loss + logs['lr'].update(lr, 1) + logs['loss'].update(loss, 1) + if iter % log_interval == 0: + latest_lr = logs['lr'].statistics('current') # select statistical methods by name + mean_loss = logs['loss'].statistics('mean', log_interval) # mean loss of the latest `log_interval` iterations + print(f'lr: {latest_lr}\n' + f'loss: {mean_loss}') +# lr: 0.05 +# loss: 0.45666666666666667 +# lr: 0.1 +# loss: 0.12912698412698415 +``` + +## MessageHub + +As shown above, HistoryBuffer can easily handle the update and statistics of a single variable. However, there are multiple variables to log during training, each potentially coming from a different module. This makes it an issue to collect and distribute different variables. To address this issue, we provide MessageHub in MMEngine. It is derived from [ManagerMixin](../advanced_tutorials/manager_mixin.md) and thus can be accessed globally. It can be used to simplify the sharing of data across modules. + +MessageHub stores data into 2 internal dictionaries, each has its own definition: + +- `log_scalars`: Scalars including losses, learning rates and iteration time are collected from different modules and stored into the HistoryBuffer with corresponding key in this dict. Values in this dict will be formatted by [LogProcessor](mmengine.runner.LogProcessor) and then output to terminal or saved locally. If you want to customize your logging info, you can add new keys to this dict and update in the subsequent training steps. +- `runtime_info`: Some runtime information including epochs and iterations are stored in this dict. This dict makes it easy to share some necessary information across modules. + +```{note} +You may need to use MessageHub only if you want to add extra data to logs or share custom data across modules. +``` + +The following examples show the usage of MessageHub, including scalars update, data sharing and log customization. + +### Update & get training log + +HistoryBuffers are stored in MessageHub's `log_scalars` dictionary as values. You can call `update_scalars` method to update the HistoryBuffer with the given key. On first call with an unseen key, a HistoryBuffer will be initialized. In the subsequent calls with the same key, the corresponding HistoryBuffer's `update` method will be invoked. You can get values or statistics of a HistoryBuffer by specifying a key in `get_scalar` method. You can also get full logs by directly accessing the `log_scalars` attribute of a MessageHub. + +```python +from mmengine import MessageHub + +message_hub = MessageHub.get_instance('task') +message_hub.update_scalar('train/loss', 1, 1) +message_hub.get_scalar('train/loss').current() # 1, the latest updated train/loss +message_hub.update_scalar('train/loss', 3, 1) +message_hub.get_scalar('train/loss').mean() # 2, the mean calculated as (1 + 3) / (1 + 1) +message_hub.update_scalar('train/lr', 0.1, 1) + +message_hub.update_scalars({'train/time': {'value': 0.1, 'count': 1}, + 'train/data_time': {'value': 0.1, 'count': 1}}) + +train_time = message_hub.get_scalar('train/time') # 1 + +log_dict = message_hub.log_scalars # return the whole dict +lr_buffer, loss_buffer, time_buffer, data_time_buffer = ( + log_dict['train/lr'], log_dict['train/loss'], log_dict['train/time'], + log_dict['train/data_time']) +``` + +```{note} +Losses, learning rates and iteration time are automatically updated by runner and hooks. You are not supposed to manually update them. +``` + +```{note} +MessageHub has no special requirements for keys in `log_scalars`. However, MMEngine will only output a scalar to logs if it has a key prfixed with train/val/test. +``` + +### Update & get runtime info + +Runtime information is stored in `runtime_info` dict. The dict accepts data in any data types. Different from HistoryBuffer, the value will be overwritten on every update. + +```python +message_hub = MessageHub.get_instance('task') +message_hub.update_info('iter', 1) +message_hub.get_info('iter') # 1 +message_hub.update_info('iter', 2) +message_hub.get_info('iter') # 2, overwritten by the above command +``` + +### Share MessageHub across modules + +During the execution of a runner, different modules receive and post data through MessageHub. Then, [RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook) gathers data such as losses and learning rates before exporting them to user defined backends (Tensorboard, WandB, etc). Following is an example to show the communication between logger hook and other modules. + +```python +from mmengine import MessageHub + +class LogProcessor: + # gather data from other modules. similar to logger hook + def __init__(self, name): + self.message_hub = MessageHub.get_instance(name) # access MessageHub + + def run(self): + print(f"Learning rate is {self.message_hub.get_scalar('train/lr').current()}") + print(f"loss is {self.message_hub.get_scalar('train/loss').current()}") + print(f"meta is {self.message_hub.get_info('meta')}") + + +class LrUpdater: + # update the learning rate + def __init__(self, name): + self.message_hub = MessageHub.get_instance(name) # access MessageHub + + def run(self): + self.message_hub.update_scalar('train/lr', 0.001) + # update the learning rate, saved as HistoryBuffer + + +class MetaUpdater: + # update meta information + def __init__(self, name): + self.message_hub = MessageHub.get_instance(name) + + def run(self): + self.message_hub.update_info( + 'meta', + dict(experiment='retinanet_r50_caffe_fpn_1x_coco.py', + repo='mmdetection')) # meta info will be overwritten on every update + + +class LossUpdater: + # update losses + def __init__(self, name): + self.message_hub = MessageHub.get_instance(name) + + def run(self): + self.message_hub.update_scalar('train/loss', 0.1) + +class ToyRunner: + # compose of different modules + def __init__(self, name): + self.message_hub = MessageHub.get_instance(name) # this will create a global MessageHub instance + self.log_processor = LogProcessor(name) + self.updaters = [LossUpdater(name), + MetaUpdater(name), + LrUpdater(name)] + + def run(self): + for updater in self.updaters: + updater.run() + self.log_processor.run() + +if __name__ == '__main__': + task = ToyRunner('name') + task.run() + # Learning rate is 0.001 + # loss is 0.1 + # meta {'experiment': 'retinanet_r50_caffe_fpn_1x_coco.py', 'repo': 'mmdetection'} +``` + +### Add custom logs + +Users can update scalars in MessageHub anywhere in any module. All data in `log_scalars` with valid keys are exported to user defined backends after statistical methods. + +```{note} +Only those data in `log_scalars` with keys prefixed with train/val/test are exported. +``` + +```python +class CustomModule: + def __init__(self): + self.message_hub = MessageHub.get_current_instance() + + def custom_method(self): + self.message_hub.update_scalar('train/a', 100) + self.message_hub.update_scalars({'train/b': 1, 'train/c': 2}) +``` + +By default, the latest value of the custom data(a, b and c) are exported. Users can also configure the [LogProcessor](mmengine.runner.LogProcessor) to switch between statistical methods. + +## LogProcessor + +Users can configure the LogProcessor to specify the statistical methods and extra arguments. By default, learning rates are displayed by the latest value, while losses and iteration time are counted with an iteration-based smooth method. + +### Minimum example + +```python +log_processor = dict( + window_size=10 +) +``` + +In this configuration, losses and iteration time will be averaged in the latest 10 iterations. The output might be: + +```bash +04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.13 +``` + +### Custom statistical methods + +Users can configure the `custom_cfg` list to specify the statistical method. Each element in `custom_cfg` must be a dict consisting of the following keys: + +- `data_src`: Required argument representing the data source of the log. A data source may have multiple statistical methods. Default sources, which are automatically added to logs, include all keys in loss dict(i.e. `loss`), learning rate(`lr`) and iteration time(`time` & `data_time`). Besides, all scalars updated by MessageHub's `update_scalar`/`update_scalars` methods with valid keys are configurable data sources, but be aware that the prefix('train/', 'val/', 'test/') should be removed. +- `method_name`: Required argument representing the statistical method. It supports both built-in methods and custom methods. +- `log_name`: Optional argument representing the output name after statistics. If not specified, the new log will overwrite the old one. +- Other arguments: Extra arguments needed by your specified method. `window_size` is a special key, which can be either an int, 'epoch' or 'global'. LogProcessor will parse these arguments and return statistical result based on iteration/epoch/global smooth. + +1. Overwrite the old statistical method + +```python +log_processor = dict( + window_size=10, + by_epoch=True, + custom_cfg=[ + dict(data_src='loss', + method_name='mean', + window_size=100)]) +``` + +In this configuration, LogProcessor will overwrite the default window size 10 by a larger window size 100 and output the mean value to 'loss' field in logs. + +```bash +04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.11 +``` + +2. New statistical method without overwriting + +```python +log_processor = dict( + window_size=10, + by_epoch=True, + custom_cfg=[ + dict(data_src='loss', + log_name='loss_min', + method_name='min', + window_size=100)]) +``` + +```bash +04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.11, loss_min: 0.08 +``` + +## MMLogger + +In order to export logs with clear hierarchies, unified formats and less disturbation from third-party logging systems, MMengine implements a `MMLogger` class based on `logging`. It is derived from ManagerMixin. Compared with `logging.logger`, it enables accessing logger in current runner without knowing the logger name. + +### Instantiate MMLogger + +Users can create a global logger by calling `get_instance`. The default log format is shown as below + +```python +logger = MMLogger.get_instance('mmengine', log_level='INFO') +logger.info("this is a test") +# 04/15 14:01:11 - mmengine - INFO - this is a test +``` + +Apart from user defined messages, the logger will also export timestamps, logger name and log level. ERROR messages are treated specially with red highlight and extra information like error locations. + +```python +logger = MMLogger.get_instance('mmengine', log_level='INFO') +logger.error('division by zero') +# 04/15 14:01:56 - mmengine - ERROR - /mnt/d/PythonCode/DeepLearning/OpenMMLab/mmengine/a.py - - 4 - division by zero +``` + +### Export logs + +When `get_instance` is invoked with log_file argument, logs will be additionally exported to local storage in text format. + +```Python +logger = MMLogger.get_instance('mmengine', log_file='tmp.log', log_level='INFO') +logger.info("this is a test") +# 04/15 14:01:11 - mmengine - INFO - this is a test +``` + +`tmp/tmp.log`: + +```text +04/15 14:01:11 - mmengine - INFO - this is a test +``` + +Since distributed applications will create multiple log files, we add a directory with the same name to the exported log file name. Logs from different processes are all saved in this directory. Therefore, the actual log file path in the above example is `tmp/tmp.log`. + +### Export logs in distributed training + +When training with pytorch distributed methods, users can set `distributed=True` in config file to export multiple logs from all processes. If not specified, only master process will export log file. + +```python +logger = MMLogger.get_instance('mmengine', log_file='tmp.log', distributed=True, log_level='INFO') +``` + +In the case of multiple processes in a single node, or multiple processes in multiple nodes with shared storage, the exported log files have the following hierarchy + +```text +# shared storage case +./tmp +├── tmp.log +├── tmp_rank1.log +├── tmp_rank2.log +├── tmp_rank3.log +├── tmp_rank4.log +├── tmp_rank5.log +├── tmp_rank6.log +└── tmp_rank7.log +... +└── tmp_rank63.log +``` + +In the case of multiple processes in multiple nodes without storage, logs are organized as follows + +```text +# without shared storage +# node 0: +work_dir/ +└── exp_name_logs + ├── exp_name.log + ├── exp_name_rank1.log + ├── exp_name_rank2.log + ├── exp_name_rank3.log + ... + └── exp_name_rank7.log + +# node 7: +work_dir/ +└── exp_name_logs + ├── exp_name_rank56.log + ├── exp_name_rank57.log + ├── exp_name_rank58.log + ... + └── exp_name_rank63.log +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/design/runner.md b/testbed/open-mmlab__mmengine/docs/en/design/runner.md new file mode 100644 index 0000000000000000000000000000000000000000..b5fb0be69b973dad6644c995ff2525bf93b25307 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/design/runner.md @@ -0,0 +1,181 @@ +# Runner + +Deep learning algorithms usually share similar pipelines for training, validation and testing. +Therefore, MMengine designed `Runner` to simplify the construction of these pipelines. +In most cases, users can use our default `Runner` directly. +If you find it not feasible to implement your ideas, you can also modify it or customize your own runner. + +Before introducing the design of `Runner`, let's walk through some examples to better understand why we should use runner. +Below is a few lines of pseudo codes for training models in PyTorch: + +```python +model = ResNet() +optimizer = SGD(model.parameters(), lr=0.01, momentum=0.9) +train_dataset = ImageNetDataset(...) +train_dataloader = DataLoader(train_dataset, ...) + +for i in range(max_epochs): + for data_batch in train_dataloader: + optimizer.zero_grad() + outputs = model(data_batch) + loss = loss_func(outputs, data_batch) + loss.backward() + optimizer.step() +``` + +Pseudo codes for model validation in PyTorch: + +```python +model = ResNet() +model.load_state_dict(torch.load(CKPT_PATH)) +model.eval() + +test_dataset = ImageNetDataset(...) +test_dataloader = DataLoader(test_dataset, ...) + +for data_batch in test_dataloader: + outputs = model(data_batch) + acc = calculate_acc(outputs, data_batch) +``` + +Pseudo codes for model inference in PyTorch: + +```python +model = ResNet() +model.load_state_dict(torch.load(CKPT_PATH)) +model.eval() + +for img in imgs: + prediction = model(img) +``` + +The observation from the above 3 pieces of codes is that they are similar. +They can all be divided into some distinct steps, such as model construction, data loading and loop iterations. +Although the above examples are based on image classification tasks, the same holds for many other tasks as well, including object detection, image segmentation, etc. +Based on the observation above, we propose runner, which structures the training, validation and testing pipeline. +With runner, the only thing you need to do is to prepare necessary components (models, data, etc.) of your pipeline, and leave the schedule and execution to `Runner`. +You are free of constructing similar pipelines one and another time. +You are free of annoying details like the differences between distributed and non-distributed training. +You can focus on your own awesome ideas. +These are all achieved by runner and various practical modules in MMEngine. + +![Runner](https://user-images.githubusercontent.com/12907710/184577204-3ea033bd-91dd-4da8-b4ac-22763d7d6c7d.png) + +The `Runner` in MMEngine contains various modules required for training, testing and validation, as well as loop controllers(`Loop`) and [Hook](../tutorials/hook.md), as shown in the figure above. +It provides 3 APIs for users: `train`, `val` and `test`, each correspond to a specific `Loop`. +You can use `Runner` either by providing a config file, or by providing manually constructed modules. +Once activated, the `Runner` will automatically setup the runtime environment, build/compose your modules, execute the loop iterations in `Loop` and call registered hooks during iterations. + +The execution order of `Runner` is as follows: + +![runner_flow](https://user-images.githubusercontent.com/12907710/184577118-b8f30521-0dba-4b94-a78f-8682459650a5.png) + +A feature of `Runner` is that it will always lazily initialize modules managed by itself. +To be specific, `Runner` won't build every module on initialization, and it won't build a module until it is needed in current `Loop`. +Therefore, if you are running only one of the `train`, `val`, or `test` pipelines, you only need to provide the relevant configs/modules. + +## Loop + +In MMEngine, we abstract the execution process of the task into `Loop`, based on the observation that most deep learning tasks can be summarized as a model iterating over datasets. +We provide 4 built-in loops in MMEngine: + +- EpochBasedTrainLoop +- IterBasedTrainLoop +- ValLoop +- TestLoop + +![Loop](https://user-images.githubusercontent.com/12907710/184577588-d74e16dd-15c7-4f73-9857-61c56c29057b.png) + +The built-in runner and loops are capable of most deep learning tasks, but surely not all. +Some tasks need extra modifications and refactorizations. +Therefore, we make it possible for users to customize their own pipelines for model training, validation and testing. + +You can write your own pipeline by subclassing [BaseLoop](mmengine.runner.BaseLoop), which needs 2 arguments for initialization: 1) `runner` the Runner instance, and 2) `dataloader` the dataloader used in this loop. +You are free to add more arguments to your own loop subclass. +After defining your own loop subclass, you should register it to LOOPS(mmengine.registry.LOOPS), and specify it in config files by `type` field in `train_cfg`, `val_cfg` and `test_cfg`. +In fact, you can write any execution order, any hook position in your own loop. +However, built-in hooks may not work if you change hook positions, which may lead to inconsistent behavior during training. +Therefore, we strongly recommend you to implement you subclass with similar execution order illustrated in the figure above, and with the same hook positions defined in [hook documentation](../tutorials/hook.md). + +```python +from mmengine.registry import LOOPS, HOOKS +from mmengine.runner import BaseLoop +from mmengine.hooks import Hook + + +# Customized validation loop +@LOOPS.register_module() +class CustomValLoop(BaseLoop): + def __init__(self, runner, dataloader, evaluator, dataloader2): + super().__init__(runner, dataloader, evaluator) + self.dataloader2 = runner.build_dataloader(dataloader2) + + def run(self): + self.runner.call_hooks('before_val_epoch') + for idx, data_batch in enumerate(self.dataloader): + self.runner.call_hooks( + 'before_val_iter', batch_idx=idx, data_batch=data_batch) + outputs = self.run_iter(idx, data_batch) + self.runner.call_hooks( + 'after_val_iter', batch_idx=idx, data_batch=data_batch, outputs=outputs) + metric = self.evaluator.evaluate() + + # add extra loop for validation purpose + for idx, data_batch in enumerate(self.dataloader2): + # add new hooks + self.runner.call_hooks( + 'before_valloader2_iter', batch_idx=idx, data_batch=data_batch) + self.run_iter(idx, data_batch) + # add new hooks + self.runner.call_hooks( + 'after_valloader2_iter', batch_idx=idx, data_batch=data_batch, outputs=outputs) + metric2 = self.evaluator.evaluate() + + ... + + self.runner.call_hooks('after_val_epoch') + + +# Define a hook with extra hook positions +@HOOKS.register_module() +class CustomValHook(Hook): + def before_valloader2_iter(self, batch_idx, data_batch): + ... + + def after_valloader2_iter(self, batch_idx, data_batch, outputs): + ... + +``` + +The example above shows how to implement a different validation loop. +The new loop validates on two different validation datasets. +It also defines a new hook position in the second validation. +You can easily use it by setting `type='CustomValLoop'` in `val_cfg` in your config file. + +```python +# Customized validation loop +val_cfg = dict(type='CustomValLoop', dataloader2=dict(dataset=dict(type='ValDataset2'), ...)) +# Customized hook with extra hook position +custom_hooks = [dict(type='CustomValHook')] +``` + +## Customize Runner + +Moreover, you can write your own runner by subclassing `Runner` if the built-in `Runner` is not feasible. +The method is similar to writing other modules: write your subclass inherited from `Runner`, overrides some functions, register it to [RUNNERS](mmengine.registry.RUNNERS) and access it by assigning `runner_type` in your config file. + +```python +from mmengine.registry import RUNNERS +from mmengine.runner import Runner + +@RUNNERS.register_module() +class CustomRunner(Runner): + + def setup_env(self): + ... +``` + +The example above shows how to implement a customized runner which overrides the `setup_env` function and is registered to RUNNERS. +Now `CustomRunner` is prepared to be used by setting `runner_type='CustomRunner'` in your config file. + +Further readings: [Runner tutorial](../tutorials/runner.md) and [Runner API documentations](mmengine.runner.Runner) diff --git a/testbed/open-mmlab__mmengine/docs/en/design/visualization.md b/testbed/open-mmlab__mmengine/docs/en/design/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..745f16f25ee4f72288e402df749c0f3f49b45b55 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/design/visualization.md @@ -0,0 +1,76 @@ +# Visualization + +## 1 Overall Design + +Visualization provides an intuitive explanation of the training and testing process of the deep learning model. In OpenMMLab, we expect the visualization module to meet the following requirements: + +- Provides rich out-of-the-box features that can meet most computer vision visualization tasks. +- Versatile, expandable, and can be customized easily +- Able to visualize at anywhere in the training and testing process. +- Unified APIs for all OpenMMLab libraries, which is convenient for users to understand and use. + +Based on the above requirements, we proposed the `Visualizer` and various `VisBackend` such as `LocalVisBackend`, `WandbVisBackend`, and `TensorboardVisBackend` in OpenMMLab 2.0. The visualizer could not only visualize the image data, but also things like configurations, scalars, and model structure. + +- For convenience, the APIs provided by the `Visualizer` implement the drawing and storage functions. As an internal property of `Visualizer`, `VisBackend` will be called by `Visualizer` to write data to different backends. +- Considering that you may want to write data to multiple backends after drawing, `Visualizer` can be configured with multiple backends. When the user calls the storage API of the `Visualizer`, it will traverse and call all the specified APIs of `VisBackend` internally. + +The UML diagram of the two is as follows. + +
+ +
+ +## 2 Visualizer + +The external interface of `Visualizer` can be divided into three categories. + +1. Drawing APIs + +- [draw_bboxes](mmengine.visualization.Visualizer.draw_bboxes) draws a single or multiple bounding boxes +- [draw_points](mmengine.visualization.Visualizer.draw_points) draws a single or multiple points +- [draw_texts](mmengine.visualization.Visualizer.draw_texts) draws a single or multiple text boxes +- [draw_lines](mmengine.visualization.Visualizer.lines) draws a single or multiple line segments +- [draw_circles](mmengine.visualization.Visualizer.draw_circles) draws a single or multiple circles +- [draw_polygons](mmengine.visualization.Visualizer.draw_polygons) draws a single or multiple polygons +- [draw_binary_masks](mmengine.visualization.Visualizer.draw_binary_mask) draws single or multiple binary masks +- [draw_featmap](mmengine.visualization.Visualizer.draw_featmap) draws feature map (**static method**) + +The above APIs can be called in a chain except for `draw_featmap` because the image size may change after this method is called. To avoid confusion, `draw_featmap` is a static method. + +2. Storage APIs + +- [add_config](mmengine.visualization.writer.BaseWriter.add_config) writes configuration to a specific storage backend +- [add_graph](mmengine.visualization.writer.BaseWriter.add_graph) writes model graph to a specific storage backend +- [add_image](mmengine.visualization.writer.BaseWriter.add_image) writes image to a specific storage backend +- [add_scalar](mmengine.visualization.writer.BaseWriter.add_scalar) writes scalar to a specific storage backend +- [add_scalars](mmengine.visualization.writer.BaseWriter.add_scalars) writes multiple scalars to a specific storage backend at once +- [add_datasample](mmengine.visualization.writer.BaseWriter.add_datasample) the abstract interface for each repositories to draw data sample + +Interfaces beginning with the `add` prefix represent storage APIs. \[datasample\] (`./data_element.md`)is the unified interface of each downstream repository in the OpenMMLab 2.0, and `add_datasample` can process the data sample directly . + +3. Other APIs + +- [set_image](mmengine.visualization.Visualizer.set_image) sets the original image data, the default input image format is RGB +- [get_image](mmengine.visualization.Visualizer.get_image) gets the image data in Numpy format after drawing, the default output format is RGB +- [show](mmengine.visualization.Visualizer.show) for visualization +- [get_backend](mmengine.visualization.Visualizer.get_backend) gets a specific storage backend by name +- [close](mmengine.visualization.Visualizer.close) closes all resources, including `VisBackend` + +For more details, you can refer to [Visualizer Tutorial](../tutorials/visualization.md). + +## 3 VisBackend + +After drawing, the drawn data can be stored in multiple visualization storage backends. To unify the interfaces, MMEngine provides an abstract class, `BaseVisBackend`, and some commonly used backends such as `LocalVisBackend`, `WandbVisBackend`, and `TensorboardVisBackend`. +The main interfaces and properties of `BaseVisBackend` are as follows: + +- [add_config](mmengine.visualization.vis_backend.BaseVisBackend.add_config) writes configuration to a specific storage backend +- [add_graph](mmengine.visualization.vis_backend.BaseVisBackend.add_graph) writes model graph to a specific backend +- [add_image](mmengine.visualization.vis_backend.BaseVisBackend.add_image) writes image to a specific backend +- [add_scalar](mmengine.visualization.vis_backend.BaseVisBackend.add_scalar) writes scalar to a specific backend +- [add_scalars](mmengine.visualization.vis_backend.BaseVisBackend.add_scalars) writes multiple scalars to a specific backend at once +- [close](mmengine.visualization.vis_backend.BaseVisBackend.close) closes the resource that has been opened +- [experiment](mmengine.visualization.vis_backend.BaseVisBackend.experiment) writes backend objects, such as WandB objects and Tensorboard objects + +`BaseVisBackend` defines five common data writing interfaces. Some writing backends are very powerful, such as WandB, which could write tables and videos. Users can directly obtain the `experiment` object for such needs and then call native APIs of the corresponding backend. `LocalVisBackend`, `WandbVisBackend`, and `TensorboardVisBackend` are all inherited from `BaseVisBackend` and implement corresponding storage functions according to their features. Users can also customize `BaseVisBackend` to extend the storage backends and implement custom storage requirements. + +For more details, you can refer to [Storage Backend Tutorial](../advanced_tutorials//visualization.md). diff --git a/testbed/open-mmlab__mmengine/docs/en/examples/resume_training.md b/testbed/open-mmlab__mmengine/docs/en/examples/resume_training.md new file mode 100644 index 0000000000000000000000000000000000000000..3bd4195a9627800829dab82d7eed8f9c65d85679 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/examples/resume_training.md @@ -0,0 +1,36 @@ +# Resume Training + +Resuming training means continuing training from the state saved from some previous training, where the state includes the model's weights, the state of the optimizer and the state of parameter scheduler. + +## Automatically resume training + +Users can set the `resume` parameter of [Runner](mmengine.runner.Runner) to enable automatic training resumption. When `resume` is set to `True`, the Runner will try to resume from the latest checkpoint in `work_dir` automatically. If there is a latest checkpoint in `work_dir` (e.g. the training was interrupted during the last training), the training will be resumed from that checkpoint, otherwise (e.g. the last training did not have time to save the checkpoint or a new training task is started) the training will restart. Here is an example of how to enable automatic training resumption. + +```python +runner = Runner( + model=ResNet18(), + work_dir='./work_dir', + train_dataloader=train_dataloader_cfg, + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)), + train_cfg=dict(by_epoch=True, max_epochs=3), + resume=True, +) +runner.train() +``` + +## Specify the checkpoint path + +If you want to specify the path to resume training, you need to set `load_from` in addition to `resume=True`. Note that if only `load_from` is set without `resume=True`, then only the weights in the checkpoint will be loaded and training will be restarted, instead of continuing with the previous state. + +```python +runner = Runner( + model=ResNet18(), + work_dir='./work_dir', + train_dataloader=train_dataloader_cfg, + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)), + train_cfg=dict(by_epoch=True, max_epochs=3), + load_from='./work_dir/epoch_2.pth', + resume=True, +) +runner.train() +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/examples/save_gpu_memory.md b/testbed/open-mmlab__mmengine/docs/en/examples/save_gpu_memory.md new file mode 100644 index 0000000000000000000000000000000000000000..160f2d2409cb5d036a88fabf2cb3d41c8b88499d --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/examples/save_gpu_memory.md @@ -0,0 +1,112 @@ +# Save Memory on GPU + +Memory capacity is critical in deep learning training and inference and determines whether the model can run successfully. Common memory saving approaches include: + +- Gradient Accumulation + + Gradient accumulation is the mechanism that runs at a configured number of steps accumulating the gradients instead of updating parameters, after which the network parameters are updated and the gradients are cleared. With this technique of delayed parameter update, the result is similar to those scenarios using a large batch size, while the memory of activation can be saved. However, it should be noted that if the model contains a batch normalization layer, using gradient accumulation will impact performance. + +- Gradient Checkpointing + + Gradient checkpointing is a time-for-space method that compresses the model by reducing the number of saved activations, however, the unstored activations must be recomputed when calculating the gradient. The corresponding functionality has been implemented in the `torch.utils.checkpoint` package. The implementation can be briefly concluded as that, in the forward phase, the forward function passed to the checkpoint runs in `torch.no_grad` mode and saves only the input and the output of the forward function. Then recalculates its intermediate activations in the backward phase. + +- Large Model Training Techniques + + Recent research has shown that training a large model would be helpful to improve performance, but training a model at such a scale requires huge resources, and it is hard to store the entire model in the memory of a single graphics card. Therefore large model training techniques, typically such as [DeepSpeed ZeRO](https://www.deepspeed.ai/tutorials/zero/#zero-overview) and the Fully Shared Data Parallel ([FSDP](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/)) technique introduced in FairScale are introduced. These techniques allow slicing the parameters, gradients, and optimizer states among the parallel processes, while still maintaining the simplicity of the data parallelism. + +MMEngine now supports gradient accumulation and large model training FSDP techniques, and the usages are described as follows. + +## Gradient Accumulation + +The configuration can be written in this way: + +```python +optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.001, momentum=0.9), + # update every four times + accumulative_counts=4) +``` + +The full example working with `Runner` is as follows. + +```python +import torch +import torch.nn as nn +from torch.utils.data import DataLoader +from mmengine.runner import Runner +from mmengine.model import BaseModel + +train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50 +train_dataloader = DataLoader(train_dataset, batch_size=2) + + +class ToyModel(BaseModel): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + return dict(loss1=loss1, loss2=loss2) + + +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01), + accumulative_counts=4) +) +runner.train() +``` + +## Large Model Training + +`FSDP` is officially supported from PyTorch 1.11. The config can be written in this way: + +```python +# located in cfg file +model_wrapper_cfg=dict(type='MMFullyShardedDataParallel', cpu_offload=True) +``` + +The full example working with `Runner` is as follows. + +```python +import torch +import torch.nn as nn +from torch.utils.data import DataLoader +from mmengine.runner import Runner +from mmengine.model import BaseModel + +train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50 +train_dataloader = DataLoader(train_dataset, batch_size=2) + + +class ToyModel(BaseModel): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + return dict(loss1=loss1, loss2=loss2) + + +runner = Runner( + model=ToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=1), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)), + cfg=dict(model_wrapper_cfg=dict(type='MMFullyShardedDataParallel', cpu_offload=True)) +) +runner.train() +``` + +Please be noted that `FSDP` works only in distributed training environments. diff --git a/testbed/open-mmlab__mmengine/docs/en/examples/speed_up_training.md b/testbed/open-mmlab__mmengine/docs/en/examples/speed_up_training.md new file mode 100644 index 0000000000000000000000000000000000000000..9350cbf4fc659606d1d0aca7b2d541f8dac56078 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/examples/speed_up_training.md @@ -0,0 +1,78 @@ +# Speed up Training + +## Distributed Training + +MMEngine supports training models with CPU, single GPU, multiple GPUs in single machine and multiple machines. When multiple GPUs are available in the environment, we can use the following command to enable multiple GPUs in single machine or multiple machines to shorten the training time of the model. + +- multiple GPUs in single machine + + Assuming the current machine has 8 GPUs, you can enable multiple GPUs training with the following command: + + ```bash + python -m torch.distributed.launch --nproc_per_node=8 examples/train.py --launcher pytorch + ``` + + If you need to specify the GPU index, you can set the `CUDA_VISIBLE_DEVICES` environment variable, e.g. use the 0th and 3rd GPU. + + ```bash + CUDA_VISIBLE_DEVICES=0,3 python -m torch.distributed.launch --nproc_per_node=2 examples/train.py --launcher pytorch + ``` + +- multiple machines + + Assume that there are 2 machines connected with ethernet, you can simply run following commands. + + On the first machine: + + ```bash + python -m torch.distributed.launch \ + --nnodes 8 \ + --node_rank 0 \ + --master_addr 127.0.0.1 \ + --master_port 29500 \ + --nproc_per_node=8 \ + examples/train.py --launcher pytorch + ``` + + On the second machine: + + ```bash + python -m torch.distributed.launch \ + --nnodes 8 \ + --node_rank 1 \ + --master_addr 127.0.0.1 \ + --master_port 29500 \ + --nproc_per_node=8 \ + ``` + + If you are running MMEngine in a slurm cluster, simply run the following command to enable training for 2 machines and 16 GPUs. + + ```bash + srun -p mm_dev \ + --job-name=test \ + --gres=gpu:8 \ + --ntasks=16 \ + --ntasks-per-node=8 \ + --cpus-per-task=5 \ + --kill-on-bad-exit=1 \ + python examples/train.py --launcher="slurm" + ``` + +## Mixed Precision Training + +Nvidia introduced the Tensor Core unit into the Volta and Turing architectures to support FP32 and FP16 mixed precision computing. With automatic mixed precision training enabled, some operators operate at FP16 and the rest operate at FP32, which reduces training time and storage requirements without changing the model or degrading its training precision, thus supporting training with larger batch sizes, larger models, and larger input sizes. + +[PyTorch officially supports amp from 1.6](https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/). If you are interested in the implementation of automatic mixing precision, you can refer to [Mixed Precision Training](https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html). + +MMEngine provides the wrapper [AmpOptimWrapper](mmengine.optim.AmpOptimWrapper) for auto-mixing precision training, just set `type='AmpOptimWrapper'` in ` optim_wrapper` to enable auto-mixing precision training, no other code changes are needed. + +```python +runner = Runner( + model=ResNet18(), + work_dir='./work_dir', + train_dataloader=train_dataloader_cfg, + optim_wrapper=dict(type='AmpOptimWrapper', optimizer=dict(type='SGD', lr=0.001, momentum=0.9)), + train_cfg=dict(by_epoch=True, max_epochs=3), +) +runner.train() +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/examples/train_a_gan.md b/testbed/open-mmlab__mmengine/docs/en/examples/train_a_gan.md new file mode 100644 index 0000000000000000000000000000000000000000..e00b183a17c01d1005e6ecce92bbe44eda675623 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/examples/train_a_gan.md @@ -0,0 +1,3 @@ +# Train a GAN + +Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/examples/train_a_gan.html). diff --git a/testbed/open-mmlab__mmengine/docs/en/get_started/15_minutes.md b/testbed/open-mmlab__mmengine/docs/en/get_started/15_minutes.md new file mode 100644 index 0000000000000000000000000000000000000000..48f0b8bcf989c9356d20917f3921684e91883d3f --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/get_started/15_minutes.md @@ -0,0 +1,245 @@ +# 15 minutes to get started with MMEngine + +In this tutorial, we'll take training a ResNet-50 model on CIFAR-10 dataset as an example. We will build a complete and configurable pipeline for both training and validation in only 80 lines of code with `MMEgnine`. +The whole process includes the following steps: + +1. [Build a Model](#build-a-model) +2. [Build a Dataset and DataLoader](#build-a-dataset-and-dataloader) +3. [Build a Evaluation Metrics](#build-a-evaluation-metrics) +4. [Build a Runner and Run the Task](#build-a-runner-and-run-the-task) + +## Build a Model + +First, we need to build a **model**. In MMEngine, the model should inherit from `BaseModel`. Aside from parameters representing inputs from the dataset, its `forward` method needs to accept an extra argument called `mode`: + +- for training, the value of `mode` is "loss," and the `forward` method should return a `dict` containing the key "loss". +- for validation, the value of `mode` is "predict", and the forward method should return results containing both predictions and labels. + +```python +import torch.nn.functional as F +import torchvision +from mmengine.model import BaseModel + + +class MMResNet50(BaseModel): + def __init__(self): + super().__init__() + self.resnet = torchvision.models.resnet50() + + def forward(self, imgs, labels, mode): + x = self.resnet(imgs) + if mode == 'loss': + return {'loss': F.cross_entropy(x, labels)} + elif mode == 'predict': + return x, labels +``` + +## Build a Dataset and DataLoader + +Next, we need to create **Dataset** and **DataLoader** for training and validation. +For basic training and validation, we can simply use built-in datasets supported in TorchVision. + +```python +import torchvision.transforms as transforms +from torch.utils.data import DataLoader + +norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201]) +train_dataloader = DataLoader(batch_size=32, + shuffle=True, + dataset=torchvision.datasets.CIFAR10( + 'data/cifar10', + train=True, + download=True, + transform=transforms.Compose([ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize(**norm_cfg) + ]))) + +val_dataloader = DataLoader(batch_size=32, + shuffle=False, + dataset=torchvision.datasets.CIFAR10( + 'data/cifar10', + train=False, + download=True, + transform=transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(**norm_cfg) + ]))) +``` + +## Build a Evaluation Metrics + +To validate and test the model, we need to define a **Metric** called accuracy to evaluate the model. This metric needs inherit from `BaseMetric` and implements the `process` and `compute_metrics` methods where the `process` method accepts the output of the dataset and other outputs when `mode="predict"`. The output data at this scenario is a batch of data. After processing this batch of data, we save the information to `self.results` property. +`compute_metrics` accepts a `results` parameter. The input `results` of `compute_metrics` is all the information saved in `process` (In the case of a distributed environment, `results` are the information collected from all `process` in all the processes). Use these information to calculate and return a `dict` that holds the results of the evaluation metrics + +```python +from mmengine.evaluator import BaseMetric + +class Accuracy(BaseMetric): + def process(self, data_batch, data_samples): + score, gt = data_samples + # save the middle result of a batch to `self.results` + self.results.append({ + 'batch_size': len(gt), + 'correct': (score.argmax(dim=1) == gt).sum().cpu(), + }) + + def compute_metrics(self, results): + total_correct = sum(item['correct'] for item in results) + total_size = sum(item['batch_size'] for item in results) + # return the dict containing the eval results + # the key is the name of the metric name + return dict(accuracy=100 * total_correct / total_size) +``` + +## Build a Runner and Run the Task + +Now we can build a **Runner** with previously defined `Model`, `DataLoader`, and `Metrics`, and some other configs shown as follows: + +```python +from torch.optim import SGD +from mmengine.runner import Runner + +runner = Runner( + # the model used for training and validation. + # Needs to meet specific interface requirements + model=MMResNet50(), + # working directory which saves training logs and weight files + work_dir='./work_dir', + # train dataloader needs to meet the PyTorch data loader protocol + train_dataloader=train_dataloader, + # optimize wrapper for optimization with additional features like + # AMP, gradtient accumulation, etc + optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)), + # trainging coinfs for specifying training epoches, verification intervals, etc + train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1), + # validation dataloaer also needs to meet the PyTorch data loader protocol + val_dataloader=val_dataloader, + # validation configs for specifying additional parameters required for validation + val_cfg=dict(), + # validation evaluator. The default one is used here + val_evaluator=dict(type=Accuracy), +) + +runner.train() +``` + +Finally, let's put all the codes above together into a complete script that uses the `MMEngine` executor for training and validation: + +Open in Colab + +```python +import torch.nn.functional as F +import torchvision +import torchvision.transforms as transforms +from torch.optim import SGD +from torch.utils.data import DataLoader + +from mmengine.evaluator import BaseMetric +from mmengine.model import BaseModel +from mmengine.runner import Runner + + +class MMResNet50(BaseModel): + def __init__(self): + super().__init__() + self.resnet = torchvision.models.resnet50() + + def forward(self, imgs, labels, mode): + x = self.resnet(imgs) + if mode == 'loss': + return {'loss': F.cross_entropy(x, labels)} + elif mode == 'predict': + return x, labels + + +class Accuracy(BaseMetric): + def process(self, data_batch, data_samples): + score, gt = data_samples + self.results.append({ + 'batch_size': len(gt), + 'correct': (score.argmax(dim=1) == gt).sum().cpu(), + }) + + def compute_metrics(self, results): + total_correct = sum(item['correct'] for item in results) + total_size = sum(item['batch_size'] for item in results) + return dict(accuracy=100 * total_correct / total_size) + + +norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201]) +train_dataloader = DataLoader(batch_size=32, + shuffle=True, + dataset=torchvision.datasets.CIFAR10( + 'data/cifar10', + train=True, + download=True, + transform=transforms.Compose([ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize(**norm_cfg) + ]))) + +val_dataloader = DataLoader(batch_size=32, + shuffle=False, + dataset=torchvision.datasets.CIFAR10( + 'data/cifar10', + train=False, + download=True, + transform=transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(**norm_cfg) + ]))) + +runner = Runner( + model=MMResNet50(), + work_dir='./work_dir', + train_dataloader=train_dataloader, + optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)), + train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1), + val_dataloader=val_dataloader, + val_cfg=dict(), + val_evaluator=dict(type=Accuracy), +) +runner.train() +``` + +Training log would be similar to this: + +``` +2022/08/22 15:51:53 - mmengine - INFO - +------------------------------------------------------------ +System environment: + sys.platform: linux + Python: 3.8.12 (default, Oct 12 2021, 13:49:34) [GCC 7.5.0] + CUDA available: True + numpy_random_seed: 1513128759 + GPU 0: NVIDIA GeForce GTX 1660 SUPER + CUDA_HOME: /usr/local/cuda +... + +2022/08/22 15:51:54 - mmengine - INFO - Checkpoints will be saved to /home/mazerun/work_dir by HardDiskBackend. +2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][10/1563] lr: 1.0000e-03 eta: 0:18:23 time: 0.1414 data_time: 0.0077 memory: 392 loss: 5.3465 +2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][20/1563] lr: 1.0000e-03 eta: 0:11:29 time: 0.0354 data_time: 0.0077 memory: 392 loss: 2.7734 +2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][30/1563] lr: 1.0000e-03 eta: 0:09:10 time: 0.0352 data_time: 0.0076 memory: 392 loss: 2.7789 +2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][40/1563] lr: 1.0000e-03 eta: 0:08:00 time: 0.0353 data_time: 0.0073 memory: 392 loss: 2.5725 +2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][50/1563] lr: 1.0000e-03 eta: 0:07:17 time: 0.0347 data_time: 0.0073 memory: 392 loss: 2.7382 +2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][60/1563] lr: 1.0000e-03 eta: 0:06:49 time: 0.0347 data_time: 0.0072 memory: 392 loss: 2.5956 +2022/08/22 15:51:58 - mmengine - INFO - Epoch(train) [1][70/1563] lr: 1.0000e-03 eta: 0:06:28 time: 0.0348 data_time: 0.0072 memory: 392 loss: 2.7351 +... +2022/08/22 15:52:50 - mmengine - INFO - Saving checkpoint at 1 epochs +2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][10/313] eta: 0:00:03 time: 0.0122 data_time: 0.0047 memory: 392 +2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][20/313] eta: 0:00:03 time: 0.0122 data_time: 0.0047 memory: 308 +2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][30/313] eta: 0:00:03 time: 0.0123 data_time: 0.0047 memory: 308 +... +2022/08/22 15:52:54 - mmengine - INFO - Epoch(val) [1][313/313] accuracy: 35.7000 +``` + +The corresponding implementation of PyTorch and MMEngine: + +![output](https://user-images.githubusercontent.com/57566630/203142869-cfe5f855-f391-4fd4-a80c-beecf1bd111f.gif) + +In addition to these basic components, you can also use **executor** to easily combine and configure various training techniques, such as enabling mixed-precision training and gradient accumulation (see [OptimWrapper](../tutorials/optim_wrapper.md)), configuring the learning rate decay curve (see [Metrics & Evaluator](../tutorials/evaluation.md)), and etc. diff --git a/testbed/open-mmlab__mmengine/docs/en/get_started/introduction.md b/testbed/open-mmlab__mmengine/docs/en/get_started/introduction.md new file mode 100644 index 0000000000000000000000000000000000000000..b90cc15460efd785c6e4acb3465899d4519320f6 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/get_started/introduction.md @@ -0,0 +1,3 @@ +## Introduction + +Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/get_started/installation.html). diff --git a/testbed/open-mmlab__mmengine/docs/en/migration/model.md b/testbed/open-mmlab__mmengine/docs/en/migration/model.md new file mode 100644 index 0000000000000000000000000000000000000000..0509f4930d4b84e31b57462f9dfd204c3d85afc8 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/migration/model.md @@ -0,0 +1,443 @@ +# Migrate Model from MMCV to MMEngine + +## Introduction + +The early computer vision tasks supported by MMCV, such as detection and classification, used a general process to optimize model. It can be summarized as the following four steps: + +1. Calculate the loss +2. Calculate the gradients +3. Update the model parameters +4. Clean the gradients of the last iteration + +For most of the high-level tasks, "where" and "when" to perform the above processes is commonly fixed, therefore it seems reasonable to use [Hook](../design/hook.md) to implement it. MMCV implements series of hooks, such as `OptimizerHook`, `Fp16OptimizerHook` and `GradientCumulativeFp16OptimizerHook` to provide varies of optimization strategies. + +On the other hand, tasks like GAN (Generative adversarial network) and Self-supervision require more flexible training processes, which do not meet the characteristics mentioned above, and it could be hard to use hooks to implement them. To meet the needs of these tasks, MMCV will pass `optimizer` to `train_step` and users can customize the optimization process as they want. Although it works, it cannot utilize various `OptimizerHook` implemented in MMCV, and downstream repositories have to implement mix-precision training, and gradient accumulation on their own. + +To unify the training process of various deep learning tasks, MMEngine designed the [OptimWrapper](mmengine.optim.OptimWrapper), which integrates the mixed-precision training, gradient accumulation and other optimization strategies into a unified interface. + +## Migrate optimization process + +Since MMEngine designs the `OptimWrapper` and deprecates series of `OptimizerHook`, there would be some differences between the optimization process in MMCV and MMEngine. + +### Commonly used optimization process + +Considering tasks like detection and classification, the optimization process is usually the same, so `BaseModel` integrates the process into `train_step`. + +**Model based on MMCV** + +Before describing how to migrate the model, let's look at a minimal example to train a model based on the MMCV. + +```python +import torch +import torch.nn as nn +from torch.optim import SGD +from torch.utils.data import DataLoader + +from mmcv.runner import Runner +from mmcv.utils.logging import get_logger + + +train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50 +train_dataloader = DataLoader(train_dataset, batch_size=2) + + +class MMCVToyModel(nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, return_loss=False): + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + loss = (loss1 + loss2).sum() + return dict(loss=loss, + num_samples=len(img), + log_vars=dict( + loss1=loss1.sum().item(), + loss2=loss2.sum().item())) + + def train_step(self, data, optimizer=None): + return self(*data, return_loss=True) + + def val_step(self, data, optimizer=None): + return self(*data, return_loss=False) + + +model = MMCVToyModel() +optimizer = SGD(model.parameters(), lr=0.01) +logger = get_logger('demo') + +lr_config = dict(policy='step', step=[2, 3]) +optimizer_config = dict(grad_clip=None) +log_config = dict(interval=10, hooks=[dict(type='TextLoggerHook')]) + + +runner = Runner( + model=model, + work_dir='tmp_dir', + optimizer=optimizer, + logger=logger, + max_epochs=5) + +runner.register_training_hooks( + lr_config=lr_config, + optimizer_config=optimizer_config, + log_config=log_config) +runner.run([train_dataloader], [('train', 1)]) +``` + +Model based on MMCV must implement `train_step`, and return a `dict` which contains the following keys: + +- `loss`: Passed to `OptimizerHook` to calculate gradient. +- num_samples: Passed to `LogBuffer` to count the averaged loss +- log_vars: Passed to `LogBuffer` to count the averaged loss + +**Model based on MMEngine** + +The same model based on MMEngine + +```python +import torch +import torch.nn as nn +from torch.utils.data import DataLoader + +from mmengine.runner import Runner +from mmengine.model import BaseModel + +train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50 +train_dataloader = DataLoader(train_dataset, batch_size=2) + + +class MMEngineToyModel(BaseModel): + + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + feat = self.linear(img) + # Called by train_step and return the loss dict + if mode == 'loss': + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + return dict(loss1=loss1, loss2=loss2) + # Called by val_step and return the predictions + elif mode == 'predict': + return [_feat for _feat in feat] + # tensor model, find more details in tutorials/model.md + else: + pass + + +runner = Runner( + model=MMEngineToyModel(), + work_dir='tmp_dir', + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=5), + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01))) +runner.train() +``` + +In MMEngine, users can customize their model based on `BaseModel`, which implements the same logic as `OptimizerHook` in `train_step`. For high-level tasks, `train_step` will be called in [train loop](mmengine.runner.loop) with specific arguments, and users do not need to care about the optimization process. For low-level tasks, users can override the `train_step` to customize the optimization process. + + + + + + + + + + + + + +
Model in MMCVModel in MMEngine
+ +```python +class MMCVToyModel(nn.Module): + + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, return_loss=False): + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + loss = (loss1 + loss2).sum() + return dict(loss=loss, + num_samples=len(img), + log_vars=dict( + loss1=loss1.sum().item(), + loss2=loss2.sum().item())) + + def train_step(self, data, optimizer=None): + return self(*data, return_loss=True) + + def val_step(self, data, optimizer=None): + return self(*data, return_loss=False) +``` + +
+
+ +```python +class MMEngineToyModel(BaseModel): + + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(1, 1) + + def forward(self, img, label, mode): + if mode == 'loss': + feat = self.linear(img) + loss1 = (feat - label).pow(2) + loss2 = (feat - label).abs() + return dict(loss1=loss1, loss2=loss2) + elif mode == 'predict': + return [_feat for _feat in feat] + else: + pass + + # The equivalent code snippet of `train_step` + # def train_step(self, data, optim_wrapper): + # data = self.data_preprocessor(data) + # loss_dict = self(*data, mode='loss') + # loss_dict['loss1'] = loss_dict['loss1'].sum() + # loss_dict['loss2'] = loss_dict['loss2'].sum() + # loss = (loss_dict['loss1'] + loss_dict['loss2']).sum() + # Call the optimizer wrapper to update parameters. + # optim_wrapper.update_params(loss) + # return loss_dict +``` + +
+ +```{note} +See more information about `data_preprocessor` and `optim_wrapper` in docs [optim_wrapper](../tutorials/optim_wrapper.md) and [data_preprocessor](../tutorials/model.md). +``` + +The main differences of model in MMCV and MMEngine can be summarized as follows: + +- `MMCVToyModel` inherits from `nn.Module`, and `MMEngineToyModel` inherits from `BaseModel` + +- `MMCVToyModel` must implement `train_step` method and return a `dict` with keys `loss`, `log_vars`, and `num_samples`. `MMEngineToyModel` only needs to implement `forward` method for high level tasks, and return a `dict` with differentiable losses. + +- `MMCVToyModel.forward` and `MMEngineToyModel.forward` must match with `train_step` which will call it. Since `MMEngineToyModel` does not override the `train_step`, `BaseModel.train_step` will be directly called, which requires that forward must accept `mode` parameter. Find more details in [tutorials of model](../tutorials/model.md) + +### Custom optimization process + +Takes training a GAN model as an example, generator and discriminator need to be optimized in turn and the optimization strategy could change as the training iteration grows. Therefore it could be hard to use `OptimizerHook` to meet such requirements in MMCV. GAN model based on MMCV will accept an optimizer in `train_step` and update parameters in it. Actually, MMEngine borrows this way and simplifies it by passing an [optim_wrapper](../tutorials/optim_wrapper.md) rather than an optimizer. + +Referred to [training a GAN model](../examples/train_a_gan.md), The differences of MMCV and MMEngine are as follows: + + + + + + + + + + + + + + +
Training gan in MMCVTraining gan in MMEngine
+ +```python + def train_discriminator(self, inputs, optimizer): + real_imgs = inputs['inputs'] + z = torch.randn( + (real_imgs.shape[0], self.noise_size)).type_as(real_imgs) + with torch.no_grad(): + fake_imgs = self.generator(z) + + disc_pred_fake = self.discriminator(fake_imgs) + disc_pred_real = self.discriminator(real_imgs) + + parsed_losses, log_vars = self.disc_loss(disc_pred_fake, + disc_pred_real) + parsed_losses.backward() + optimizer.step() + optimizer.zero_grad() + return log_vars + + def train_generator(self, inputs, optimizer): + real_imgs = inputs['inputs'] + z = torch.randn(inputs['inputs'].shape[0], self.noise_size).type_as( + real_imgs) + + fake_imgs = self.generator(z) + + disc_pred_fake = self.discriminator(fake_imgs) + parsed_loss, log_vars = self.gen_loss(disc_pred_fake) + + parsed_losses.backward() + optimizer.step() + optimizer.zero_grad() + return log_vars +``` + +
+ +```python + def train_discriminator(self, inputs, optimizer_wrapper): + real_imgs = inputs['inputs'] + z = torch.randn( + (real_imgs.shape[0], self.noise_size)).type_as(real_imgs) + with torch.no_grad(): + fake_imgs = self.generator(z) + + disc_pred_fake = self.discriminator(fake_imgs) + disc_pred_real = self.discriminator(real_imgs) + + parsed_losses, log_vars = self.disc_loss(disc_pred_fake, + disc_pred_real) + optimizer_wrapper.update_params(parsed_losses) + return log_vars + + + + def train_generator(self, inputs, optimizer_wrapper): + real_imgs = inputs['inputs'] + z = torch.randn(real_imgs.shape[0], self.noise_size).type_as(real_imgs) + + fake_imgs = self.generator(z) + + disc_pred_fake = self.discriminator(fake_imgs) + parsed_loss, log_vars = self.gen_loss(disc_pred_fake) + + optimizer_wrapper.update_params(parsed_loss) + return log_vars +``` + +
+ +Apart from the differences mentioned in the previous section, the main difference in the optimization process in MMCV and MMEngine is that the latter can use `optim_wrapper` in a more simple way. The convenience of `optim_wrapper` would be more obvious if gradient accumulation and mix-precision training are applied. + +## Migrate validation/testing process + +Model based on MMCV usually does not need to provide `test_step` or `val_step` for testing/validation. However, MMEngine performs the testing/validation by [ValLoop](mmengine.runner.ValLoop) and [TestLoop](mmengine.runner.TestLoop), which will call `runner.model.val_step` and `runner.model.test_step`. Therefore model based on MMEngine needs to implement `val_step` and `test_step`, of which input data and output predictions should be compatible with DataLoader and [Evaluator.process](mmengine.evaluator.Evaluator.process) respectively. You can find more details in the [model tutorial](../tutorials/model.md). Therefore, `MMEngineToyModel.forward` will slice the feat and return the predictions as a list. + +```python + +class MMEngineToyModel(BaseModel): + + ... + def forward(self, img, label, mode): + if mode == 'loss': + ... + elif mode == 'predict': + # Slice the data to a list + return [_feat for _feat in feat] + else: + ... +``` + +## Migrate the distributed training + +MMCV will wrap the model with distributed wrapper before building the runner, while MMEngine will wrap the model in Runner. Therefore, we need to configure the `launcher` and `model_wrapper_cfg` for Runner. [Migrate Runner from MMCV to MMEngine](./runner.md) will introduce it in detail. + +1. **Commonly used training process** + + For the high-level tasks mentioned in [introduction](#introduction), the default [distributed model wrapper](mmengine.model.MMDistributedDataParallel) is enough. Therefore, we only need to configure the `launcher` for MMEngine Runner. + + + + + + + + + + + + +
Distributed training in MMCV Distributed training in MMEngine
+ + ```python + model = MMDistributedDataParallel( + model, + device_ids=[int(os.environ['LOCAL_RANK'])], + broadcast_buffers=False, + find_unused_parameters=find_unused_parameters) + ... + runner = Runner(model=model, ...) + ``` + +
+
+ + ```python + runner = Runner( + model=model, + launcher='pytorch', # enable distributed training + ..., + ) + ``` + +
+
+ +  + +2. **optimize modules independently with custom optimization process** + + Again, taking the example of training a GAN model, the generator and discriminator need to be optimized separately. Therefore, the model needs to be wrapped by `MMSeparateDistributedDataParallel`, which need to be specified when building the runner. + + ```python + cfg = dict(model_wrapper_cfg='MMSeparateDistributedDataParallel') + runner = Runner( + model=model, + ..., # 其他配置 + launcher='pytorch', + cfg=cfg) + ``` + +  + +3. **Optimize a model with a custom optimization process** + +Sometimes we need to optimize the whole model with a custom optimization process, where we cannot reuse `BaseModel.train_step`, but need to override it, e.g. we want to optimize the model twice with the same batch of images: the first time with batch data augmentation on, and the second time with it off + +```python +class CustomModel(BaseModel): + + def train_step(self, data, optim_wrapper): + data = self.data_preprocessor(data, training=True) # Enable batch augmentation + loss = self(data, mode='loss') + optim_wrapper.update_params(loss) + data = self.data_preprocessor(data, training=False) # Disable batch augmentation + loss = self(data, mode='loss') + optim_wrapper.update_params(loss) +``` + +In this case, we need to customize a model wrapper that overrides the `train_step` and performs the same process as `CustomModel.train_step`. + +```python + class CustomDistributedDataParallel(MMSeparateDistributedDataParallel): + + def train_step(self, data, optim_wrapper): + data = self.data_preprocessor(data, training=True) # Enable batch augmentation + loss = self(data, mode='loss') + optim_wrapper.update_params(loss) + data = self.data_preprocessor(data, training=False) # Disable batch augmentation + loss = self(data, mode='loss') + optim_wrapper.update_params(loss) +``` + +Then we can specify it when building Runner: + +```python +cfg = dict(model_wrapper_cfg=dict(type='CustomDistributedDataParallel')) +runner = Runner( + model=model, + ..., + launcher='pytorch', + cfg=cfg +) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/migration/param_scheduler.md b/testbed/open-mmlab__mmengine/docs/en/migration/param_scheduler.md new file mode 100644 index 0000000000000000000000000000000000000000..1b3051af33e0fdd8d1e281c803bbca3f2f2bfca0 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/migration/param_scheduler.md @@ -0,0 +1,567 @@ +# Migrate parameter scheduler from MMCV to MMEngine + +MMCV 1.x version uses [LrUpdaterHook](https://mmcv.readthedocs.io/en/v1.6.0/api.html#mmcv.runner.LrUpdaterHook) and [MomentumUpdaterHook](https://mmcv.readthedocs.io/en/v1.6.0/api.html#mmcv.runner.MomentumUpdaterHook) to adjust the learning rate and momentum. +However, the design of LrUpdaterHook has been difficult to meet more abundant customization requirements due to the development of the training strategies. Hence, MMEngine proposes parameter schedulers (ParamScheduler). + +The interface of the parameter scheduler is consistent with PyTroch's learning rate scheduler (LRScheduler). In addition, the parameter scheduler provides stronger functions. For details, please refer to [Parameter Scheduler User Guide](../tutorials/param_scheduler.md). + +## Learning rate scheduler (LrUpdater) migration + +MMEngine uses LRScheduler instead of LrUpdaterHook. The field in the config file is changed from the original `lr_config` to `param_scheduler`. +The learning rate config in MMCV corresponds to the parameter scheduler config in MMEngine as follows: + +### Learning rate warm-up migration + +The learning rate warm-up can be achieved through the combination of schedulers by specifying the effective range `begin` and `end`. There are 3 learning rate warm-up methods in MMCV, namely `'constant'`, `'linear'`, `'exp'`. The corresponding config in MMEngine should be modified as follows: + +#### Constant warm-up + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + warmup='constant', + warmup_ratio=0.1, + warmup_iters=500, + warmup_by_epoch=False +) +``` + + + +```python +param_scheduler = [ + dict(type='ConstantLR', + factor=0.1, + begin=0, + end=500, + by_epoch=False), + dict(...) # the main learning rate scheduler +] +``` + +
+ +#### Linear warm-up + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + warmup='linear', + warmup_ratio=0.1, + warmup_iters=500, + warmup_by_epoch=False +) +``` + + + +```python +param_scheduler = [ + dict(type='LinearLR', + start_factor=0.1, + begin=0, + end=500, + by_epoch=False), + dict(...) # the main learning rate scheduler +] +``` + +
+ +#### Exponential warm-up + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + warmup='exp', + warmup_ratio=0.1, + warmup_iters=500, + warmup_by_epoch=False +) +``` + + + +```python +param_scheduler = [ + dict(type='ExponentialLR', + gamma=0.1, + begin=0, + end=500, + by_epoch=False), + dict(...) # the main learning rate scheduler +] +``` + +
+ +### Fixed learning rate (FixedLrUpdaterHook) migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict(policy='fixed') +``` + + + +```python +param_scheduler = [ + dict(type='ConstantLR', factor=1) +] +``` + +
+ +### Step learning rate (StepLrUpdaterHook) migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='step', + step=[8, 11], + gamma=0.1, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='MultiStepLR', + milestone=[8, 11], + gamma=0.1, + by_epoch=True) +] +``` + +
+ +### Poly learning rate (PolyLrUpdaterHook) migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='poly', + power=0.7, + min_lr=0.001, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='PolyLR', + power=0.7, + eta_min=0.001, + begin=0, + end=num_epochs, + by_epoch=True) +] +``` + +
+ +### Exponential learning rate (ExpLrUpdaterHook) migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='exp', + power=0.5, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='ExponentialLR', + gamma=0.5, + begin=0, + end=num_epochs, + by_epoch=True) +] +``` + +
+ +### Cosine annealing learning rate (CosineAnnealingLrUpdaterHook) migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='CosineAnnealing', + min_lr=0.5, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='CosineAnnealingLR', + eta_min=0.5, + T_max=num_epochs, + begin=0, + end=num_epochs, + by_epoch=True) +] +``` + +
+ +### FlatCosineAnnealingLrUpdaterHook migration + +The learning rate strategy combined by multiple phases like FlatCosineAnnealing originally needs to be achieved by rewriting a Hook. But in MMEngine, it can be achieved with combining two parameter scheduler configs: + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='FlatCosineAnnealing', + start_percent=0.5, + min_lr=0.005, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='ConstantLR', factor=1, begin=0, end=num_epochs * 0.75) + dict(type='CosineAnnealingLR', + eta_min=0.005, + begin=num_epochs * 0.75, + end=num_epochs, + T_max=num_epochs * 0.25, + by_epoch=True) +] +``` + +
+ +### CosineRestartLrUpdaterHook migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict(policy='CosineRestart', + periods=[5, 10, 15], + restart_weights=[1, 0.7, 0.3], + min_lr=0.001, + by_epoch=True) +``` + + + +```python +param_scheduler = [ + dict(type='CosineRestartLR', + periods=[5, 10, 15], + restart_weights=[1, 0.7, 0.3], + eta_min=0.001, + by_epoch=True) +] +``` + +
+ +### OneCycleLrUpdaterHook migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict(policy='OneCycle', + max_lr=0.02, + total_steps=90000, + pct_start=0.3, + anneal_strategy='cos', + div_factor=25, + final_div_factor=1e4, + three_phase=True, + by_epoch=False) +``` + + + +```python +param_scheduler = [ + dict(type='OneCycleLR', + eta_max=0.02, + total_steps=90000, + pct_start=0.3, + anneal_strategy='cos', + div_factor=25, + final_div_factor=1e4, + three_phase=True, + by_epoch=False) +] +``` + +
+ +Notice: `by_epoch` defaults to `False` in MMCV. It now defaults to `True` in MMEngine. + +### LinearAnnealingLrUpdaterHook migration + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='LinearAnnealing', + min_lr_ratio=0.01, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + dict(type='LinearLR', + start_factor=1, + end_factor=0.01, + begin=0, + end=num_epochs, + by_epoch=True) +] +``` + +
+ +## MomentumUpdater migration + +MMCV uses `momentum_config` field and MomentumUpdateHook to adjust momentum. The momentum in MMEngine is also controlled by the parameter scheduler. Users can simply change the `LR` of the learning rate scheduler to `Momentum` to use the same strategy to adjust the momentum. The momentum scheduler shares the same `param_scheduler` field in the config with the learning rate scheduler: + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict(...) +momentum_config = dict( + policy='CosineAnnealing', + min_momentum=0.1, + by_epoch=True +) +``` + + + +```python +param_scheduler = [ + # config of learning rate schedulers + dict(...), + # config of momentum schedulers + dict(type='CosineAnnealingMomentum', + eta_min=0.1, + T_max=num_epochs, + begin=0, + end=num_epochs, + by_epoch=True) +] +``` + +
+ +## Migrate parameter update frequency related config + +If you want to update the parameter rate based on iteration while using the epoch-based training loop and setting the effective range (`begin`, `end`) or period (`T_max`) and other variables according to epoch in MMCV, you need to set `by_epoch` to False. + +However, in MMEngine, the `by_epoch` in the config still needs to be set to True. Instead, you need to add `convert_to_iter_based=True` in the config to build a parameter scheduler which updates by iteration, see [Parameter Scheduler Tutorial](../tutorials/param_scheduler.md) for more details. + +Take the migration of CosineAnnealing as an example: + + + + + + + + + + + + +
MMCV-1.xMMEngine
+ +```python +lr_config = dict( + policy='CosineAnnealing', + min_lr=0.5, + by_epoch=False +) +``` + + + +```python +param_scheduler = [ + dict( + type='CosineAnnealingLR', + eta_min=0.5, + T_max=num_epochs, + by_epoch=True, # Notice, by_epoch need to be set to True + convert_to_iter_based=True # convert to an iter-based scheduler + ) +] +``` + +
+ +You may also want to read [parameter scheduler tutorial](../tutorials/param_scheduler.md) or [parameter scheduler API documentations](mmengine.optim.scheduler). diff --git a/testbed/open-mmlab__mmengine/docs/en/migration/runner.md b/testbed/open-mmlab__mmengine/docs/en/migration/runner.md new file mode 100644 index 0000000000000000000000000000000000000000..9bbd66106e72519965a582d995a3baeb9158f49b --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/migration/runner.md @@ -0,0 +1,1475 @@ +# Migrate Runner from MMCV to MMEngine + +## Introduction + +As MMCV supports more and more deep learning tasks, and users' needs become much more complicated, we have higher requirements for the flexibility and versatility of the existing `Runner` of MMCV. Therefore, MMEngine implements a more general and flexible `Runner` based on MMCV to support more complicated training processes. + +The `Runner` in MMEngine expands the scope and takes on more functions. we abstracted [training loop controller (EpochBasedTrainLoop/IterBasedTrainLoop)](mmengine.runner.EpochBasedLoop), [validation loop controller ( ValLoop)](mmengine.runner.ValLoop) and [TestLoop](mmengine.runner.TestLoop) to make it more convenient for users to customize their training process. + +Firstly, we will introduce how to migrate the entry point of training from MMCV to MMEngine, to simplify and unify the training script. Then, we'll introduce the difference in the instantiation of `Runner` between MMCV and MMEngine in detail. + +## Migrate the entry point + +Take MMDet as an example, the differences between training scripts in MMCV and MMEngine are as follows: + +### Migrate the configuration file + + + + + + + + + + + + + + + + + + + + + +
Configuration file based on MMCV Runner Configuration file based on MMEngine Runner
+ +```python +# default_runtime.py +checkpoint_config = dict(interval=1) +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) +custom_hooks = [dict(type='NumClassCheckHook')] + +dist_params = dict(backend='nccl') +log_level = 'INFO' +load_from = None +resume_from = None +workflow = [('train', 1)] + + +opencv_num_threads = 0 +mp_start_method = 'fork' +auto_scale_lr = dict(enable=False, base_batch_size=16) +``` + +
+
+ +```python +# default_runtime.py +default_scope = 'mmdet' + +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', interval=1), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='DetVisualizationHook')) + +env_cfg = dict( + cudnn_benchmark=False, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) + +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +log_processor = dict(type='LogProcessor', window_size=50, by_epoch=True) + +log_level = 'INFO' +load_from = None +resume = False +``` + +
+
+ +```python +# scheduler.py +# optimizer +optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[8, 11]) +runner = dict(type='EpochBasedRunner', max_epochs=12) +``` + +
+
+ +```python +# scheduler.py +# training schedule for 1x +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) + +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) +``` + +
+
+ +```python +# coco_detection.py + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' +img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='DefaultFormatBundle'), + dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), +] +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='MultiScaleFlipAug', + img_scale=(1333, 800), + flip=False, + transforms=[ + dict(type='Resize', keep_ratio=True), + dict(type='RandomFlip'), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +data = dict( + samples_per_gpu=2, + workers_per_gpu=2, + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +evaluation = dict(interval=1, metric='bbox') +``` + +
+
+ +```python +# coco_detection.py + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +file_client_args = dict(backend='disk') + +train_pipeline = [ + dict(type='LoadImageFromFile', file_client_args=file_client_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', file_client_args=file_client_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False) +test_evaluator = val_evaluator +``` + +
+
+ +`Runner` in MMEngine provides more customizable components, including training/validation/testing process and DataLoader. Therefore, the configuration file is a bit longer compared to MMCV. + +`MMEngine` follows the WYSIWYG principle and reorganizes the hierarchy of each component in configuration so that most of the first-level fields of configuration correspond to the core components in the `Runner`, such as DataLoader, [Evaluator](../tutorials/evaluation.md), [Hook](../tutorials/hook.md), etc. The new format configuration file could help users to read and understand the core components in `Runner`, and ignore the relatively unimportant parts. + +### Migrate the training script + +Compared with the `Runner` in MMCV, `Runner` in MMEngine takes on more functions, such as building DataLoader and distributed model. Therefore, we do not need to build the components like DataLoader and distributed model manually anymore. We can configure them during the instantiation of `Runner`, and then build them in the training/validation/testing process. Take the training script of MMDet as an example: + + + + + + + + + + + + + + + + +
Training script based on MMCV RunnerTraining script based on MMEngine Runner
+ +```python +# tools/train.py +args = parse_args() + +cfg = Config.fromfile(args.config) + +# replace the ${key} with the value of cfg.key +cfg = replace_cfg_vals(cfg) + +# update data root according to MMDET_DATASETS +update_data_root(cfg) + +if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + +if args.auto_scale_lr: + if 'auto_scale_lr' in cfg and \ + 'enable' in cfg.auto_scale_lr and \ + 'base_batch_size' in cfg.auto_scale_lr: + cfg.auto_scale_lr.enable = True + else: + warnings.warn('Can not find "auto_scale_lr" or ' + '"auto_scale_lr.enable" or ' + '"auto_scale_lr.base_batch_size" in your' + ' configuration file. Please update all the ' + 'configuration files to mmdet >= 2.24.1.') + +# set multi-process settings +setup_multi_processes(cfg) + +# set cudnn_benchmark +if cfg.get('cudnn_benchmark', False): + torch.backends.cudnn.benchmark = True + +# work_dir is determined in this priority: CLI > segment in file > filename +if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir +elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + +if args.resume_from is not None: + cfg.resume_from = args.resume_from +cfg.auto_resume = args.auto_resume +if args.gpus is not None: + cfg.gpu_ids = range(1) + warnings.warn('`--gpus` is deprecated because we only support ' + 'single GPU mode in non-distributed training. ' + 'Use `gpus=1` now.') +if args.gpu_ids is not None: + cfg.gpu_ids = args.gpu_ids[0:1] + warnings.warn('`--gpu-ids` is deprecated, please use `--gpu-id`. ' + 'Because we only support single GPU mode in ' + 'non-distributed training. Use the first GPU ' + 'in `gpu_ids` now.') +if args.gpus is None and args.gpu_ids is None: + cfg.gpu_ids = [args.gpu_id] + +# init distributed env first, since logger depends on the dist info. +if args.launcher == 'none': + distributed = False +else: + distributed = True + init_dist(args.launcher, **cfg.dist_params) + # re-set gpu_ids with distributed training mode + _, world_size = get_dist_info() + cfg.gpu_ids = range(world_size) + +# create work_dir +mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) +# dump config +cfg.dump(osp.join(cfg.work_dir, osp.basename(args.config))) +# init the logger before other steps +timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) +log_file = osp.join(cfg.work_dir, f'{timestamp}.log') +logger = get_root_logger(log_file=log_file, log_level=cfg.log_level) + +# init the meta dict to record some important information such as +# environment info and seed, which will be logged +meta = dict() +# log env info +env_info_dict = collect_env() +env_info = '\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()]) +dash_line = '-' * 60 + '\n' +logger.info('Environment info:\n' + dash_line + env_info + '\n' + + dash_line) +meta['env_info'] = env_info +meta['config'] = cfg.pretty_text +# log some basic info +logger.info(f'Distributed training: {distributed}') +logger.info(f'Config:\n{cfg.pretty_text}') + +cfg.device = get_device() +# set random seeds +seed = init_random_seed(args.seed, device=cfg.device) +seed = seed + dist.get_rank() if args.diff_seed else seed +logger.info(f'Set random seed to {seed}, ' + f'deterministic: {args.deterministic}') +set_random_seed(seed, deterministic=args.deterministic) +cfg.seed = seed +meta['seed'] = seed +meta['exp_name'] = osp.basename(args.config) + +model = build_detector( + cfg.model, + train_cfg=cfg.get('train_cfg'), + test_cfg=cfg.get('test_cfg')) +model.init_weights() + +datasets = [] +train_detector( + model, + datasets, + cfg, + distributed=distributed, + validate=(not args.no_validate), + timestamp=timestamp, + meta=meta) +``` + +
+
+ +```python +# tools/train.py +args = parse_args() + +# register all modules in mmdet into the registries +# do not init the default scope here because it will be init in the runner +register_all_modules(init_default_scope=False) + +# load config +cfg = Config.fromfile(args.config) +cfg.launcher = args.launcher +if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + +# work_dir is determined in this priority: CLI > segment in file > filename +if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir +elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + +# enable automatic-mixed-precision training +if args.amp is True: + optim_wrapper = cfg.optim_wrapper.type + if optim_wrapper == 'AmpOptimWrapper': + print_log( + 'AMP training is already enabled in your config.', + logger='current', + level=logging.WARNING) + else: + assert optim_wrapper == 'OptimWrapper', ( + '`--amp` is only supported when the optimizer wrapper type is ' + f'`OptimWrapper` but got {optim_wrapper}.') + cfg.optim_wrapper.type = 'AmpOptimWrapper' + cfg.optim_wrapper.loss_scale = 'dynamic' + +# enable automatically scaling LR +if args.auto_scale_lr: + if 'auto_scale_lr' in cfg and \ + 'enable' in cfg.auto_scale_lr and \ + 'base_batch_size' in cfg.auto_scale_lr: + cfg.auto_scale_lr.enable = True + else: + raise RuntimeError('Can not find "auto_scale_lr" or ' + '"auto_scale_lr.enable" or ' + '"auto_scale_lr.base_batch_size" in your' + ' configuration file.') + +cfg.resume = args.resume + +# build the runner from config +if 'runner_type' not in cfg: + # build the default runner + runner = Runner.from_cfg(cfg) +else: + # build customized runner from the registry + # if 'runner_type' is set in the cfg + runner = RUNNERS.build(cfg) + +# start training +runner.train() +``` + +
+
+ +```python +# apis/train.py +def init_random_seed(...): + ... + +def set_random_seed(...): + ... + +# define function tools. +... + + +def train_detector(model, + dataset, + cfg, + distributed=False, + validate=False, + timestamp=None, + meta=None): + + cfg = compat_cfg(cfg) + logger = get_root_logger(log_level=cfg.log_level) + + # put model on gpus + if distributed: + find_unused_parameters = cfg.get('find_unused_parameters', False) + # Sets the `find_unused_parameters` parameter in + # torch.nn.parallel.DistributedDataParallel + model = build_ddp( + model, + cfg.device, + device_ids=[int(os.environ['LOCAL_RANK'])], + broadcast_buffers=False, + find_unused_parameters=find_unused_parameters) + else: + model = build_dp(model, cfg.device, device_ids=cfg.gpu_ids) + + # build optimizer + auto_scale_lr(cfg, distributed, logger) + optimizer = build_optimizer(model, cfg.optimizer) + + runner = build_runner( + cfg.runner, + default_args=dict( + model=model, + optimizer=optimizer, + work_dir=cfg.work_dir, + logger=logger, + meta=meta)) + + # an ugly workaround to make .log and .log.json filenames the same + runner.timestamp = timestamp + + # fp16 setting + fp16_cfg = cfg.get('fp16', None) + if fp16_cfg is not None: + optimizer_config = Fp16OptimizerHook( + **cfg.optimizer_config, **fp16_cfg, distributed=distributed) + elif distributed and 'type' not in cfg.optimizer_config: + optimizer_config = OptimizerHook(**cfg.optimizer_config) + else: + optimizer_config = cfg.optimizer_config + + # register hooks + runner.register_training_hooks( + cfg.lr_config, + optimizer_config, + cfg.checkpoint_config, + cfg.log_config, + cfg.get('momentum_config', None), + custom_hooks_config=cfg.get('custom_hooks', None)) + + if distributed: + if isinstance(runner, EpochBasedRunner): + runner.register_hook(DistSamplerSeedHook()) + + # register eval hooks + if validate: + val_dataloader_default_args = dict( + samples_per_gpu=1, + workers_per_gpu=2, + dist=distributed, + shuffle=False, + persistent_workers=False) + + val_dataloader_args = { + **val_dataloader_default_args, + **cfg.data.get('val_dataloader', {}) + } + # Support batch_size > 1 in validation + + if val_dataloader_args['samples_per_gpu'] > 1: + # Replace 'ImageToTensor' to 'DefaultFormatBundle' + cfg.data.val.pipeline = replace_ImageToTensor( + cfg.data.val.pipeline) + val_dataset = build_dataset(cfg.data.val, dict(test_mode=True)) + + val_dataloader = build_dataloader(val_dataset, **val_dataloader_args) + eval_cfg = cfg.get('evaluation', {}) + eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner' + eval_hook = DistEvalHook if distributed else EvalHook + # In this PR (https://github.com/open-mmlab/mmcv/pull/1193), the + # priority of IterTimerHook has been modified from 'NORMAL' to 'LOW'. + runner.register_hook( + eval_hook(val_dataloader, **eval_cfg), priority='LOW') + + resume_from = None + if cfg.resume_from is None and cfg.get('auto_resume'): + resume_from = find_latest_checkpoint(cfg.work_dir) + if resume_from is not None: + cfg.resume_from = resume_from + + if cfg.resume_from: + runner.resume(cfg.resume_from) + elif cfg.load_from: + runner.load_checkpoint(cfg.load_from) + runner.run(data_loaders, cfg.workflow) +``` + +
+
+ +```python +# `apis/train.py` is removed in `mmengine` +``` + +
+ +Table above shows the differences between training script of MMEngine `Runner` and MMCV `Runner`. Repositories of OpenMMLab 1.x organize their own process to build `Runner`, which contributes to the large amount of redundant code. MMEngine unifies and formats the building process, such as setting random seed, initializing distributed environment, building DataLoader, building `Optimizer`, etc. This help the downstream repositories simplify the process to prepare the runner, and only need to configure the parameters of `Runner`. + +For the downstream repositories, training script based on MMEngine Runner not only simplify the `tools/train.py`, but also can directly omit the `apis/train.py`. Similarly, we can also set random seed, initialize distributed environment by configuring the parameters of `Runner`, and do not need to implement the corresponding code. + +## Migrate Runner + +This section describes the differences in the training, validation, and testing processes between the MMCV Runner and the MMEngine Runner, as follows. + +01. [Prepare logger](#prepare-logger) +02. [Set random seed](#set-random-seed) +03. [Initialize environment variables](#initialize-environment-variables) +04. [Prepare data](#prepare-data) +05. [Prepare model](#prepare-model) +06. [Prepare optimizer](#prepare-optimizer) +07. [Prepare hooks](#prepare-hooks) +08. [Prepare testing/validation components](#prepare-testingvalidation-components) +09. [Build runner](#build-runner) +10. [Load checkpoint](#load-checkpoint) +11. [Training process](#training-process), [Testing process](#testing-process) +12. [Custom training process](#customize-training-process) + +The following tutorial will describe the difference above in detail. + +### Prepare logger + +**Prepare logger in MMCV** + +MMCV needs to call the `get_logger` to get a formatted logger and use it to output and log the training information. + +```python +logger = get_logger(name='custom', log_file=log_file, log_level=cfg.log_level) +env_info_dict = collect_env() +env_info = '\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()]) +dash_line = '-' * 60 + '\n' +logger.info('Environment info:\n' + dash_line + env_info + '\n' + + dash_line) +``` + +The instantiation of the Runner also relies on the logger: + +```python +runner = Runner( + ... + logger=logger + ...) +``` + +**Prepare logger in MMEngine** + +Configure the `log_level` for `Runner`, and it will build the logger automatically. + +```python +log_level = 'INFO' +``` + +### Set random seed + +**Set random seed in MMCV** + +Set random seed manually in training script: + +```python +... +seed = init_random_seed(args.seed, device=cfg.device) +seed = seed + dist.get_rank() if args.diff_seed else seed +logger.info(f'Set random seed to {seed}, ' + f'deterministic: {args.deterministic}') +set_random_seed(seed, deterministic=args.deterministic) +... +``` + +**Set random seed in MMEngine** + +Configure the `randomness` for `Runner`, see more information in [Runner.set_randomness](mmengine.runner.Runner.set_randomness) + +**Configuration changes** + + + + + + + + + + + + +
Configuration of MMCVConfiguration of MMEngine
+ +```python +seed = 1 +deterministic=False +diff_seed=False +``` + +
+
+ +```python +randomness=dict(seed=1, + deterministic=True, + diff_rank_seed=False) +``` + +
+
+ +### Initialize environment variables + +**Initialize the environment variables** + +MMCV needs to setup launcher of distributed training, set environment variables for multi-process communication, initialize the distributed environment and wrap model with the distributed wrapper like this: + +```python +... +setup_multi_processes(cfg) +init_dist(cfg.launcher, **cfg.dist_params) +model = MMDistributedDataParallel( + model, + device_ids=[int(os.environ['LOCAL_RANK'])], + broadcast_buffers=False, + find_unused_parameters=find_unused_parameters) +``` + +As for MMEngine, you can setup launcher by configuring `launcher` of `Runner`, and configure other items mentioned above in `env_cfg`. See more information in the table below: + +**Configuration changes** + + + + + + + + + + + + +
MMCV configurationMMEngine configuration
+ +```python +launcher = 'pytorch' # enable distributed training +dist_params = dict(backend='nccl') # choose communication backend +``` + +
+
+ +```python +launcher = 'pytorch' +env_cfg = dict(dist_cfg=dict(backend='nccl')) +``` + +
+
+ +In this tutorial, we set `env_cfg` to: + +```python +env_cfg = dict(dist_cfg=dict(backend='nccl')) +``` + +### Prepare data + +Both MMEngine and MMCV `Runner` can accept built `DataLoader` + +```python +import torchvision.transforms as transforms +from torch.utils.data import DataLoader +from torchvision.datasets import CIFAR10 + +transform = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) +]) + +train_dataset = CIFAR10( + root='data', train=True, download=True, transform=transform) +train_dataloader = DataLoader( + train_dataset, batch_size=128, shuffle=True, num_workers=2) + +val_dataset = CIFAR10( + root='data', train=False, download=True, transform=transform) +val_dataloader = DataLoader( + val_dataset, batch_size=128, shuffle=False, num_workers=2) +``` + +**Configuration changes** + + + + + + + + + + + + +
Configuration of MMCVConfiguration of MMEngine
+ +```python +data = dict( + samples_per_gpu=2, # batch_size of single gpu + workers_per_gpu=2, # num_workers of DataLoader + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +``` + +
+
+ +```python +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + # Configurable sampler + sampler=dict(type='DefaultSampler', shuffle=True), + # Configurable batch_sampler + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, # batch_size of validation process + num_workers=2, + persistent_workers=True, + drop_last=False, # whether drop the last batch + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) + +test_dataloader = val_dataloader +``` + +
+
+ +### Prepare model + +See [Migrate model from mmcv](./model.md) for more information + +```python +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModel + + +class Model(BaseModel): + + def __init__(self): + super().__init__() + self.conv1 = nn.Conv2d(3, 6, 5) + self.pool = nn.MaxPool2d(2, 2) + self.conv2 = nn.Conv2d(6, 16, 5) + self.fc1 = nn.Linear(16 * 5 * 5, 120) + self.fc2 = nn.Linear(120, 84) + self.fc3 = nn.Linear(84, 10) + self.loss_fn = nn.CrossEntropyLoss() + + def forward(self, img, label, mode): + feat = self.pool(F.relu(self.conv1(img))) + feat = self.pool(F.relu(self.conv2(feat))) + feat = feat.view(-1, 16 * 5 * 5) + feat = F.relu(self.fc1(feat)) + feat = F.relu(self.fc2(feat)) + feat = self.fc3(feat) + if mode == 'loss': + loss = self.loss_fn(feat, label) + return dict(loss=loss) + else: + return [feat.argmax(1)] + +model = Model() +``` + +### Prepare optimizer + +**Prepare optimizer in MMCV** + +MMCV Runner can accept built optimizer + +```python +optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9) +``` + +For complicated configurations of optimizers, MMCV needs to build optimizers based on the optimizer constructors. + +```python + +optimizer_cfg = dict( + optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001), + paramwise_cfg=dict(norm_decay_mult=0)) + +def build_optimizer_constructor(cfg): + constructor_type = cfg.get('type') + if constructor_type in OPTIMIZER_BUILDERS: + return build_from_cfg(cfg, OPTIMIZER_BUILDERS) + elif constructor_type in MMCV_OPTIMIZER_BUILDERS: + return build_from_cfg(cfg, MMCV_OPTIMIZER_BUILDERS) + else: + raise KeyError(f'{constructor_type} is not registered ' + 'in the optimizer builder registry.') + + +def build_optimizer(model, cfg): + optimizer_cfg = copy.deepcopy(cfg) + constructor_type = optimizer_cfg.pop('constructor', + 'DefaultOptimizerConstructor') + paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) + optim_constructor = build_optimizer_constructor( + dict( + type=constructor_type, + optimizer_cfg=optimizer_cfg, + paramwise_cfg=paramwise_cfg)) + optimizer = optim_constructor(model) + return optimizer + +optimizer = build_optimizer(model, optimizer_cfg) +``` + +**Prepare optimizer in MMEngine** + +MMEngine needs to configure [optim_wrapper](mmengine.optim.OptimWrapper) for `Runner`. For more complicated cases, you can also configure the `optim_wrapper` more specifically. See more information in the API [documents](mmengine.runner.Runner.build_optim_wrapper) + +**Configuration changes** + + + + + + + + + + + + +
Configuration in MMCVConfiguration in MMEngine
+ +```python +optimizer = dict( + constructor='CustomConstructor', + type='AdamW', + lr=0.0001, + betas=(0.9, 0.999), + weight_decay=0.05, + paramwise_cfg={ # parameters of constructor + 'decay_rate': 0.95, + 'decay_type': 'layer_wise', + 'num_layers': 6 + }) + +# MMCV needs to configure `optim_config` additionally +optimizer_config = dict(grad_clip=None) +``` + +
+
+ +```python +optim_wrapper = dict( + constructor='CustomConstructor', + type='OptimWrapper', # Specify the type of OptimWrapper + optimizer=dict( # optimizer configuration + type='AdamW', + lr=0.0001, + betas=(0.9, 0.999), + weight_decay=0.05) + paramwise_cfg={ + 'decay_rate': 0.95, + 'decay_type': 'layer_wise', + 'num_layers': 6 + }) +``` + +
+
+ +```{note} +For the high-level tasks like detection and classification, MMCV needs to configure `optim_config` to build `OptimizerHook`, while not necessary for MMEngine. +``` + +`optim_wrapper` used in this tutorial is as follows: + +```python +from torch.optim import SGD + +optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9) +optim_wrapper = dict(optimizer=optimizer) +``` + +### Prepare hooks + +**Prepare hooks in MMCV** + +The commonly used hooks configuration in MMCV is as follows: + +```python +# learning rate scheduler config +lr_config = dict(policy='step', step=[2, 3]) +# configuration of optimizer +optimizer_config = dict(grad_clip=None) +# configuration of saving checkpoints periodically +checkpoint_config = dict(interval=1) +# save log periodically and multiple hooks can be used simultaneously +log_config = dict(interval=100, hooks=[dict(type='TextLoggerHook')]) +# register hooks to runner and those hooks will be invoked automatically +runner.register_training_hooks( + lr_config=lr_config, + optimizer_config=optimizer_config, + checkpoint_config=checkpoint_config, + log_config=log_config) +``` + +Among them: + +- `lr_config` is used for `LrUpdaterHook` +- `optimizer_config` is used for `OptimizerHook` +- `checkpoint_config` is used for `CheckPointHook` +- `log_config` is used for `LoggerHook` + +Besides the hooks mentioned above, MMCV Runner will build `IterTimerHook` automatically. MMCV `Runner` will register the training hooks after instantiating the model, while MMEngine Runner will initialize the hooks during instantiating the model. + +**Prepare hooks in MMEngine** + +MMEngine `Runner` takes some commonly used hooks in MMCV as the default hooks. + +- [RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook) +- [IterTimerHook](mmengine.hooks.IterTimerHook) +- [DistSamplerSeedHook](mmengine.hooks.DistSamplerSeedHook) +- [LoggerHook](mmengine.hooks.LoggerHook) +- [CheckpointHook](mmengine.hooks.CheckpointHook) +- [ParamSchedulerHook](mmengine.hooks.ParamSchedulerHook) + +Compared with the example of MMCV + +- `LrUpdaterHook` correspond to the `ParamSchedulerHook`, find more details in [migrate scheduler](./param_scheduler.md) +- MMEngine optimize the model in [train_step](mmengine.model.BaseModel.train_step), therefore we do not need `OptimizerHook` in MMEngine anymore +- MMEngine takes `CheckPointHook` as the default hook +- MMEngine take `LoggerHook` as the default hook + +Therefore, we can achieve the same effect as the MMCV example as long as we configure the [param_scheduler](../tutorials/param_scheduler.md) correctly. + +We can also register custom hooks in MMEngine runner, find more details in [runner tutorial](../tutorials/runner.md) and [migrate hook](./hook.md). + + + + + + + + + + + + +
Commonly used hooks in MMCVDefault hooks in MMEngine
+ +```python +# Configure training hooks +# Configure LrUpdaterHook +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[8, 11]) + +# Configure OptimizerHook +optimizer_config = dict(grad_clip=None) + +# Configure LoggerHook +log_config = dict( # LoggerHook + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +# Configure CheckPointHook +checkpoint_config = dict(interval=1) # CheckPointHook +``` + +
+
+ +```python +# Configure parameter scheduler +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] + +# Configure default hooks +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', interval=1), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='DetVisualizationHook')) +``` + +
+
+ +The parameter scheduler used in this tutorial is as follows: + +```python +from math import gamma + +param_scheduler = dict(type='MultiStepLR', milestones=[2, 3], gamma=0.1) +``` + +### Prepare testing/validation components + +MMCV implements the validation process by `EvalHook`, and we'll not talk too much about it here. Given that validation is a common process in training, MMEngine abstracts validation as two independent modules: [Evaluator](../tutorials/evaluation.md) and [ValLoop](../tutorials/runner.md). We can customize the metric or the validation process by defining a new [loop](mmengine.runner.ValLoop) or a new [metric](mmengine.evaluator.BaseMetirc). + +```python +import torch +from mmengine.evaluator import BaseMetric +from mmengine.registry import METRICS + +@METRICS.register_module(force=True) +class ToyAccuracyMetric(BaseMetric): + + def process(self, label, pred) -> None: + self.results.append((label[1], pred, len(label[1]))) + + def compute_metrics(self, results: list) -> dict: + num_sample = 0 + acc = 0 + for label, pred, batch_size in results: + acc += (label == torch.stack(pred)).sum() + num_sample += batch_size + return dict(Accuracy=acc / num_sample) +``` + +After defining the metric, we should also configure the evaluator and loop for `Runner`. The example used in this tutorial is as follows: + +```python +val_evaluator = dict(type='ToyAccuracyMetric') +val_cfg = dict(type='ValLoop') +``` + + + + + + + + + + + + +
Configure validation in MMCVConfigure validation in MMEngine
+ +```python +eval_cfg = cfg.get('evaluation', {}) +eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner' +eval_hook = DistEvalHook if distributed else EvalHook +runner.register_hook( + eval_hook(val_dataloader, **eval_cfg), priority='LOW') +``` + +
+
+ +```python +val_dataloader = val_dataloader +val_evaluator = dict(type='ToyAccuracyMetric') +val_cfg = dict(type='ValLoop') +``` + +
+
+ +### Build Runner + +**Building Runner in MMCV** + +```python +runner = EpochBasedRunner( + model=model, + optimizer=optimizer, + work_dir=work_dir, + logger=logger, + max_epochs=4 +) +``` + +**Building Runner in MMEngine** + +The `EpochBasedRunner` and `max_epochs` arguments in `MMCV` are moved to `train_cfg` in MMEngine. All parameters configurable in `train_cfg` are listed below: + +- by_epoch: `True` equivalent to `EpochBasedRunner`. `False` equivalent to `IterBasedRunner` +- `max_epoch/max_iter`: Equivalent to `max_epochs` and `max_iters` in MMCV +- `val_iterval`: Equivalent to `interval` in MMCV + +```python +from mmengine.runner import Runner + +runner = Runner( + model=model, # model to be optimized + work_dir='./work_dir', # working directory + randomness=randomness, # random seed + env_cfg=env_cfg, # environment config + launcher='none', # launcher for distributed training + optim_wrapper=optim_wrapper, # configure optimizer wrapper + param_scheduler=param_scheduler, # configure parameter scheduler + train_dataloader=train_dataloader, # configure train dataloader + train_cfg=dict(by_epoch=True, max_epochs=4, val_interval=1), # Configure training loop + val_dataloader=val_dataloader, # Configure validation dataloader + val_evaluator=val_evaluator, # Configure evaluator and metrics + val_cfg=val_cfg) # Configure validation loop +``` + +### Load checkpoint + +**Loading checkpoint in MMCV** + +```python +if cfg.resume_from: + runner.resume(cfg.resume_from) +elif cfg.load_from: + runner.load_checkpoint(cfg.load_from) +``` + +**Loading checkpoint in MMEngine** + +```python +runner = Runner( + ... + load_from='/path/to/checkpoint', + resume=True +) +``` + + + + + + + + + + + + + + + + +
Configuration of loading checkpoint in MMCVConfiguration of loading checkpoint in MMEngine
+ +```python +load_from = 'path/to/ckpt' +``` + +
+ +```python +load_from = 'path/to/ckpt' +resume = False +``` + +
+
+ +```python +resume_from = 'path/to/ckpt' +``` + +
+ +```python +load_from = 'path/to/ckpt' +resume = True +``` + +
+
+ +### Training process + +**Training process in MMCV** + +Resume or load checkpoint firstly, and then start training. + +```python +if cfg.resume_from: + runner.resume(cfg.resume_from) +elif cfg.load_from: + runner.load_checkpoint(cfg.load_from) +runner.run(data_loaders, cfg.workflow) +``` + +**Training process in MMEngine** + +Complete the process mentioned above the `Runner.__init__` and `Runner.train` + +```python +runner.train() +``` + +### Testing process + +Since MMCV Runner does not integrate the test function, we need to implement the test scripts by ourselves. + +For MMEngine Runner, as long as we have configured the `test_dataloader`, `test_cfg` and `test_evaluator` for the `Runner`, we can call `Runner.test` to start the testing process. + +**`work_dir` is the same for training** + +```python +runner = Runner( + model=model, + work_dir='./work_dir', + randomness=randomness, + env_cfg=env_cfg, + launcher='none', # 不开启分布式训练 + optim_wrapper=optim_wrapper, + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1), + val_dataloader=val_dataloader, + val_evaluator=val_evaluator, + val_cfg=val_cfg, + test_dataloader=val_dataloader, # 假设测试和验证使用相同的数据和评测器 + test_evaluator=val_evaluator, + test_cfg=dict(type='TestLoop'), +) +runner.test() +``` + +**`work_dir` is the different for training, configure load_from manually** + +```python +runner = Runner( + model=model, + work_dir='./test_work_dir', + load_from='./work_dir/epoch_5.pth', # set load_from additionally + randomness=randomness, + env_cfg=env_cfg, + launcher='none', + optim_wrapper=optim_wrapper, + train_dataloader=train_dataloader, + train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1), + val_dataloader=val_dataloader, + val_evaluator=val_evaluator, + val_cfg=val_cfg, + test_dataloader=val_dataloader, + test_evaluator=val_evaluator, + test_cfg=dict(type='TestLoop'), +) +runner.test() +``` + +### Customize training process + +If we want to customize a training/validation process, we need to override the `Runner.val` or `Runner.train` in a custom `Runner`. Take overriding `runner.train` as an example, suppose we need to train with the same batch twice for each iteration, we can override the `Runner.train` like this: + +```python +class CustomRunner(EpochBasedRunner): + def train(self, data_loader, **kwargs): + self.model.train() + self.mode = 'train' + self.data_loader = data_loader + self._max_iters = self._max_epochs * len(self.data_loader) + self.call_hook('before_train_epoch') + time.sleep(2) # Prevent possible deadlock during epoch transition + for i, data_batch in enumerate(self.data_loader): + self.data_batch = data_batch + self._inner_iter = i + for _ in range(2) + self.call_hook('before_train_iter') + self.run_iter(data_batch, train_mode=True, **kwargs) + self.call_hook('after_train_iter') + del self.data_batch + self._iter += 1 + + self.call_hook('after_train_epoch') + self._epoch += 1 +``` + +In MMEngine, we need to customize a train loop. + +```python +from mmengine.registry import LOOPS +from mmengine.runner import EpochBasedTrainLoop + + +@LOOPS.register_module() +class CustomEpochBasedTrainLoop(EpochBasedTrainLoop): + def run_iter(self, idx, data_batch) -> None: + for _ in range(2): + super().run_iter(idx, data_batch) +``` + +and then, we need to set `type` as `CustomEpochBasedTrainLoop` in `train_cfg`. Note that `by_epoch` and `type` cannot be configured at the same time. Once `by_epoch` is configured, the type of the training loop will be inferred as `EpochBasedTrainLoop`. + +```python +runner = Runner( + model=model, + work_dir='./test_work_dir', + randomness=randomness, + env_cfg=env_cfg, + launcher='none', + optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)), + train_dataloader=train_dataloader, + train_cfg=dict( + type='CustomEpochBasedTrainLoop', + max_epochs=5, + val_interval=1), + val_dataloader=val_dataloader, + val_evaluator=val_evaluator, + val_cfg=val_cfg, + test_dataloader=val_dataloader, + test_evaluator=val_evaluator, + test_cfg=dict(type='TestLoop'), +) +runner.train() +``` + +For more complicated migration needs of `Runner`, you can refer to the [runner tutorials](../tutorials/runner.md) and [runner design](../design/runner.md). diff --git a/testbed/open-mmlab__mmengine/docs/en/migration/transform.md b/testbed/open-mmlab__mmengine/docs/en/migration/transform.md new file mode 100644 index 0000000000000000000000000000000000000000..ccfafd5642223db5af9591060f5c73b1a3584ea5 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/migration/transform.md @@ -0,0 +1,162 @@ +# Migrate Data Transform to OpenMMLab 2.0 + +## Introduction + +According to the data transform interface convention of TorchVision, all data transform classes need to +implement the `__call__` method. And in the convention of OpenMMLab 1.0, we require the input and output of +the `__call__` method should be a dictionary. + +In OpenMMLab 2.0, to make the data transform classes more extensible, we use `transform` method instead of +`__call__` method to implement data transformation, and all data transform classes should inherit the +[`mmcv.transforms.BaseTransfrom`](mmcv.transforms.BaseTransfrom) class. And you can still use these data +transform classes by calling. + +A tutorial to implement a data transform class can be found in the [Data Transform](../advanced_tutorials/data_element.md). + +In addition, we move some common data transform classes from every repositories to MMCV, and in this document, +we will compare the functionalities, usages and implementations between the original data transform classes (in [MMClassification v0.23.2](https://github.com/open-mmlab/mmclassification/tree/v0.23.2), [MMDetection v2.25.1](https://github.com/open-mmlab/mmdetection/tree/v2.25.1)) and the new data transform classes (in [MMCV v2.0.0rc1](https://github.com/open-mmlab/mmcv/tree/2.x)) + +## Functionality Differences + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MMClassification (original)MMDetection (original)MMCV (new)
LoadImageFromFileJoin the 'img_prefix' and 'img_info.filename' field to find the path of images and loading.Join the 'img_prefix' and 'img_info.filename' field to find the path of images and loading. Support + specifying the order of channels.Load images from 'img_path'. Support ignoring failed loading and specifying decode backend.
LoadAnnotationsNot available.Load bbox, label, mask (include polygon masks), semantic segmentation. Support converting bbox coordinate system.Load bbox, label, mask (not include polygon masks), semantic segmentation.
PadPad all images in the "img_fields" field.Pad all images in the "img_fields" field. Support padding to integer multiple size.Pad the image in the "img" field. Support padding to integer multiple size.
CenterCropCrop all images in the "img_fields" field. Support cropping as EfficientNet style.Not available.Crop the image in the "img" field, the bbox in the "gt_bboxes" field, the semantic segmentation in the "gt_seg_map" field, the keypoints in the "gt_keypoints" field. Support padding the margin of the cropped image.
NormalizeNormalize the image.No differences.No differences, but we recommend to use data preprocessor to normalize the image.
ResizeResize all images in the "img_fields" field. Support resizing proportionally according to the specified edge.Use Resize with ratio_range=None, the img_scale have a single scale, and multiscale_mode="value".Resize the image in the "img" field, the bbox in the "gt_bboxes" field, the semantic segmentation in the "gt_seg_map" field, the keypoints in the "gt_keypoints" field. Support specifying the ratio of new scale to original scale and support resizing proportionally.
RandomResizeNot availableUse Resize with ratio_range=None, img_scale have two scales and multiscale_mode="range", or ratio_range is not None. +
Resize(
+    img_sacle=[(640, 480), (960, 720)],
+    mode="range",
+)
+
Have the same resize function as Resize. Support sampling the scale from a scale range or scale ratio range. +
RandomResize(scale=[(640, 480), (960, 720)])
+
RandomChoiceResizeNot availableUse Resize with ratio_range=None, img_scale have multiple scales, and multiscale_mode="value". +
Resize(
+    img_sacle=[(640, 480), (960, 720)],
+    mode="value",
+)
+
Have the same resize function as Resize. Support randomly choosing the scale from multiple scales or multiple scale ratios. +
RandomChoiceResize(scales=[(640, 480), (960, 720)])
+
RandomGrayscaleRandomly grayscale all images in the "img_fields" field. Support keeping channels after grayscale.Not availableRandomly grayscale the image in the "img" field. Support specifying the weight of each channel, and support keeping channels after grayscale.
RandomFlipRandomly flip all images in the "img_fields" field. Support flipping horizontally and vertically.Randomly flip all values in the "img_fields", "bbox_fields", "mask_fields" and "seg_fields". Support flipping horizontally, vertically and diagonally, and support specifying the probability of every kind of flipping.Randomly flip the values in the "img", "gt_bboxes", "gt_seg_map", "gt_keypoints" field. Support flipping horizontally, vertically and diagonally, and support specifying the probability of every kind of flipping.
MultiScaleFlipAugNot availableUsed for test-time-augmentation.Use TestTimeAug
ToTensorConvert the values in the specified fields to torch.Tensor.No differencesNo differences
ImageToTensorConvert the values in the specified fields to torch.Tensor and transpose the channels to CHW.No differences.No differences.
+ +## Implementation Differences + +Take `RandomFlip` as example, the new version [RandomFlip](<>) in MMCV inherits `BaseTransfrom`, and move the +functionality implementation from `__call__` to `transform` method. In addition, the randomness related code +is placed in some extra methods and these methods need to be wrapped by `cache_randomness` decorator. + +- MMDetection (original version) + +```python +class RandomFlip: + def __call__(self, results): + """Randomly flip images.""" + ... + # Randomly choose the flip direction + cur_dir = np.random.choice(direction_list, p=flip_ratio_list) + ... + return results +``` + +- MMCV (new version) + +```python +class RandomFlip(BaseTransfrom): + def transform(self, results): + """Randomly flip images""" + ... + cur_dir = self._random_direction() + ... + return results + + @cache_randomness + def _random_direction(self): + """Randomly choose the flip direction""" + ... + return np.random.choice(direction_list, p=flip_ratio_list) +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/notes/changelog.md b/testbed/open-mmlab__mmengine/docs/en/notes/changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..0d216170225f7286679950b956a284ce1c0ac0ff --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/notes/changelog.md @@ -0,0 +1,161 @@ +# Changelog of v0.x + +## v0.3.2 (11/24/2022) + +### New Features & Enhancements + +- Send git errors to subprocess.PIPE by @austinmw in https://github.com/open-mmlab/mmengine/pull/717 +- Add a common `TestRunnerTestCase` to build a Runner instance. by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/631 +- Align the log by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/436 +- Log the called order of hooks during training process by @songyuc in https://github.com/open-mmlab/mmengine/pull/672 +- Support setting `eta_min_ratio` in `CosineAnnealingParamScheduler` by @cir7 in https://github.com/open-mmlab/mmengine/pull/725 +- Enhance compatibility of `revert_sync_batchnorm` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/695 + +### Bug Fixes + +- Fix `distributed_training.py` in examples by @PingHGao in https://github.com/open-mmlab/mmengine/pull/700 +- Format the log of `CheckpointLoader.load_checkpoint` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/685 +- Fix bug of CosineAnnealingParamScheduler by @fangyixiao18 in https://github.com/open-mmlab/mmengine/pull/735 +- Fix `add_graph` is not called bug by @shenmishajing in https://github.com/open-mmlab/mmengine/pull/632 +- Fix .pre-commit-config-zh-cn.yaml pyupgrade-repo github->gitee by @BayMaxBHL in https://github.com/open-mmlab/mmengine/pull/756 + +### Docs + +- Add English docs of BaseDataset by @GT9505 in https://github.com/open-mmlab/mmengine/pull/713 +- Fix `BaseDataset` typo about lazy initialization by @MengzhangLI in https://github.com/open-mmlab/mmengine/pull/733 +- Fix typo by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/734 +- Translate visualization docs by @xin-li-67 in https://github.com/open-mmlab/mmengine/pull/692 + +## v0.3.1 (11/09/2022) + +### Highlights + +- Fix error when saving best checkpoint in ddp-training + +### New Features & Enhancements + +- Replace `print` with `print_log` for those functions called by runner by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/686 + +### Bug Fixes + +- Fix error when saving best checkpoint in ddp-training by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/682 + +### Docs + +- Refine Chinese tutorials by @Xiangxu-0103 in https://github.com/open-mmlab/mmengine/pull/694 +- Add MMEval in README by @sanbuphy in https://github.com/open-mmlab/mmengine/pull/669 +- Fix error URL in runner docstring by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/668 +- Fix error evaluator type name in `evaluator.md` by @sanbuphy in https://github.com/open-mmlab/mmengine/pull/675 +- Fix typo in `utils.md` @sanbuphy in https://github.com/open-mmlab/mmengine/pull/702 + +## v0.3.0 (11/02/2022) + +### New Features & Enhancements + +- Support running on Ascend chip by @wangjiangben-hw in https://github.com/open-mmlab/mmengine/pull/572 +- Support torch `ZeroRedundancyOptimizer` by @nijkah in https://github.com/open-mmlab/mmengine/pull/551 +- Add non-blocking feature to `BaseDataPreprocessor` by @shenmishajing in https://github.com/open-mmlab/mmengine/pull/618 +- Add documents for `clip_grad`, and support clip grad by value. by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/513 +- Add ROCm info when collecting env by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/633 +- Add a function to mark the deprecated function. by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/609 +- Call `register_all_modules` in `Registry.get()` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/541 +- Deprecate `_save_to_state_dict` implemented in mmengine by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/610 +- Add `ignore_keys` in ConcatDataset by @BIGWangYuDong in https://github.com/open-mmlab/mmengine/pull/556 + +### Docs + +- Fix cannot show `changelog.md` in chinese documents. by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/606 +- Fix Chinese docs whitespaces by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/521 +- Translate installation and 15_min by @xin-li-67 in https://github.com/open-mmlab/mmengine/pull/629 +- Refine chinese doc by @Tau-J in https://github.com/open-mmlab/mmengine/pull/516 +- Add MMYOLO link in README by @Xiangxu-0103 in https://github.com/open-mmlab/mmengine/pull/634 +- Add MMEngine logo in docs by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/641 +- Fix docstring of `BaseDataset` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/656 +- Fix docstring and documentation used for `hub.get_model` by @zengyh1900 in https://github.com/open-mmlab/mmengine/pull/659 +- Fix typo in `docs/zh_cn/advanced_tutorials/visualization.md` by @MambaWong in https://github.com/open-mmlab/mmengine/pull/616 +- Fix typo docstring of `DefaultOptimWrapperConstructor` by @triple-Mu in https://github.com/open-mmlab/mmengine/pull/644 +- Fix typo in advanced tutorial by @cxiang26 in https://github.com/open-mmlab/mmengine/pull/650 +- Fix typo in `Config` docstring by @sanbuphy in https://github.com/open-mmlab/mmengine/pull/654 +- Fix typo in `docs/zh_cn/tutorials/config.md` by @Xiangxu-0103 in https://github.com/open-mmlab/mmengine/pull/596 +- Fix typo in `docs/zh_cn/tutorials/model.md` by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/598 + +### Bug Fixes + +- Fix error calculation of `eta_min` in `CosineRestartParamScheduler` by @Z-Fran in https://github.com/open-mmlab/mmengine/pull/639 +- Fix `BaseDataPreprocessor.cast_data` could not handle string data by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/602 +- Make `autocast` compatible with mps by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/587 +- Fix error format of log message by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/508 +- Fix error implementation of `is_model_wrapper` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/640 +- Fix `VisBackend.add_config` is not called by @shenmishajing in https://github.com/open-mmlab/mmengine/pull/613 +- Change `strict_load` of EMAHook to False by default by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/642 +- Fix `open` encoding problem of Config in Windows by @sanbuphy in https://github.com/open-mmlab/mmengine/pull/648 +- Fix the total number of iterations in log is a float number. by @jbwang1997 in https://github.com/open-mmlab/mmengine/pull/604 +- Fix `pip upgrade` CI by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/622 + +### New Contributors + +- @shenmishajing made their first contribution in https://github.com/open-mmlab/mmengine/pull/618 +- @Xiangxu-0103 made their first contribution in https://github.com/open-mmlab/mmengine/pull/596 +- @Tau-J made their first contribution in https://github.com/open-mmlab/mmengine/pull/516 +- @wangjiangben-hw made their first contribution in https://github.com/open-mmlab/mmengine/pull/572 +- @triple-Mu made their first contribution in https://github.com/open-mmlab/mmengine/pull/644 +- @sanbuphy made their first contribution in https://github.com/open-mmlab/mmengine/pull/648 +- @Z-Fran made their first contribution in https://github.com/open-mmlab/mmengine/pull/639 +- @BIGWangYuDong made their first contribution in https://github.com/open-mmlab/mmengine/pull/556 +- @zengyh1900 made their first contribution in https://github.com/open-mmlab/mmengine/pull/659 + +## v0.2.0 (11/10/2022) + +### New Features & Enhancements + +- Add SMDDP backend and support running on AWS by @austinmw in https://github.com/open-mmlab/mmengine/pull/579 +- Refactor `FileIO` but without breaking bc by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/533 +- Add test time augmentation base model by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/538 +- Use `torch.lerp\_()` to speed up EMA by @RangiLyu in https://github.com/open-mmlab/mmengine/pull/519 +- Support converting `BN` to `SyncBN` by config by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/506 +- Support defining metric name in wandb backend by @okotaku in https://github.com/open-mmlab/mmengine/pull/509 +- Add dockerfile by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/347 + +### Docs + +- Fix API files of English documentation by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/525 +- Fix typo in `instance_data.py` by @Dai-Wenxun in https://github.com/open-mmlab/mmengine/pull/530 +- Fix the docstring of the model sub-package by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/573 +- Fix a spelling error in docs/zh_cn by @cxiang26 in https://github.com/open-mmlab/mmengine/pull/548 +- Fix typo in docstring by @MengzhangLI in https://github.com/open-mmlab/mmengine/pull/527 +- Update `config.md` by @Zhengfei-0311 in https://github.com/open-mmlab/mmengine/pull/562 + +### Bug Fixes + +- Fix `LogProcessor` does not smooth loss if the name of loss doesn't start with `loss` by @liuyanyi in + https://github.com/open-mmlab/mmengine/pull/539 +- Fix failed to enable `detect_anomalous_params` in `MMSeparateDistributedDataParallel` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/588 +- Fix CheckpointHook behavior unexpected if given `filename_tmpl` argument by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/518 +- Fix error argument sequence in `FSDP` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/520 +- Fix uploading image in wandb backend @okotaku in https://github.com/open-mmlab/mmengine/pull/510 +- Fix loading state dictionary in `EMAHook` by @okotaku in https://github.com/open-mmlab/mmengine/pull/507 +- Fix circle import in `EMAHook` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/523 +- Fix unit test could fail caused by `MultiProcessTestCase` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/535 +- Remove unnecessary "if statement" in `Registry` by @MambaWong in https://github.com/open-mmlab/mmengine/pull/536 +- Fix `_save_to_state_dict` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/542 +- Support comparing NumPy array dataset meta in `Runner.resume` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/511 +- Use `get` instead of `pop` to dump `runner_type` in `build_runner_from_cfg` by @nijkah in https://github.com/open-mmlab/mmengine/pull/549 +- Upgrade pre-commit hooks by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/576 +- Delete the error comment in `registry.md` by @vansin in https://github.com/open-mmlab/mmengine/pull/514 +- Fix Some out-of-date unit tests by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/586 +- Fix typo in `MMFullyShardedDataParallel` by @yhna940 in https://github.com/open-mmlab/mmengine/pull/569 +- Update Github Action CI and CircleCI by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/512 +- Fix unit test in windows by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/515 +- Fix merge ci & multiprocessing unit test by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/529 + +### New Contributors + +- @okotaku made their first contribution in https://github.com/open-mmlab/mmengine/pull/510 +- @MengzhangLI made their first contribution in https://github.com/open-mmlab/mmengine/pull/527 +- @MambaWong made their first contribution in https://github.com/open-mmlab/mmengine/pull/536 +- @cxiang26 made their first contribution in https://github.com/open-mmlab/mmengine/pull/548 +- @nijkah made their first contribution in https://github.com/open-mmlab/mmengine/pull/549 +- @Zhengfei-0311 made their first contribution in https://github.com/open-mmlab/mmengine/pull/562 +- @austinmw made their first contribution in https://github.com/open-mmlab/mmengine/pull/579 +- @yhna940 made their first contribution in https://github.com/open-mmlab/mmengine/pull/569 +- @liuyanyi made their first contribution in https://github.com/open-mmlab/mmengine/pull/539 diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/hook.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/hook.md new file mode 100644 index 0000000000000000000000000000000000000000..d17286ba86d2af440a19b11add639b217347773f --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/hook.md @@ -0,0 +1,254 @@ +# Hook + +Hook programming is a programming pattern in which a mount point is set in one or more locations of a program. When the program runs to a mount point, all methods registered to it at runtime are automatically called. Hook programming can increase the flexibility and extensibility of the program, since users can register custom methods to the mount point to be called without modifying the code in the program. + +## Built-in Hooks + +MMEngine encapsules many ultilities as built-in hooks. These hooks are divided into two categories, namely default hooks and custom hooks. The former refers to those registered with the [Runner](mmengine.runner.Runner) by default, while the latter refers to those registered by the user on demand. + +Each hook has a corresponding priority. At each mount point, hooks with higher priority are called earlier by the `Runner`. When sharing the same priority, the hooks are called in their registration order. The priority list is as follows. + +- HIGHEST (0) +- VERY_HIGH (10) +- HIGH (30) +- ABOVE_NORMAL (40) +- NORMAL (50) +- BELOW_NORMAL (60) +- LOW (70) +- VERY_LOW (90) +- LOWEST (100) + +**default hooks** + +| Name | Function | Priority | +| :-----------------------------------------: | :------------------------------------------------------------------------------------------------------------------: | :---------------: | +| [RuntimeInfoHook](#runtimeinfohook) | update runtime information into message hub | VERY_HIGH (10) | +| [IterTimerHook](#itertimerhook) | Update the time spent during iteration into message hub | NORMAL (50) | +| [DistSamplerSeedHook](#distsamplerseedhook) | Ensure distributed Sampler shuffle is active | NORMAL (50) | +| [LoggerHook](#loggerhook) | Collect logs from different components of `Runner` and write them to terminal, JSON file, tensorboard and wandb .etc | BELOW_NORMAL (60) | +| [ParamSchedulerHook](#paramschedulerhook) | update some hyper-parameters of optimizer | LOW (70) | +| [CheckpointHook](#checkpointhook) | Save checkpoints periodically | VERY_LOW (90) | + +**custom hooks** + +| Name | Function | Priority | +| :---------------------------------: | :----------------------------------------------------------------------: | :---------: | +| [EMAHook](#emahook) | apply Exponential Moving Average (EMA) on the model during training | NORMAL (50) | +| [EmptyCacheHook](#emptycachehook) | Releases all unoccupied cached GPU memory during the process of training | NORMAL (50) | +| [SyncBuffersHook](#syncbuffershook) | Synchronize model buffers at the end of each epoch | NORMAL (50) | + +```{note} +It is not recommended to modify the priority of the default hooks, as hooks with lower priority may depend on hooks with higher priority. For example, `CheckpointHook` needs to have a lower priority than ParamSchedulerHook so that the saved optimizer state is correct. Also, the priority of custom hooks defaults to `NORMAL (50)`. +``` + +The two types of hooks are set differently in the Runner, with the configuration of default hooks being passed to the `default_hooks` parameter of the Runner and the configuration of custom hooks being passed to the `custom_hooks` parameter, as follows. + +```python +from mmengine.runner import Runner +default_hooks = dict( + runtime_info=dict(type='RuntimeInfoHook'), + timer=dict(type='IterTimerHook'), + sampler_seed=dict(type='DistSamplerSeedHook'), + logger=dict(type='LoggerHook'), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', interval=1), +) +custom_hooks = [dict(type='EmptyCacheHook')] +runner = Runner(default_hooks=default_hooks, custom_hooks=custom_hooks, ...) +runner.train() +``` + +### CheckpointHook + +[CheckpointHook](mmengine.hooks.CheckpointHook) saves the checkpoints at a given interval. In the case of distributed training, only the master process will save the checkpoints. The main features of `CheckpointHook` is as follows. + +- Save checkpoints by interval, and support saving them by epoch or iteration +- Save the most recent checkpoints +- Save the best checkpoints +- Specify the path to save the checkpoints + +For more features, please read the [CheckpointHook API documentation](mmengine.hooks.CheckpointHook). + +The four features mentioned above are described below. + +- Save checkpoints by interval, and support saving them by epoch or iteration + + Suppose we train a total of 20 epochs and want to save the checkpoints every 5 epochs, the following configuration will help us achieve this requirement. + + ```python + # the default value of by_epoch is True + default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, by_epoch=True)) + ``` + + If you want to save checkpoints by iteration, you can set `by_epoch` to False and `interval=5` to save them every 5 iterations. + + ```python + default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, by_epoch=False)) + ``` + +- Save the most recent checkpoints + + If you only want to keep a certain number of checkpoints, you can set the `max_keep_ckpts` parameter. When the number of checkpoints saved exceeds `max_keep_ckpts`, the previous checkpoints will be deleted. + + ```python + default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, max_keep_ckpts=2)) + ``` + + The above config shows that if a total of 20 epochs are trained, the model will be saved at epochs 5, 10, 15, and 20, but the checkpoint `epoch_5.pth` will be deleted at epoch 15, and at epoch 20 the checkpoint `epoch_10.pth` will be deleted, so that only the `epoch_15.pth` and `epoch_20.pth` will be saved. + +- Save the best checkpoints + + If you want to save the best checkpoints of the validation set for the training process, you can set the `save_best` parameter. If set to `'auto'`, the current checkpoint are judged to be best based on the first evaluation metric of the validation set (the evaluation metrics returned by evaluator are an ordered dictionary). + + ```python + default_hooks = dict(checkpoint=dict(type='CheckpointHook', save_best='auto')) + ``` + + You can also directly specify the value of `save_best` as the evaluation metric, for example, in a classification task, you can specify `save_best='top-1'`, then the current checkpoint will be judged as best based on the value of `'top-1'`. + + In addition to the `save_best` parameter, other parameters related to saving the best checkpoint are `rule`, `greater_keys` and `less_keys`, which are used to imply whether its good to have large value or not. For example, if you specify `save_best='top-1'`, you can specify `rule='greater'` to imply that the larger the value, the better the checkpoint. + +- Specify the path to save the checkpoints + + The checkpoints are saved in `work_dir` by default, but the path can be changed by setting `out_dir`. + + ```python + default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, out_dir='/path/of/directory')) + ``` + +[LoggerHook](mmengine.hooks.LoggerHook) collects logs from different components of `Runner` and write them to terminal, JSON file, tensorboard and wandb .etc. + +If we want to output (or save) the logs every 20 iterations, we can set the `interval` parameter and configure it as follows. + +```python +default_hooks = dict(logger=dict(type='LoggerHook', interval=20)) +``` + +If you are interested in how MMEngine manages logging, you can refer to [logging](../advanced_tutorials/logging.md). + +### ParamSchedulerHook + +[ParamSchedulerHook](mmengine.hooks.ParamSchedulerHook) iterates through all optimizer parameter schedulers of the Runner and calls their `step` method to update the optimizer parameters in order. See [Parameter Schedulers](param_scheduler.md) for more details about what are parameter schedulers. + +`ParamSchedulerHook` is registered to the Runner by default and has no configurable parameters, so there is no need to configure it. + +### IterTimerHook + +[IterTimerHook](mmengine.hooks.IterTimerHook) is used to record the time taken to load data and iterate once. + +`IterTimerHook` is registered to the Runner by default and has no configurable parameters, so there is no need to configure it. + +### DistSamplerSeedHook + +[DistSamplerSeedHook](mmengine.hooks.DistSamplerSeedHook) calls the `step` method of the Sampler during distributed training to ensure that the shuffle operation takes effect. + +`DistSamplerSeedHook` is registered to the Runner by default and has no configurable parameters, so there is no need to configure it. + +### RuntimeInfoHook + +[RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook) will update the current runtime information (e.g. epoch, iter, max_epochs, max_iters, lr, metrics, etc.) to the message hub at different mount points in the Runner so that other modules without access to the Runner can obtain this information. + +`RuntimeInfoHook` is registered to the Runner by default and has no configurable parameters, so there is no need to configure it. + +### EMAHook + +[EMAHook](mmengine.hooks.EMAHook) performs an exponential moving average operation on the model during training, with the aim of improving the robustness of the model. Note that the model generated by exponential moving average is only used for validation and testing, and does not affect training. + +```python +custom_hooks = [dict(type='EMAHook')] +runner = Runner(custom_hooks=custom_hooks, ...) +runner.train() +``` + +`EMAHook` uses [ExponentialMovingAverage](mmengine.model.ExponentialMovingAverage) by default, with optional values of [StochasticWeightAverage](mmengine.model.StochasticWeightAverage) and [MomentumAnnealingEMA](mmengine.model.MomentumAnnealingEMA). Other averaging strategies can be used by setting `ema_type`. + +```python +custom_hooks = [dict(type='EMAHook', ema_type='StochasticWeightAverage')] +``` + +See [EMAHook API Reference](mmengine.hooks.EMAHook) for more usage. + +### EmptyCacheHook + +[EmptyCacheHook](mmengine.hooks.EmptyCacheHook) calls `torch.cuda.empty_cache()` to release all unoccupied cached GPU memory. The timing of releasing memory can be controlled by setting parameters like `before_epoch`, `after_iter`, and `after_epoch`, meaning before the start of each epoch, after each iteration, and after each epoch respectively. + +```python +# The release operation is performed at the end of each epoch +custom_hooks = [dict(type='EmptyCacheHook', after_epoch=True)] +runner = Runner(custom_hooks=custom_hooks, ...) +runner.train() +``` + +### SyncBuffersHook + +[SyncBuffersHook](mmengine.hooks.SyncBuffersHook) synchronizes the buffer of the model at the end of each epoch during distributed training, e.g. `running_mean` and `running_var` of the BN layer. + +```python +custom_hooks = [dict(type='SyncBuffersHook')] +runner = Runner(custom_hooks=custom_hooks, ...) +runner.train() +``` + +## Customize Your Hooks + +If the built-in hooks provided by MMEngine do not cover your demands, you are encouraged to customize your own hooks by simply inheriting the base [hook](mmengine.hooks.Hook) class and overriding the corresponding mount point methods. + +For example, if you want to check whether the loss value is valid, i.e. not infinite, during training, you can simply override the `after_train_iter` method as below. The check will be performed after each training iteration. + +```python +import torch +from mmengine.registry import HOOKS +from mmengine.hooks import Hook +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + """Check invalid loss hook. + This hook will regularly check whether the loss is valid + during training. + Args: + interval (int): Checking interval (every k iterations). + Defaults to 50. + """ + def __init__(self, interval=50): + self.interval = interval + def after_train_iter(self, runner, batch_idx, data_batch=None, outputs=None): + """All subclasses should override this method, if they need any + operations after each training iteration. + Args: + runner (Runner): The runner of the training process. + batch_idx (int): The index of the current batch in the train loop. + data_batch (dict or tuple or list, optional): Data from dataloader. + outputs (dict, optional): Outputs from model. + """ + if self.every_n_train_iters(runner, self.interval): + assert torch.isfinite(outputs['loss']),\ + runner.logger.info('loss become infinite or NaN!') +``` + +We simply pass the hook config to the `custom_hooks` parameter of the Runner, which will register the hooks when the Runner is initialized. + +```python +from mmengine.runner import Runner +custom_hooks = dict( + dict(type='CheckInvalidLossHook', interval=50) +) +runner = Runner(custom_hooks=custom_hooks, ...) +runner.train() # start training +``` + +Then the loss value are checked after iteration. + +Note that the priority of the custom hook is `NORMAL (50)` by default, if you want to change the priority of the hook, then you can set the priority key in the config. + +```python +custom_hooks = dict( + dict(type='CheckInvalidLossHook', interval=50, priority='ABOVE_NORMAL') +) +``` + +You can also set priority when defining classes. + +```python +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + priority = 'ABOVE_NORMAL' +``` diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/model.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/model.md new file mode 100644 index 0000000000000000000000000000000000000000..adcaacc85797e8e3383ac64ad5c511ea83b354e1 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/model.md @@ -0,0 +1,208 @@ +# Model + +## Runner and model + +As mentioned in [basic dataflow](./runner.md#bassic-dataflow), the dataflow between DataLoader, model and evaluator follows some rules. Don't remember clearly? Let's review it: + +```python +# Training process +for data_batch in train_dataloader: + data_batch = model.data_preprocessor(data_batch, training=True) + if isinstance(data_batch, dict): + losses = model(**data_batch, mode='loss') + elif isinstance(data_batch, (list, tuple)): + losses = model(*data_batch, mode='loss') + else: + raise TypeError() +# Validation process +for data_batch in val_dataloader: + data_batch = model.data_preprocessor(data_batch, training=False) + if isinstance(data_batch, dict): + outputs = model(**data_batch, mode='predict') + elif isinstance(data_batch, (list, tuple)): + outputs = model(**data_batch, mode='predict') + else: + raise TypeError() + evaluator.process(data_samples=outputs, data_batch=data_batch) +metrics = evaluator.evaluate(len(val_dataloader.dataset)) +``` + +In [runner tutorial](../tutorials/runner.md), we simply mentioned the relationship between DataLoader, model and evaluator, and introduced the concept of `data_preprocessor`. You may have a certain understanding of the model. However, during the running of Runner, the situation is far more complex than the above pseudo-code. + +In order to focus your attention on the algorithm itself, and ignore the complex relationship between the model, DataLoader and evaluator, we designed [BaseModel](mmengine.model.BaseModel). In most cases, the only thing you need to do is to make your model inherit from `BaseModel`, and implement the `forward` as required to perform the training, testing, and validation process. + +Before continuing reading the model tutorial, let's throw out two questions that we hope you will find the answers after reading the model tutorial: + +1. When do we update the parameters of model? and how to update the parameters by a custom optimization process? +2. Why is the concept of data_preprocessor necessary? What functions can it perform? + +## Interface introduction + +Usually, we should define a model to implement the body of the algorithm. In MMEngine, model will be managed by Runner, and need to implement some interfaces, such as `train_step`, `val_step`, and `test_step`. For high-level tasks like detection, classification, and segmentation, the interfaces mentioned above commonly implement a standard workflow. For example, `train_step` will calculate the loss and update the parameters of the model, and `val_step`/`test_step` will calculate the metrics and return the predictions. Therefore, MMEnine abstracts the [BaseModel](mmengine.model.BaseModel) to implement the common workflow. + +Benefits from the `BaseModel`, we only need to make the model inherit from `BaseModel`, and implement the `forward` function to perform the training, testing, and validation process. + +```{note} +BaseModel inherits from [BaseModule](../advanced_tutorials/initialize.md),which can be used to initialize the model parameters dynamically. +``` + +[**forward**](mmengine.model.BaseModel.forward): The arguments of `forward` need to match with the data given by [DataLoader](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html). If the DataLoader samples a tuple `data`, `forward` needs to accept the value of unpacked `*data`. If DataLoader returns a dict `data`, `forward` needs to accept the key-value of unpacked `**data`. `forward` also accepts `mode` parameter, which is used to control the running branch: + +- `mode='loss'`: `loss` mode is enabled in training process, and `forward` returns a differentiable loss `dict`. Each key-value pair in loss `dict` will be used to log the training status and optimize the parameters of model. This branch will be called by `train_step` + +- `mode='predict'`: `predict` mode is enabled in validation/testing process, and `forward` will return predictions, which matches with arguments of [process](mmengine.evaluator.Evaluator.process). Repositories of OpenMMLab have a more strict rules. The predictions must be a list and each element of it must be a [BaseDataElement](../advanced_tutorials/data_element.md). This branch will be called by `val_step` + +- `mode='tensor'`: In `tensor` and `predict` modes, `forward` will return the predictions. The difference is that `forward` will return a `tensor` or a container or `tensor` which has not been processed by a series of post-process methods, such as non-maximum suppression (NMS). You can customize your post-process method after getting the result of `tensor` mode. + +[**train_step**](mmengine.model.BaseModel.train_step): Get the loss `dict` by calling `forward` with `loss` mode. `BaseModel` implements a standard optimization process as follows: + +```python +def train_step(self, data, optim_wrapper): + # See details in the next section + data = self.data_preprocessor(data, training=True) + # `loss` mode, return a loss dict. Actually train_step accepts + # both tuple dict input, and unpack it with ** or * + loss = self(**data, mode='loss') + # Parse the loss dict and return the parsed losses for optimization + # and log_vars for logging + parsed_losses, log_vars = self.parse_losses() + optim_wrapper.update_params(parsed_losses) # 更新参数 + return log_vars +``` + +[**val_step**](mmengine.model.BaseModel.val_step): Get the predictions by calling `forward` with `predict` mode. + +```python +def val_step(self, data, optim_wrapper): + data = self.data_preprocessor(data, training=False) + outputs = self(**data, mode='predict') + return outputs +``` + +[**test_step**](mmengine.model.BaseModel.test_step): There is no difference between `val_step` and `test_step` in `BaseModel`. But we can customize it in the subclasses, for example, you can get validation loss in `val_step`. + +Understand the interfaces of `BaseModel`, now we are able to come up with a more complete pseudo-code: + +```python +# training +for data_batch in train_dataloader: + loss_dict = model.train_step(data_batch) +# validation +for data_batch in val_dataloader: + preds = model.test_step(data_batch) + evaluator.process(data_samples=outputs, data_batch=data_batch) +metrics = evaluator.evaluate(len(val_dataloader.dataset)) +``` + +Great!, ignoring `Hook`, the pseudo-code above almost implements the main logic in [loop](mmengine.runner.EpochBasedTrainLoop)! Let's go back to [15 minutes to get started with MMEngine](../get_started/15_minutes.md), we may truly understand what `MMResNet` has done: + +```python +import torch.nn.functional as F +import torchvision +from mmengine.model import BaseModel + +class MMResNet50(BaseModel): + def __init__(self): + super().__init__() + self.resnet = torchvision.models.resnet50() + + def forward(self, imgs, labels, mode): + x = self.resnet(imgs) + if mode == 'loss': + return {'loss': F.cross_entropy(x, labels)} + elif mode == 'predict': + return x, labels + + # train_step, val_step and test_step have been implemented in BaseModel. + # We list the equivalent code here for better understanding + def train_step(self, data, optim_wrapper): + data = self.data_preprocessor(data) + loss = self(*data, mode='loss') + parsed_losses, log_vars = self.parse_losses() + optim_wrapper.update_params(parsed_losses) + return log_vars + + def val_step(self, data, optim_wrapper): + data = self.data_preprocessor(data) + outputs = self(*data, mode='predict') + return outputs + + def test_step(self, data, optim_wrapper): + data = self.data_preprocessor(data) + outputs = self(*data, mode='predict') + return outputs +``` + +Now, you may have a deeper understanding of dataflow, and can answer the first question in [Runner and model](#runner-and-model). + +`BaseModel.train_step` implements the standard optimization, and if we want to customize a new optimization process, we can override it in the subclass. However, it is important to note that we need to make sure that `train_step` returns a loss dict. + +## DataPreprocessor + +If your computer is equipped with a GPU (or other hardware that can accelerate training, such as MPS, IPU, etc.), when you run the [15 minutes tutorial](../get_started/15_minutes.md), you will see that the program is running on the GPU, but, when does `MMEngine` move the data and model from the CPU to the GPU? + +In fact, the Runner will move the model to the specified device during the construction, while the data will be moved to the specified device at the `self.data_preprocessor(data)` mentioned in the code snippet of the previous section. The moved data will be further passed to the model. + +Makes sense but it's weird, isn't it? At this point you may be wondering: + +1. `MMResNet50` does not define `data_preprocessor`, but why it can still access `data_preprocessor` and move data to GPU? + +2. Why `BaseModel` does not move data by `data = data.to(device)`, but needs the `DataPreprocessor` to move data? + +The answer to the first question is that: `MMResNet50` inherit from `BaseModel`, and `super().__init__` will build a default `data_preprocessor` for it. The equivalent implementation of the default one is like this: + +```python +class BaseDataPreprocessor(nn.Module): + def forward(self, data, training=True): # ignore the training parameter here + # suppose data given by CIFAR10 is a tuple. Actually + # BaseDataPreprocessor could move various type of data + # to target device. + return tuple(_data.cuda() for _data in data) +``` + +`BaseDataPreprocessor` will move the data to the specified device. + +Before answering the second question, let's think about a few more questions + +1. Where should we perform normalization? [transform](../advanced_tutorials/data_transform.md) or `Model`? + + It sounds reasonable to put it in transform to take advantage of Dataloader's multi-process acceleration, and in the model to move it to GPU to use GPU resources to accelerate normalization. However, while we are debating whether CPU normalization is faster than GPU normalization, the time of data moving from CPU to GPU is much longer than the former. + + In fact, for less computationally intensive operations like normalization, it takes much less time than data transferring, which has a higher priority for being optimized. If I could move the data to the specified device while it is still in `uint8` and before it is normalized (the size of normalized `float` data is 4 times larger than that of unit8), it would reduce the bandwidth and greatly improve the efficiency of data transferring. This "lagged" normalization behavior is one of the main reasons why we designed the `DataPreprocessor`. The data preprocessor moves the data first and then normalizes it. + +2. How we implement the data augmentation like MixUp and Mosaic? + + Although it seems that MixUp and Mosaic are just special data transformations that should be implemented in transform. However, considering that these two transformations involve **fusing multiple images into one**, it would be very difficult to implement them in transform since the current paradigm of transform is to do various enhancements on **one** image. It would be hard to read additional images from dataset because the dataset is not accessible in the transform. However, if we implement Mosaic or Mixup based on the `batch_data` sampled from Dataloader, everything becomes easy. We can access multiple images at the same time, and we can easily perform the image fusion operation. + + ```python + class MixUpDataPreprocessor(nn.Module): + def __init__(self, num_class, alpha): + self.alpha = alpha + + def forward(self, data, training=True): + data = tuple(_data.cuda() for _data in data) + # Only perform MixUp in training mode + if not training: + return data + + label = F.one_hot(label) # label to OneHot + batch_size = len(label) + index = torch.randperm(batch_size) # Get the index of fused image + img, label = data + lam = np.random.beta(self.alpha, self.alpha) # Fusion factor + + # MixUp + img = lam * img + (1 - lam) * img[index, :] + label = lam * batch_scores + (1 - lam) * batch_scores[index, :] + # Since the returned label is onehot encoded, the `forward` of the + # model should also be adjusted. + return tuple(img, label) + ``` + + Therefore, besides data transferring and normalization, another major function of `data_preprocessor` is BatchAugmentation. The modularity of the data preprocessor also helps us to achieve a free combination between algorithms and data augmentation. + +3. What should we do if the data sampled from the DataLoader does not match the model input, should I modify the DataLoader or the model interface? + + The answer is: neither is appropriate. The ideal solution is to do the adaptation without breaking the existing interface between the model and the DataLoader. `DataPreprocessor` could also handle this, you can customize your `DataPreprocessor` to convert the incoming to the target type. + +By now, You must understand the rationale of the data preprocessor and can confidently answer the two questions posed at the beginning of the tutorial! But you may still wonder what is the `optim_wrapper` passed to `train_step`, and how do the predictions returned by `test_step` and `val_step` relate to the evaluator. You will find more introduction in the [evaluation tutorial](./evaluation.md) and the [optimizer wrapper tutorial](./optim_wrapper.md). diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/optim_wrapper.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/optim_wrapper.md new file mode 100644 index 0000000000000000000000000000000000000000..9cb05b3b2411ff5e9076759ce83c5c51332307f3 --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/optim_wrapper.md @@ -0,0 +1,503 @@ +# OptimWrapper + +In previous tutorials of [runner](./runner.md) and [model](./model.md), we have more or less mentioned the concept of `OptimWrapper`, but we have not introduced why we need it and what are the advantages of `OptimWrapper` compared to Pytorch's native optimizer. In this tutorial, we will help you understand the advantages and demonstrate how to use the wrapper. + +As its name suggests, `OptimWrapper` is a high-level abstraction of PyTorch's native optimizer, which provides a unified set of interfaces while adding more functionality. `OptimWrapper` supports different training strategies, including mixed precision training, gradient accumulation, and gradient clipping. We can choose the appropriate training strategy according to our needs. `OptimWrapper` also defines a standard process for parameter updating based on which users can switch between different training strategies for the same set of code. + +## OptimWrapper vs Optimizer + +Now we use both the native optimizer of PyTorch and the OptimWrapper in MMEngine to perform single-precision training, mixed-precision training, and gradient accumulation to show the difference in implementations. + +### Model training + +**1.1 Single-precision training with SGD in PyTorch** + +```python +import torch +from torch.optim import SGD +import torch.nn as nn +import torch.nn.functional as F + +inputs = [torch.zeros(10, 1, 1)] * 10 +targets = [torch.ones(10, 1, 1)] * 10 +model = nn.Linear(1, 1) +optimizer = SGD(model.parameters(), lr=0.01) +optimizer.zero_grad() + +for input, target in zip(inputs, targets): + output = model(input) + loss = F.l1_loss(output, target) + loss.backward() + optimizer.step() + optimizer.zero_grad() +``` + +**1.2 Single-precision training with OptimWrapper in MMEngine** + +```python +from mmengine.optim import OptimWrapper + +optim_wrapper = OptimWrapper(optimizer=optimizer) + +for input, target in zip(inputs, targets): + output = model(input) + loss = F.l1_loss(output, target) + optim_wrapper.update_params(loss) +``` + +![image](https://user-images.githubusercontent.com/57566630/185605436-17f08083-b219-4b38-b714-eb891f7a8e56.png) + +The `OptimWrapper.update_params` achieves the standard process for gradient computation, parameter updating, and gradient zeroing, which can be used to update the model parameters directly. + +**2.1 Mixed-precision training with SGD in PyTorch** + +```python +from torch.cuda.amp import autocast + +model = model.cuda() +inputs = [torch.zeros(10, 1, 1, 1)] * 10 +targets = [torch.ones(10, 1, 1, 1)] * 10 + +for input, target in zip(inputs, targets): + with autocast(): + output = model(input.cuda()) + loss = F.l1_loss(output, target.cuda()) + loss.backward() + optimizer.step() + optimizer.zero_grad() +``` + +**2.2 Mixed-precision training with OptimWrapper in MMEngine** + +```python +from mmengine.optim import AmpOptimWrapper + +optim_wrapper = AmpOptimWrapper(optimizer=optimizer) + +for input, target in zip(inputs, targets): + with optim_wrapper.optim_context(model): + output = model(input.cuda()) + loss = F.l1_loss(output, target.cuda()) + optim_wrapper.update_params(loss) +``` + +![image](https://user-images.githubusercontent.com/57566630/185606060-2fdebd90-c17a-4a8c-aaf1-540d47975c59.png) + +To enable mixed precision training, users need to use `AmpOptimWrapper.optim_context` which is similar to the `autocast` for enabling the context for mixed precision training. In addition, `AmpOptimWrapper.optim_context` can accelerate the gradient accumulation during the distributed training, which will be introduced in the next example. + +**3.1 Mixed-precision training and gradient accumulation with SGD in PyTorch** + +```python +for idx, (input, target) in enumerate(zip(inputs, targets)): + with autocast(): + output = model(input.cuda()) + loss = F.l1_loss(output, target.cuda()) + loss.backward() + if idx % 2 == 0: + optimizer.step() + optimizer.zero_grad() +``` + +**3.2 Mixed-precision training and gradient accumulation with OptimWrapper in MMEngine** + +```python +optim_wrapper = AmpOptimWrapper(optimizer=optimizer, accumulative_counts=2) + +for input, target in zip(inputs, targets): + with optim_wrapper.optim_context(model): + output = model(input.cuda()) + loss = F.l1_loss(output, target.cuda()) + optim_wrapper.update_params(loss) +``` + +![image](https://user-images.githubusercontent.com/57566630/185608932-91a082d4-1bf4-4329-b283-98fbbc20b5f7.png) + +We only need to configure the `accumulative_counts` parameter and call the `update_params` interface to achieve the gradient accumulation function. Besides, in the distributed training scenario, if we configure the gradient accumulation with `optim_context` context enabled, we can avoid unnecessary gradient synchronization during the gradient accumulation step. + +The OptimWrapper also provides a more fine-grained interface for users to customize with their own parameter update logics. + +- `backward`: Accept a `loss` dictionary, and compute the gradient of parameters. +- `step`: Same as `optimizer.step`, and update the parameters. +- `zero_grad`: Same as `optimizer.zero_grad`, and zero the gradient of parameters + +We can use the above interface to implement the same logic of parameters updating as the Pytorch optimizer. + +```python +for idx, (input, target) in enumerate(zip(inputs, targets)): + optimizer.zero_grad() + with optim_wrapper.optim_context(model): + output = model(input.cuda()) + loss = F.l1_loss(output, target.cuda()) + optim_wrapper.backward(loss) + if idx % 2 == 0: + optim_wrapper.step() + optim_wrapper.zero_grad() +``` + +We can also configure a gradient clipping strategy for the OptimWrapper. + +```python +# based on torch.nn.utils.clip_grad_norm_ method +optim_wrapper = AmpOptimWrapper( + optimizer=optimizer, clip_grad=dict(max_norm=1)) + +# based on torch.nn.utils.clip_grad_value_ method +optim_wrapper = AmpOptimWrapper( + optimizer=optimizer, clip_grad=dict(clip_value=0.2)) +``` + +### Get learning rate/momentum + +The OptimWrapper provides the `get_lr` and `get_momentum` for the convenience of getting the learning rate and momentum of the first parameter group in the optimizer. + +```python +import torch.nn as nn +from torch.optim import SGD + +from mmengine.optim import OptimWrapper + +model = nn.Linear(1, 1) +optimizer = SGD(model.parameters(), lr=0.01) +optim_wrapper = OptimWrapper(optimizer) + +print(optimizer.param_groups[0]['lr']) # 0.01 +print(optimizer.param_groups[0]['momentum']) # 0 +print(optim_wrapper.get_lr()) # {'lr': [0.01]} +print(optim_wrapper.get_momentum()) # {'momentum': [0]} +``` + +``` +0.01 +0 +{'lr': [0.01]} +{'momentum': [0]} +``` + +### Export/load state dicts + +Similar to the optimizer, the OptimWrapper provides the `state_dict` and `load_state_dict` interfaces for exporting and loading the optimizer states. For the `AmpOptimWrapper`, it can export mixed-precision training parameters as well. + +```python +import torch.nn as nn +from torch.optim import SGD +from mmengine.optim import OptimWrapper, AmpOptimWrapper + +model = nn.Linear(1, 1) +optimizer = SGD(model.parameters(), lr=0.01) + +optim_wrapper = OptimWrapper(optimizer=optimizer) +amp_optim_wrapper = AmpOptimWrapper(optimizer=optimizer) + +# export state dicts +optim_state_dict = optim_wrapper.state_dict() +amp_optim_state_dict = amp_optim_wrapper.state_dict() + +print(optim_state_dict) +print(amp_optim_state_dict) +optim_wrapper_new = OptimWrapper(optimizer=optimizer) +amp_optim_wrapper_new = AmpOptimWrapper(optimizer=optimizer) + +# load state dicts +amp_optim_wrapper_new.load_state_dict(amp_optim_state_dict) +optim_wrapper_new.load_state_dict(optim_state_dict) +``` + +``` +{'state': {}, 'param_groups': [{'lr': 0.01, 'momentum': 0, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'maximize': False, 'foreach': None, 'params': [0, 1]}]} +{'state': {}, 'param_groups': [{'lr': 0.01, 'momentum': 0, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'maximize': False, 'foreach': None, 'params': [0, 1]}], 'loss_scaler': {'scale': 65536.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2000, '_growth_tracker': 0}} +``` + +### Use multiple optimizers + +Considering that algorithms like GANs usually need to use multiple optimizers to train the generator and the discriminator, MMEngine provides a container class called `OptimWrapperDict` to manage them. `OptimWrapperDict` stores the sub-OptimWrapper in the form of `dict`, and can be accessed and traversed just like a `dict`. + +Unlike regular OptimWrapper, `OptimWrapperDict` does not provide methods such as `update_prarms`, `optim_context`, `backward`, `step`, etc. Therefore, it cannot be used directly to train models. We suggest implementing the logic of parameter updating by accessing the sub-OptimWarpper in `OptimWrapperDict` directly. + +Users may wonder why not just use `dict` to manage multiple optimizers since `OptimWrapperDict` does not have training capabilities. Actually, the core function of `OptimWrapperDict` is to support exporting or loading the state dictionary of all sub-OptimWrapper and to support getting learning rates and momentums as well. Without `OptimWrapperDict`, MMEngine needs to do a lot of `if-else` in OptimWrapper to get the states of the `OptimWrappers`. + +```python +from torch.optim import SGD +import torch.nn as nn + +from mmengine.optim import OptimWrapper, OptimWrapperDict + +gen = nn.Linear(1, 1) +disc = nn.Linear(1, 1) +optimizer_gen = SGD(gen.parameters(), lr=0.01) +optimizer_disc = SGD(disc.parameters(), lr=0.01) + +optim_wapper_gen = OptimWrapper(optimizer=optimizer_gen) +optim_wapper_disc = OptimWrapper(optimizer=optimizer_disc) +optim_dict = OptimWrapperDict(gen=optim_wapper_gen, disc=optim_wapper_disc) + +print(optim_dict.get_lr()) # {'gen.lr': [0.01], 'disc.lr': [0.01]} +print(optim_dict.get_momentum()) # {'gen.momentum': [0], 'disc.momentum': [0]} +``` + +``` +{'gen.lr': [0.01], 'disc.lr': [0.01]} +{'gen.momentum': [0], 'disc.momentum': [0]} +``` + +As shown in the above example, `OptimWrapperDict` exports learning rates and momentums for all OptimWrappers easily, and `OptimWrapperDict` can export and load all the state dicts in a similar way. + +### Configure the OptimWapper in [Runner](runner.md) + +We first need to configure the `optimizer` for the OptimWrapper. MMEngine automatically adds all optimizers in PyTorch to the `OPTIMIZERS` registry, and users can specify the optimizers they need in the form of a `dict`. All supported optimizers in PyTorch are listed [here](https://pytorch.org/docs/stable/optim.html#algorithms). + +Now we take setting up a SGD OptimWrapper as an example. + +```python +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +optim_wrapper = dict(type='OptimWrapper', optimizer=optimizer) +``` + +Here we have set up an OptimWrapper with a SGD optimizer with the learning rate and momentum parameters as specified. Since OptimWrapper is designed for standard single precision training, we can also omit the `type` field in the configuration: + +```python +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +optim_wrapper = dict(optimizer=optimizer) +``` + +To enable mixed-precision training and gradient accumulation, we change `type` to `AmpOptimWrapper` and specify the `accumulative_counts` parameter. + +```python +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +optim_wrapper = dict(type='AmpOptimWrapper', optimizer=optimizer, accumulative_counts=2) +``` + +```{note} +If you are new to reading the MMEngine tutorial and are not familiar with concepts such as [configs](../advanced_tutorials/config.md) and [registries](../advanced_tutorials/registry.md), it is recommended to skip the following advanced tutorials for now and read other documents first. Of course, if you already have a good understanding of this prerequisite knowledge, we highly recommend reading the advanced part which covers: + +1. How to customize the learning rate, decay coefficient, and other parameters of the model parameters in the configuration of OptimWrapper. + +2. how to customize the construction policy of the optimizer. + +Apart from the pre-requisite knowledge of the configs and the registries, it is recommended to have a thorough understanding of the native construction of PyTorch optimizer before starting the advanced tutorials. +``` + +## Advanced usages + +PyTorch's optimizer allows different hyperparameters to be set for each parameter in the model, such as using different learning rates for the backbone and head for a classification model. + +```python +from torch.optim import SGD +import torch.nn as nn + +model = nn.ModuleDict(dict(backbone=nn.Linear(1, 1), head=nn.Linear(1, 1))) +optimizer = SGD([{'params': model.backbone.parameters()}, + {'params': model.head.parameters(), 'lr': 1e-3}], + lr=0.01, + momentum=0.9) +``` + +In the above example, we set a learning rate of 0.01 for the backbone, while another learning rate of 1e-3 for the head. Users can pass a list of dictionaries containing the different parts of the model's parameters and their corresponding hyperparameters to the optimizer, allowing for fine-grained adjustment of the model optimization. + +In MMEngine, the optimizer wrapper constructor allows users to set hyperparameters in different parts of the model directly by setting the `paramwise_cfg` in the configuration file rather than by modifying the code of building the optimizer. + +### Set different hyperparamters for different types of parameters + +The default optimizer wrapper constructor in MMEngine supports setting different hyperparameters for different types of parameters in the model. For example, we can set `norm_decay_mult=0` for `paramwise_cfg` to set the weight decay factor to 0 for the weight and bias of the normalization layer to implement the trick of not decaying the weight of the normalization layer as mentioned in the [Bag of Tricks](https://arxiv.org/abs/1812.01187). + +Here, we set the weight decay coefficient in all normalization layers (`head.bn`) in `ToyModel` to 0 as follows. + +```python +from mmengine.optim import build_optim_wrapper +from collections import OrderedDict + +class ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.backbone = nn.ModuleDict( + dict(layer0=nn.Linear(1, 1), layer1=nn.Linear(1, 1))) + self.head = nn.Sequential( + OrderedDict( + linear=nn.Linear(1, 1), + bn=nn.BatchNorm1d(1))) + + +optim_wrapper = dict( + optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001), + paramwise_cfg=dict(norm_decay_mult=0)) +optimizer = build_optim_wrapper(ToyModel(), optim_wrapper) +``` + +``` +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr=0.01 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr=0.01 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr=0.01 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:weight_decay=0.0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:weight_decay=0.0 +``` + +In addition to configuring the weight decay, `paramwise_cfg` of MMEngine's default optimizer wrapper constructor supports the following hyperparameters as well. + +`lr_mult`: Learning rate for all parameters. + +`decay_mult`: Decay coefficient for all parameters. + +`bias_lr_mult`: Learning rate coefficient of the bias (excluding bias of normalization layer and offset of the deformable convolution). + +`bias_decay_mult`: Weight decay coefficient of the bias (excluding bias of normalization layer and offset of the deformable convolution). + +`norm_decay_mult`: Weight decay coefficient for weights and bias of the normalization layer. + +`flat_decay_mult`: Weight decay coefficient of the one-dimension parameters. + +`dwconv_decay_mult`: Decay coefficient of the depth-wise convolution. + +`bypass_duplicate`: Whether to skip duplicate parameters, default to `False`. + +`dcn_offset_lr_mult`: Learning rate of the deformable convolution. + +### Set different hyperparamters for different model modules + +In addition, as shown in the PyTorch code above, in MMEngine we can also set different hyperparameters for any module in the model by setting `custom_keys` in `paramwise_cfg`. + +If we want to set the learning rate and the decay coefficient to 0 for `backbone.layer0`, and set the learning rate to 0.001 for the rest of the modules in the `backbone`. At the same time, we want to keep all the learning rate to 0.001 for the `head` module. We can do it in this way: + +```python +optim_wrapper = dict( + optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001), + paramwise_cfg=dict( + custom_keys={ + 'backbone.layer0': dict(lr_mult=0, decay_mult=0), + 'backbone': dict(lr_mult=1), + 'head': dict(lr_mult=0.1) + })) +optimizer = build_optim_wrapper(ToyModel(), optim_wrapper) +``` + +``` +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:lr=0.0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:weight_decay=0.0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:lr_mult=0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:decay_mult=0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr=0.0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:weight_decay=0.0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr_mult=0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:decay_mult=0 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:lr=0.01 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:lr_mult=1 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr=0.01 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr_mult=1 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:lr=0.001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:lr_mult=0.1 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr=0.001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr_mult=0.1 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:lr=0.001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:lr_mult=0.1 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:lr=0.001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:weight_decay=0.0001 +08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:lr_mult=0.1 +``` + +The state dictionary of the above model can be printed as the following: + +```python +for name, val in ToyModel().named_parameters(): + print(name) +``` + +``` +backbone.layer0.weight +backbone.layer0.bias +backbone.layer1.weight +backbone.layer1.bias +head.linear.weight +head.linear.bias +head.bn.weight +head.bn.bias +``` + +Each field in `custom_keys` is defined as follows. + +1. `'backbone': dict(lr_mult=1)`: Set the learning rate of the parameter whose name is prefixed with `backbone` to 1. +2. `'backbone.layer0': dict(lr_mult=0, decay_mult=0)`: Set the learning rate of the parameter with the prefix `backbone.layer0` to 0 and the decay coefficient to 0. This configuration has a higher priority than the first one. +3. `'head': dict(lr_mult=0.1)`: Set the learning rate of the parameter whose name is prefixed with `head` to 0.1. + +### Customize optimizer construction policies + +Like other modules in MMEngine, the optimizer wrapper constructor is also managed by the [registry](../advanced_tutorial/registry.md). We can customize the hyperparameter policies by implementing custom optimizer wrapper constructors. + +For example, we can implement an optimizer wrapper constructor called `LayerDecayOptimWrapperConstructor` that automatically set decreasing learning rates for layers of different depths of the model. + +```python +from mmengine.optim import DefaultOptimWrapperConstructor +from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS +from mmengine.logging import print_log + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module(force=True) +class LayerDecayOptimWrapperConstructor(DefaultOptimWrapperConstructor): + + def __init__(self, optim_wrapper_cfg, paramwise_cfg=None): + super().__init__(optim_wrapper_cfg, paramwise_cfg=None) + self.decay_factor = paramwise_cfg.get('decay_factor', 0.5) + + super().__init__(optim_wrapper_cfg, paramwise_cfg) + + def add_params(self, params, module, prefix='' ,lr=None): + if lr is None: + lr = self.base_lr + + for name, param in module.named_parameters(recurse=False): + param_group = dict() + param_group['params'] = [param] + param_group['lr'] = lr + params.append(param_group) + full_name = f'{prefix}.{name}' if prefix else name + print_log(f'{full_name} : lr={lr}', logger='current') + + for name, module in module.named_children(): + chiled_prefix = f'{prefix}.{name}' if prefix else name + self.add_params( + params, module, chiled_prefix, lr=lr * self.decay_factor) + + +class ToyModel(nn.Module): + + def __init__(self) -> None: + super().__init__() + self.layer = nn.ModuleDict(dict(linear=nn.Linear(1, 1))) + self.linear = nn.Linear(1, 1) + + +model = ToyModel() + +optim_wrapper = dict( + optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001), + paramwise_cfg=dict(decay_factor=0.5), + constructor='LayerDecayOptimWrapperConstructor') + +optimizer = build_optim_wrapper(model, optim_wrapper) +``` + +``` +08/23 22:20:26 - mmengine - INFO - layer.linear.weight : lr=0.0025 +08/23 22:20:26 - mmengine - INFO - layer.linear.bias : lr=0.0025 +08/23 22:20:26 - mmengine - INFO - linear.weight : lr=0.005 +08/23 22:20:26 - mmengine - INFO - linear.bias : lr=0.005 +``` + +When `add_params` is called for the first time, the `params` argument is an empty `list` and the `module` is the `ToyModel` instance. Please refer to the [Optimizer Wrapper Constructor Documentation](mmengine.optim.DefaultOptimWrapperConstructor) for detailed explanations on overloading. + +Similarly, if we want to construct multiple optimizers, we also need to implement a custom constructor. + +```python +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class MultipleOptimiWrapperConstructor: + ... +``` + +### Adjust hyperparameters during training + +The hyperparameters in the optimizer can only be set to a fixed value at the time it is constructed, and you cannot adjust parameters such as the learning rate during training by just using the optimizer wrapper. In MMEngine, we have implemented a parameter scheduler that allows the tuning of parameters during training. For the usage of the parameter scheduler, please refer to the [Parameter Scheduler](./param_scheduler.md) diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/config_sgd.py b/testbed/open-mmlab__mmengine/docs/resources/config/config_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..9afaf8e54ee62d58c6308af8e90f7a46e38c6dbf --- /dev/null +++ b/testbed/open-mmlab__mmengine/docs/resources/config/config_sgd.py @@ -0,0 +1 @@ +optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)