hc99 commited on
Commit
d439dc1
·
verified ·
1 Parent(s): 09a3fa9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/matplotlib__matplotlib/.appveyor.yml +107 -0
  2. testbed/matplotlib__matplotlib/.coveragerc +16 -0
  3. testbed/matplotlib__matplotlib/.devcontainer/devcontainer.json +38 -0
  4. testbed/matplotlib__matplotlib/.devcontainer/setup.sh +13 -0
  5. testbed/matplotlib__matplotlib/.flake8 +97 -0
  6. testbed/matplotlib__matplotlib/.git-blame-ignore-revs +14 -0
  7. testbed/matplotlib__matplotlib/.git_archival.txt +4 -0
  8. testbed/matplotlib__matplotlib/.gitattributes +6 -0
  9. testbed/matplotlib__matplotlib/.gitignore +112 -0
  10. testbed/matplotlib__matplotlib/.mailmap +284 -0
  11. testbed/matplotlib__matplotlib/.matplotlib-repo +3 -0
  12. testbed/matplotlib__matplotlib/.meeseeksdev.yml +4 -0
  13. testbed/matplotlib__matplotlib/.pre-commit-config.yaml +53 -0
  14. testbed/matplotlib__matplotlib/CITATION.bib +14 -0
  15. testbed/matplotlib__matplotlib/CITATION.cff +27 -0
  16. testbed/matplotlib__matplotlib/CODE_OF_CONDUCT.md +136 -0
  17. testbed/matplotlib__matplotlib/INSTALL.rst +1 -0
  18. testbed/matplotlib__matplotlib/README.md +73 -0
  19. testbed/matplotlib__matplotlib/SECURITY.md +29 -0
  20. testbed/matplotlib__matplotlib/azure-pipelines.yml +165 -0
  21. testbed/matplotlib__matplotlib/environment.yml +65 -0
  22. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/README.txt +4 -0
  23. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py +122 -0
  24. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axhspan_demo.py +36 -0
  25. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_equal_demo.py +35 -0
  26. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_labels_demo.py +20 -0
  27. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/custom_figure_class.py +52 -0
  28. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/demo_tight_layout.py +134 -0
  29. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/gridspec_nested.py +46 -0
  30. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/multiple_figs_demo.py +51 -0
  31. testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/subplot.py +51 -0
  32. testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/fancytextbox_demo.py +26 -0
  33. testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/mathtext_demo.py +26 -0
  34. testbed/matplotlib__matplotlib/galleries/plot_types/README.rst +11 -0
  35. testbed/matplotlib__matplotlib/galleries/plot_types/stats/hist2d.py +25 -0
  36. testbed/matplotlib__matplotlib/galleries/plot_types/stats/pie.py +26 -0
  37. testbed/matplotlib__matplotlib/galleries/plot_types/stats/violin.py +28 -0
  38. testbed/matplotlib__matplotlib/galleries/users_explain/animations/animations.py +247 -0
  39. testbed/matplotlib__matplotlib/galleries/users_explain/animations/blitting.py +232 -0
  40. testbed/matplotlib__matplotlib/galleries/users_explain/artists/artist_intro.rst +186 -0
  41. testbed/matplotlib__matplotlib/galleries/users_explain/artists/imshow_extent.py +266 -0
  42. testbed/matplotlib__matplotlib/galleries/users_explain/artists/index.rst +23 -0
  43. testbed/matplotlib__matplotlib/galleries/users_explain/artists/paths.py +236 -0
  44. testbed/matplotlib__matplotlib/galleries/users_explain/artists/performance.rst +148 -0
  45. testbed/matplotlib__matplotlib/galleries/users_explain/artists/transforms_tutorial.py +587 -0
  46. testbed/matplotlib__matplotlib/galleries/users_explain/axes/autoscale.py +180 -0
  47. testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_intro.rst +180 -0
  48. testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_ticks.py +275 -0
  49. testbed/matplotlib__matplotlib/galleries/users_explain/axes/colorbar_placement.py +99 -0
  50. testbed/matplotlib__matplotlib/galleries/users_explain/axes/constrainedlayout_guide.py +734 -0
testbed/matplotlib__matplotlib/.appveyor.yml ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # With infos from
2
+ # http://tjelvarolsson.com/blog/how-to-continuously-test-your-python-code-on-windows-using-appveyor/
3
+ # https://packaging.python.org/en/latest/appveyor/
4
+ # https://github.com/rmcgibbo/python-appveyor-conda-example
5
+
6
+ # Backslashes in quotes need to be escaped: \ -> "\\"
7
+ branches:
8
+ except:
9
+ - /auto-backport-.*/
10
+ - /^v\d+\.\d+\.[\dx]+-doc$/
11
+
12
+ skip_commits:
13
+ message: /\[ci doc\]/
14
+ files:
15
+ - doc/
16
+ - galleries/
17
+
18
+ clone_depth: 50
19
+
20
+ image: Visual Studio 2017
21
+
22
+ environment:
23
+
24
+ global:
25
+ PYTHONFAULTHANDLER: 1
26
+ PYTHONIOENCODING: UTF-8
27
+ PYTEST_ARGS: -raR --numprocesses=auto --timeout=300 --durations=25
28
+ --cov-report= --cov=lib --log-level=DEBUG
29
+
30
+ matrix:
31
+ - PYTHON_VERSION: "3.9"
32
+ CONDA_INSTALL_LOCN: "C:\\Miniconda3-x64"
33
+ TEST_ALL: "no"
34
+ - PYTHON_VERSION: "3.10"
35
+ CONDA_INSTALL_LOCN: "C:\\Miniconda3-x64"
36
+ TEST_ALL: "no"
37
+
38
+ # We always use a 64-bit machine, but can build x86 distributions
39
+ # with the PYTHON_ARCH variable
40
+ platform:
41
+ - x64
42
+
43
+ # all our python builds have to happen in tests_script...
44
+ build: false
45
+
46
+ cache:
47
+ - '%LOCALAPPDATA%\pip\Cache'
48
+ - '%USERPROFILE%\.cache\matplotlib'
49
+
50
+ init:
51
+ - echo %PYTHON_VERSION% %CONDA_INSTALL_LOCN%
52
+
53
+ install:
54
+ - set PATH=%CONDA_INSTALL_LOCN%;%CONDA_INSTALL_LOCN%\scripts;%PATH%;
55
+ - conda config --set always_yes true
56
+ - conda config --set show_channel_urls yes
57
+ - conda config --prepend channels conda-forge
58
+
59
+ # For building, use a new environment
60
+ # Add python version to environment
61
+ # `^ ` escapes spaces for indentation
62
+ - echo ^ ^ - python=%PYTHON_VERSION% >> environment.yml
63
+ - conda env create -f environment.yml
64
+ - activate mpl-dev
65
+ - conda install -c conda-forge pywin32
66
+ - echo %PYTHON_VERSION% %TARGET_ARCH%
67
+ # Show the installed packages + versions
68
+ - conda list
69
+
70
+ test_script:
71
+ # Now build the thing..
72
+ - set LINK=/LIBPATH:%cd%\lib
73
+ - pip install -ve .
74
+ # this should show no freetype dll...
75
+ - set "DUMPBIN=%VS140COMNTOOLS%\..\..\VC\bin\dumpbin.exe"
76
+ - '"%DUMPBIN%" /DEPENDENTS lib\matplotlib\ft2font*.pyd | findstr freetype.*.dll && exit /b 1 || exit /b 0'
77
+
78
+ # this are optional dependencies so that we don't skip so many tests...
79
+ - if x%TEST_ALL% == xyes conda install -q ffmpeg inkscape miktex
80
+ # missing packages on conda-forge for imagemagick
81
+ # This install sometimes failed randomly :-(
82
+ #- choco install imagemagick
83
+
84
+ # Test import of tkagg backend
85
+ - python -c "import matplotlib as m; m.use('tkagg'); import matplotlib.pyplot as plt; print(plt.get_backend())"
86
+ # tests
87
+ - echo The following args are passed to pytest %PYTEST_ARGS%
88
+ - pytest %PYTEST_ARGS%
89
+
90
+ artifacts:
91
+ - path: result_images\*
92
+ name: result_images
93
+ type: zip
94
+
95
+ on_finish:
96
+ - conda install codecov
97
+ - codecov -e PYTHON_VERSION PLATFORM
98
+
99
+ on_failure:
100
+ # Generate a html for visual tests
101
+ - python tools/visualize_tests.py --no-browser
102
+ - echo zipping images after a failure...
103
+ - 7z a result_images.zip result_images\ | grep -v "Compressing"
104
+ - appveyor PushArtifact result_images.zip
105
+
106
+ matrix:
107
+ fast_finish: true
testbed/matplotlib__matplotlib/.coveragerc ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ branch = true
3
+ source =
4
+ matplotlib
5
+ mpl_toolkits
6
+ omit = matplotlib/_version.py
7
+
8
+ [report]
9
+ exclude_lines =
10
+ pragma: no cover
11
+ raise NotImplemented
12
+ def __str__
13
+ def __repr__
14
+ if __name__ == .__main__.:
15
+ if TYPE_CHECKING:
16
+ if typing.TYPE_CHECKING:
testbed/matplotlib__matplotlib/.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hostRequirements": {
3
+ "memory": "8gb",
4
+ "cpus": 4
5
+ },
6
+ "image": "mcr.microsoft.com/devcontainers/universal:2",
7
+ "features": {
8
+ "ghcr.io/devcontainers/features/desktop-lite:1": {},
9
+ "ghcr.io/rocker-org/devcontainer-features/apt-packages:1": {
10
+ "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"
11
+ }
12
+ },
13
+ "onCreateCommand": ".devcontainer/setup.sh",
14
+ "postCreateCommand": "",
15
+ "forwardPorts": [6080],
16
+ "portsAttributes": {
17
+ "6080": {
18
+ "label": "desktop"
19
+ }
20
+ },
21
+ "customizations": {
22
+ "vscode": {
23
+ "extensions": [
24
+ "ms-python.python",
25
+ "yy0931.mplstyle",
26
+ "eamodio.gitlens",
27
+ "ms-vscode.live-server"
28
+ ],
29
+ "settings": {}
30
+ },
31
+ "codespaces": {
32
+ "openFiles": [
33
+ "README.md",
34
+ "doc/devel/codespaces.md"
35
+ ]
36
+ }
37
+ }
38
+ }
testbed/matplotlib__matplotlib/.devcontainer/setup.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -e
4
+
5
+ "${SHELL}" <(curl -Ls micro.mamba.pm/install.sh) < /dev/null
6
+
7
+ conda init --all
8
+ micromamba shell init -s bash
9
+ micromamba env create -f environment.yml --yes
10
+ # Note that `micromamba activate mpl-dev` doesn't work, it must be run by the
11
+ # user (same applies to `conda activate`)
12
+ echo "envs_dirs:
13
+ - /home/codespace/micromamba/envs" > /opt/conda/.condarc
testbed/matplotlib__matplotlib/.flake8 ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [flake8]
2
+ max-line-length = 88
3
+ select =
4
+ # flake8 default
5
+ D, E, F, W,
6
+ ignore =
7
+ # flake8 default
8
+ E121,E123,E126,E226,E24,E704,W503,W504,
9
+ # Additional ignores:
10
+ E127, E131,
11
+ E266,
12
+ E305, E306,
13
+ E741,
14
+ F841,
15
+ # pydocstyle
16
+ D100, D101, D102, D103, D104, D105, D106,
17
+ D200, D202, D204, D205,
18
+ D301,
19
+ D400, D401, D403, D404
20
+ # ignored by pydocstyle numpy docstring convention
21
+ D107, D203, D212, D213, D402, D413, D415, D416, D417,
22
+
23
+ exclude =
24
+ .git
25
+ build
26
+ doc/gallery
27
+ doc/tutorials
28
+ # External files.
29
+ tools/gh_api.py
30
+ .tox
31
+ .eggs
32
+
33
+ per-file-ignores =
34
+ setup.py: E402
35
+
36
+ lib/matplotlib/__init__.py: E402, F401
37
+ lib/matplotlib/_animation_data.py: E501
38
+ lib/matplotlib/_api/__init__.py: F401
39
+ lib/matplotlib/_cm.py: E122, E202, E203, E302
40
+ lib/matplotlib/_mathtext.py: E221, E251
41
+ lib/matplotlib/_mathtext_data.py: E122, E203, E261
42
+ lib/matplotlib/axes/__init__.py: F401, F403
43
+ lib/matplotlib/backends/backend_template.py: F401
44
+ lib/matplotlib/font_manager.py: E501
45
+ lib/matplotlib/image.py: F401, F403
46
+ lib/matplotlib/mathtext.py: E221
47
+ lib/matplotlib/pylab.py: F401, F403
48
+ lib/matplotlib/pyplot.py: F401, F811
49
+ lib/matplotlib/tests/test_mathtext.py: E501
50
+ lib/matplotlib/transforms.py: E201, E202, E203
51
+ lib/matplotlib/tri/_triinterpolate.py: E201, E221
52
+ lib/mpl_toolkits/axes_grid1/axes_size.py: E272
53
+ lib/mpl_toolkits/axisartist/__init__.py: F401
54
+ lib/mpl_toolkits/axisartist/angle_helper.py: E221
55
+ lib/pylab.py: F401, F403
56
+
57
+ doc/conf.py: E402
58
+ galleries/users_explain/artists/paths.py: E402
59
+ galleries/users_explain/artists/patheffects_guide.py: E402
60
+ galleries/users_explain/artists/transforms_tutorial.py: E402, E501
61
+ galleries/users_explain/colors/colormaps.py: E501
62
+ galleries/users_explain/colors/colors.py: E402
63
+ galleries/tutorials/artists.py: E402
64
+ galleries/users_explain/axes/constrainedlayout_guide.py: E402
65
+ galleries/users_explain/axes/legend_guide.py: E402
66
+ galleries/users_explain/axes/tight_layout_guide.py: E402
67
+ galleries/users_explain/animations/animations.py: E501
68
+ galleries/tutorials/images.py: E501
69
+ galleries/tutorials/pyplot.py: E402, E501
70
+ galleries/users_explain/text/annotations.py: E402, E501
71
+ galleries/users_explain/text/mathtext.py: E501
72
+ galleries/users_explain/text/text_intro.py: E402
73
+ galleries/users_explain/text/text_props.py: E501
74
+
75
+ galleries/examples/animation/frame_grabbing_sgskip.py: E402
76
+ galleries/examples/images_contours_and_fields/tricontour_demo.py: E201
77
+ galleries/examples/images_contours_and_fields/tripcolor_demo.py: E201
78
+ galleries/examples/images_contours_and_fields/triplot_demo.py: E201
79
+ galleries/examples/lines_bars_and_markers/marker_reference.py: E402
80
+ galleries/examples/misc/print_stdout_sgskip.py: E402
81
+ galleries/examples/misc/table_demo.py: E201
82
+ galleries/examples/style_sheets/bmh.py: E501
83
+ galleries/examples/subplots_axes_and_figures/demo_constrained_layout.py: E402
84
+ galleries/examples/text_labels_and_annotations/custom_legends.py: E402
85
+ galleries/examples/ticks/date_concise_formatter.py: E402
86
+ galleries/examples/ticks/date_formatters_locators.py: F401
87
+ galleries/examples/user_interfaces/embedding_in_gtk3_panzoom_sgskip.py: E402
88
+ galleries/examples/user_interfaces/embedding_in_gtk3_sgskip.py: E402
89
+ galleries/examples/user_interfaces/embedding_in_gtk4_panzoom_sgskip.py: E402
90
+ galleries/examples/user_interfaces/embedding_in_gtk4_sgskip.py: E402
91
+ galleries/examples/user_interfaces/gtk3_spreadsheet_sgskip.py: E402
92
+ galleries/examples/user_interfaces/gtk4_spreadsheet_sgskip.py: E402
93
+ galleries/examples/user_interfaces/mpl_with_glade3_sgskip.py: E402
94
+ galleries/examples/user_interfaces/pylab_with_gtk3_sgskip.py: E402
95
+ galleries/examples/user_interfaces/pylab_with_gtk4_sgskip.py: E402
96
+ galleries/examples/userdemo/pgf_preamble_sgskip.py: E402
97
+ force-check = True
testbed/matplotlib__matplotlib/.git-blame-ignore-revs ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # style: end-of-file-fixer pre-commit hook
2
+ c1a33a481b9c2df605bcb9bef9c19fe65c3dac21
3
+
4
+ # style: trailing-whitespace pre-commit hook
5
+ 213061c0804530d04bbbd5c259f10dc8504e5b2b
6
+
7
+ # style: check-docstring-first pre-commit hook
8
+ 046533797725293dfc2a6edb9f536b25f08aa636
9
+
10
+ # chore: fix spelling errors
11
+ 686c9e5a413e31c46bb049407d5eca285bcab76d
12
+
13
+ # chore: pyupgrade --py39-plus
14
+ 4d306402bb66d6d4c694d8e3e14b91054417070e
testbed/matplotlib__matplotlib/.git_archival.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ node: $Format:%H$
2
+ node-date: $Format:%cI$
3
+ describe-name: $Format:%(describe:tags=true)$
4
+ ref-names: $Format:%D$
testbed/matplotlib__matplotlib/.gitattributes ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ * text=auto
2
+ *.m diff=objc
3
+ *.ppm binary
4
+ *.svg binary
5
+ *.svg linguist-language=true
6
+ .git_archival.txt export-subst
testbed/matplotlib__matplotlib/.gitignore ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #########################################
2
+ # OS-specific temporary and backup files
3
+ .DS_Store
4
+
5
+ #########################################
6
+ # Editor temporary/working/backup files #
7
+ .#*
8
+ [#]*#
9
+ *~
10
+ *$
11
+ *.bak
12
+ *.kdev4
13
+ .project
14
+ .pydevproject
15
+ *.swp
16
+ .idea
17
+ .vscode/
18
+
19
+ # Compiled source #
20
+ ###################
21
+ *.a
22
+ *.com
23
+ *.class
24
+ *.dll
25
+ *.exe
26
+ *.o
27
+ *.py[ocd]
28
+ *.so
29
+
30
+ # Python files #
31
+ ################
32
+ # setup.py working directory
33
+ build
34
+
35
+ # setup.py dist directory
36
+ dist
37
+ # Egg metadata
38
+ *.egg-info
39
+ .eggs
40
+ # wheel metadata
41
+ pip-wheel-metadata/*
42
+ # tox testing tool
43
+ .tox
44
+ mplsetup.cfg
45
+ # generated by setuptools_scm
46
+ lib/matplotlib/_version.py
47
+
48
+ # OS generated files #
49
+ ######################
50
+ .directory
51
+ .gdb_history
52
+ .DS_Store?
53
+ ehthumbs.db
54
+ Icon?
55
+ Thumbs.db
56
+
57
+ # Things specific to this project #
58
+ ###################################
59
+ galleries/tutorials/intermediate/CL01.png
60
+ galleries/tutorials/intermediate/CL02.png
61
+
62
+ # Documentation generated files #
63
+ #################################
64
+ # sphinx build directory
65
+ doc/_build
66
+ doc/api/_as_gen
67
+ # autogenerated by sphinx-gallery
68
+ doc/examples
69
+ doc/gallery
70
+ doc/modules
71
+ doc/plot_types
72
+ doc/pyplots/tex_demo.png
73
+ doc/tutorials
74
+ doc/users/explain
75
+ lib/dateutil
76
+ galleries/examples/*/*.bmp
77
+ galleries/examples/*/*.eps
78
+ galleries/examples/*/*.pdf
79
+ galleries/examples/*/*.png
80
+ galleries/examples/*/*.svg
81
+ galleries/examples/*/*.svgz
82
+ result_images
83
+ doc/_static/constrained_layout*.png
84
+ doc/.mpl_skip_subdirs.yaml
85
+
86
+ # Nose/Pytest generated files #
87
+ ###############################
88
+ .pytest_cache/
89
+ .cache/
90
+ .coverage
91
+ .coverage.*
92
+ *.py,cover
93
+ cover/
94
+ .noseids
95
+
96
+ # Conda files #
97
+ ###############
98
+ __conda_version__.txt
99
+ lib/png.lib
100
+ lib/z.lib
101
+
102
+ # Jupyter files #
103
+ #################
104
+
105
+ .ipynb_checkpoints/
106
+
107
+ # Vendored dependencies #
108
+ #########################
109
+ lib/matplotlib/backends/web_backend/node_modules/
110
+ lib/matplotlib/backends/web_backend/package-lock.json
111
+
112
+ LICENSE/LICENSE_QHULL
testbed/matplotlib__matplotlib/.mailmap ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Adam Ortiz <adam.ortiz@utoronto.ca>
2
+
3
+ Adrien F. Vincent <vincent.adrien@gmail.com>
4
+ Adrien F. Vincent <vincent.adrien@gmail.com> <adrien.vincent@u-psud.fr>
5
+
6
+ Aleksey Bilogur <aleksey.bilogur@gmail.com>
7
+
8
+ Alexander Rudy <alex.rudy@gmail.com>
9
+
10
+ Alon Hershenhorn <hershen@gmail.com>
11
+
12
+ Alvaro Sanchez <sanchezgnzlz.alvaro@gmail.com>
13
+
14
+ Andrew Dawson <ajdawson@acm.org> <dawson@atm.ox.ac.uk>
15
+
16
+ anykraus <kraus@mpip-mainz.mpg.de> <anykraus@users.noreply.github.com>
17
+
18
+ Ariel Hernán Curiale <curiale@gmail.com>
19
+
20
+ Ben Cohen <bj.cohen19@gmail.com> <ben@cohen-family.org>
21
+
22
+ Ben Root <ben.v.root@gmail.com> Benjamin Root <ben.v.root@gmail.com>
23
+
24
+ Benedikt Daurer <benedikt.daurer@icm.uu.se>
25
+
26
+ Benjamin Congdon <bencongdon96@gmail.com>
27
+ Benjamin Congdon <bencongdon96@gmail.com> bcongdon <bcongdo2@illinois.edu>
28
+
29
+ Bruno Zohreh <z.shams@bath.ac.uk>
30
+
31
+ Carsten Schelp <carstenschelp@mp.nl>
32
+
33
+ Casper van der Wel <caspervdw@gmail.com>
34
+
35
+ Chris Holdgraf <choldgraf@gmail.com>
36
+
37
+ Cho Yin Yong <choyiny@users.noreply.github.com>
38
+
39
+ Chris <chrissshe@gmail.com>
40
+
41
+ Christoph Gohlke <cgohlke@uci.edu> cgohlke <cgohlke@uci.edu>
42
+ Christoph Gohlke <cgohlke@uci.edu> C. Gohlke <cgohlke@uci.edu>
43
+ Christoph Gohlke <cjgohlke@gmail.com>
44
+
45
+ Cimarron Mittelsteadt <cimarronm@gmail.com> Cimarron <cimarronm@gmail.com>
46
+
47
+ cldssty <huey910@gmail.com>
48
+
49
+ Conner R. Phillips <conner.r.phillips@gmail.com> <conner.r.phillips.com>
50
+
51
+ Dan Hickstein <danhickstein@gmail.com>
52
+
53
+ Daniel Hyams <dhyams@gmail.com>
54
+ Daniel Hyams <dhyams@gmail.com> Daniel Hyams <dhyams@gitdev.(none)>
55
+
56
+ David Kua <david@kua.io> <david.kua@mail.utoronto.ca>
57
+
58
+ Devashish Deshpande <ashu.9412@gmail.com>
59
+
60
+ Dietmar Schwertberger <github@schwertberger.de>
61
+
62
+ Dora Fraeman Caswell <dorafraeman@gmail.com>
63
+
64
+ endolith <endolith@gmail.com>
65
+
66
+ Eric Dill <thedizzle@gmail.com> <edill@bnl.gov>
67
+
68
+ Erik Bray <erik.m.bray@gmail.com> <embray@stsci.edu>
69
+
70
+ Eric Ma <ericmajinglong@gmail.com> <ericmjl@Erics-MacBook-Pro.local>
71
+ Eric Ma <ericmajinglong@gmail.com> <ericmjl@users.noreply.github.com>
72
+
73
+ esvhd <weiliang.zhang@gmail.com>
74
+
75
+ Filipe Fernandes <ocefpaf@gmail.com>
76
+
77
+ Florian Le Bourdais <florian.s.lebourdais@gmail.com>
78
+
79
+ Francesco Montesano <franz.bergesund@gmail.com> montefra <franz.bergesund@gmail.com>
80
+
81
+ Gauravjeet <gauravjeet.kala@mail.utoronto.ca>
82
+
83
+ Hajoon Choi <hajoon.choi@mail.utoronto.ca>
84
+
85
+ hannah <story645@gmail.com>
86
+
87
+ Hans Moritz Günther <moritz.guenther@gmx.de>
88
+
89
+ Harshal Prakash Patankar <pharshalp@gmail.com>
90
+
91
+ Harshit Patni <patniharshit@gmail.com>
92
+
93
+ ImportanceOfBeingErnest <elch.rz@ruetz-online.de>
94
+
95
+ J. Goutin <JGoutin@users.noreply.github.com> JGoutin <ginnungagap@free.fr>
96
+
97
+ Jack Kelly <jack.kelly@imperial.ac.uk> <daniel.kelly10@imperial.ac.uk>
98
+ Jack Kelly <jack.kelly@imperial.ac.uk> <jack-list@xlk.org.uk>
99
+
100
+ Jaime Fernandez <jaime.frio@gmail.com>
101
+
102
+ Jake Vanderplas <jakevdp@gmail.com>
103
+ Jake Vanderplas <jakevdp@gmail.com> <jakevdp@yahoo.com>
104
+ Jake Vanderplas <jakevdp@gmail.com> <vanderplas@astro.washington.edu>
105
+
106
+ James R. Evans <jrevans1@earthlink.net>
107
+
108
+ Jeff Lutgen <jlutgen@gmail.com> <jlutgen@users.noreply.github.com>
109
+
110
+ Jeffrey Bingham <bingjeff@gmail.com>
111
+
112
+ Jens Hedegaard Nielsen <jenshnielsen@gmail.com>
113
+ Jens Hedegaard Nielsen <jenshnielsen@gmail.com> <jens.nielsen@ucl.ac.uk>
114
+
115
+ Joel Frederico <458871+joelfrederico@users.noreply.github.com>
116
+
117
+ John Hunter <jdh2358@gmail.com>
118
+
119
+ Jorrit Wronski <jowr@mek.dtu.dk>
120
+
121
+ Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> Mad Physicist <madphysicist@users.noreply.github.com>
122
+ Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> Joseph Fox-Rabinovitz <joseph.r.fox-rabinovitz@nasa.gov>
123
+
124
+ Jouni K. Seppänen <jks@iki.fi>
125
+
126
+ Julien Lhermitte <ordirules@gmail.com>
127
+
128
+ Julien Schueller <julien.schueller@gmail.com> <schueller@porsche-l64.phimeca.lan>
129
+ Julien Schueller <julien.schueller@gmail.com> <schueller@bx-l64.phimeca.lan>
130
+
131
+ Kevin Davies <kdavies4@gmail.com> <daviesk24@yahoo.com>
132
+
133
+ kikocorreoso <kikocorreoso@gmail.com> <kikocorreoso@users.noreply.github.com>
134
+
135
+ Klara Gerlei <klarizsofi@gmail.com>
136
+ Klara Gerlei <klarizsofi@gmail.com> klaragerlei <s1466507@sms.ed.ac.uk>
137
+
138
+ Kristen M. Thyng <kthyng@gmail.com>
139
+
140
+ Kyle Sunden <sunden@wisc.edu>
141
+
142
+ Leeonadoh <leo.sunpeng.li@gmail.com>
143
+
144
+ Lennart Fricke <lennart@die-frickes.eu> <lennart.fricke@kabelmail.de>
145
+
146
+ Levi Kilcher <levi.kilcher@nrel.gov>
147
+
148
+ Leon Yin <hello.leonyin@gmail.com>
149
+
150
+ Lion Krischer <lion.krischer@gmail.com> <krischer@geophysik.uni-muenchen.de>
151
+
152
+ Manan Kevadiya <kevadiyamanan@gmail.com>
153
+ Manan Kevadiya <kevadiyamanan@gmail.com> <43081866+manan2501@users.noreply.github.com>
154
+
155
+ Manuel Nuno Melo <manuel.nuno.melo@gmail.com>
156
+
157
+ Marco Gorelli <m.e.gorelli@gmail.com>
158
+ Marco Gorelli <m.e.gorelli@gmail.com> <33491632+MarcoGorelli@users.noreply.github.com>
159
+
160
+ Marek Rudnicki <marekrud@gmail.com>
161
+
162
+ Martin Fitzpatrick <martin.fitzpatrick@gmail.com> <mfitzp@abl.es>
163
+
164
+ Matt Newville <newville@cars.uchicago.edu>
165
+
166
+ Matthew Emmett <memmett@gmail.com>
167
+ Matthew Emmett <memmett@gmail.com> <memmett@unc.edu>
168
+
169
+ Matthias Bussonnier <bussonniermatthias@gmail.com>
170
+ Matthias Bussonnier <bussonniermatthias@gmail.com> <mbussonnier@ucmerced.edu>
171
+
172
+ Matthias Lüthi <maluethi@protonmail.ch>
173
+ Matthias Lüthi <maluethi@protonmail.ch> <matthias.luethi@lhep.unibe.ch>
174
+
175
+ Matti Picus <matti.picus@gmail.com>
176
+
177
+ Michael Droettboom <mdboom@gmail.com> <mdroe@stsci.edu>
178
+ Michael Droettboom <mdboom@gmail.com> Michael Droettboom <mdboom@debian-vm>
179
+
180
+ Michiel de Hoon <mjldehoon@yahoo.com>
181
+ Michiel de Hoon <mjldehoon@yahoo.com> Michiel de Hoon <mdehoon@mad002s-MacBook-Air.local>
182
+ Michiel de Hoon <mjldehoon@yahoo.com> Michiel de Hoon <mdehoon@michiel-de-hoons-computer.local>
183
+ Michiel de Hoon <mjldehoon@yahoo.com> Michiel de Hoon <mdehoon@Michiels-MacBook-Pro.local>
184
+ Michiel de Hoon <mjldehoon@yahoo.com> Michiel de Hoon <mdehoon@tkx294.genome.gsc.riken.jp>
185
+
186
+ MinRK <benjaminrk@gmail.com>
187
+ MinRK <benjaminrk@gmail.com> Min RK <minrk@kerbin.local>
188
+
189
+ Nelle Varoquaux <nelle.varoquaux@gmail.com>
190
+
191
+ Nic Eggert <nic.eggert@gmail.com> Nic Eggert <nic@eggert.pw>
192
+ Nic Eggert <nic.eggert@gmail.com> Nic Eggert <nse23@cornell.edu>
193
+
194
+ Nicolas P. Rougier <Nicolas.Rougier@inria.fr>
195
+
196
+ OceanWolf <juichenieder-tigger@yahoo.co.uk>
197
+
198
+ Olivier Castany <1868182+ocastany@users.noreply.github.com>
199
+ Olivier Castany <1868182+ocastany@users.noreply.github.com> <Olivier@home>
200
+ Olivier Castany <1868182+ocastany@users.noreply.github.com> <castany@clevo>
201
+
202
+ Om Sitapara <omsitapara23@gmail.com>
203
+
204
+ Patrick Chen <pat.chen@mail.utoronto.ca>
205
+
206
+ Paul Ganssle <p.ganssle@gmail.com>
207
+ Paul Ganssle <pg@example.com>
208
+
209
+ Paul Hobson <pmhobson@gmail.com>
210
+ Paul Hobson <pmhobson@gmail.com> vagrant <vagrant@precise32.(none)>
211
+
212
+ Paul Ivanov <pivanov314@gmail.com>
213
+ Paul Ivanov <pivanov314@gmail.com> <pi@berkeley.edu>
214
+ Paul Ivanov <pivanov314@gmail.com> <pivanov5@bloomberg.net>
215
+
216
+ Per Parker <wisalam@live.com>
217
+
218
+ Peter Würtz <pwuertz@gmail.com>
219
+ Peter Würtz <pwuertz@gmail.com> <pwuertz@googlemail.com>
220
+
221
+ Phil Elson <pelson.pub@gmail.com>
222
+ Phil Elson <pelson.pub@gmail.com> <philipelson@hotmail.com>
223
+ Phil Elson <pelson.pub@gmail.com> <philipelson@gmail.com>
224
+
225
+ productivememberofsociety666 <productivememberofsociety666@sol.fr.am> none <none@example.net>
226
+
227
+ Rishikesh <rishikksh20@gmail.com>
228
+
229
+ RyanPan <ryanbelt1993129@hotmail.com>
230
+
231
+ Samesh Lakhotia <samesh.lakhotia@gmail.com>
232
+ Samesh Lakhotia <43701530+sameshl@users.noreply.github.com> <samesh.lakhotia@gmail.com>'
233
+
234
+ Scott Lasley <selasley@me.com>
235
+
236
+ Sebastian Raschka <mail@sebastianraschka.com>
237
+ Sebastian Raschka <mail@sebastianraschka.com> <se.raschka@me.com>
238
+
239
+ Sidharth Bansal <bansal.sidharth2996@gmail.com>
240
+ Sidharth Bansal <20972099+SidharthBansal@users.noreply.github.com> <bansal.sidharth2996@gmail.com>
241
+
242
+ Simon Cross <hodgestar+github@gmail.com> <hodgestar@gmail.com>
243
+
244
+ Slav Basharov <slavbacharov@gmail.com>
245
+
246
+ sohero <herosgq@gmail.com> sohero <ivip@tom.com>
247
+
248
+ Stefan van der Walt <stefanv@berkeley.edu> <stefan@sun.ac.za>
249
+
250
+ switham <github@mac-guyver.com> switham <switham_github@mac-guyver.com>
251
+
252
+ Taehoon Lee <taehoonlee@snu.ac.kr>
253
+
254
+ Ted Drain <ted.drain@gmail.com>
255
+
256
+ Taras Kuzyo <kuzyo.taras@gmail.com>
257
+
258
+ Terence Honles <terence@honles.com>
259
+
260
+ Thomas A Caswell <tcaswell@gmail.com> Thomas A Caswell <tcaswell@bnl.gov>
261
+ Thomas A Caswell <tcaswell@gmail.com> Thomas A Caswell <tcaswell@uchicago.edu>
262
+ Thomas A Caswell <tcaswell@gmail.com> Thomas A Caswell <“tcaswell@gmail.com”>
263
+ Thomas A Caswell <tcaswell@gmail.com> Thomas A Caswell <tcaswell@localhost.localdomain>
264
+
265
+ Till Stensitzki <mail.till@gmx.de>
266
+
267
+ Trish Gillett-Kawamoto <trish.gillett@shopify.com> <discardthree@gmail.com>
268
+
269
+ Tuan Dung Tran <tuan.d.tran@hotmail.com>
270
+
271
+ Víctor Zabalza <vzabalza@gmail.com>
272
+
273
+ Vidur Satija <vidursatija@gmail.com>
274
+
275
+ WANG Aiyong <gepcelway@gmail.com>
276
+
277
+ Zhili (Jerry) Pan <sasori.pan.jerry@gmail.com>
278
+
279
+ Werner F Bruhin <wernerfbd@gmx.ch>
280
+
281
+ Yunfei Yang <yangyunf@iits-b473-20053.(none)> Yunfei Yang <yangyunf@iits-b473-20057.(none)>
282
+ Yunfei Yang <yangyunf@iits-b473-20053.(none)> Yunfei Yang <yangyunf@iits-b473-20061.(none)>
283
+
284
+ Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
testbed/matplotlib__matplotlib/.matplotlib-repo ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ The existence of this file signals that the code is a matplotlib source repo
2
+ and not an installed version. We use this in __init__.py for gating version
3
+ detection.
testbed/matplotlib__matplotlib/.meeseeksdev.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ users:
2
+ Carreau:
3
+ can:
4
+ - backport
testbed/matplotlib__matplotlib/.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ci:
2
+ autofix_prs: false
3
+ autoupdate_schedule: 'quarterly'
4
+ exclude: |
5
+ (?x)^(
6
+ extern|
7
+ LICENSE|
8
+ lib/matplotlib/mpl-data|
9
+ doc/devel/gitwash|
10
+ doc/users/prev|
11
+ doc/api/prev|
12
+ lib/matplotlib/tests/tinypages
13
+ )
14
+ repos:
15
+ - repo: https://github.com/pre-commit/pre-commit-hooks
16
+ rev: v4.4.0
17
+ hooks:
18
+ - id: check-added-large-files
19
+ - id: check-docstring-first
20
+ exclude: lib/matplotlib/typing.py # docstring used for attribute flagged by check
21
+ - id: end-of-file-fixer
22
+ exclude_types: [svg]
23
+ - id: mixed-line-ending
24
+ - id: name-tests-test
25
+ args: ["--pytest-test-first"]
26
+ - id: no-commit-to-branch #default is master and main
27
+ - id: trailing-whitespace
28
+ exclude_types: [svg]
29
+
30
+ - repo: https://github.com/pycqa/flake8
31
+ rev: 6.0.0
32
+ hooks:
33
+ - id: flake8
34
+ additional_dependencies: [pydocstyle>5.1.0, flake8-docstrings>1.4.0, flake8-force]
35
+ args: ["--docstring-convention=all"]
36
+ - repo: https://github.com/codespell-project/codespell
37
+ rev: v2.2.4
38
+ hooks:
39
+ - id: codespell
40
+ files: ^.*\.(py|c|cpp|h|m|md|rst|yml)$
41
+ args: [
42
+ "--ignore-words",
43
+ "ci/codespell-ignore-words.txt",
44
+ "--skip",
45
+ "doc/users/project/credits.rst"
46
+ ]
47
+
48
+ - repo: https://github.com/pycqa/isort
49
+ rev: 5.12.0
50
+ hooks:
51
+ - id: isort
52
+ name: isort (python)
53
+ files: ^galleries/tutorials/|^galleries/examples/|^galleries/plot_types/
testbed/matplotlib__matplotlib/CITATION.bib ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @Article{Hunter:2007,
2
+ Author = {Hunter, J. D.},
3
+ Title = {Matplotlib: A 2D graphics environment},
4
+ Journal = {Computing in Science \& Engineering},
5
+ Volume = {9},
6
+ Number = {3},
7
+ Pages = {90--95},
8
+ abstract = {Matplotlib is a 2D graphics package used for Python for
9
+ application development, interactive scripting, and publication-quality
10
+ image generation across user interfaces and operating systems.},
11
+ publisher = {IEEE COMPUTER SOC},
12
+ doi = {10.1109/MCSE.2007.55},
13
+ year = 2007
14
+ }
testbed/matplotlib__matplotlib/CITATION.cff ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ 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.'
3
+ title: 'Matplotlib: Visualization with Python'
4
+ authors:
5
+ - name: The Matplotlib Development Team
6
+ website: https://matplotlib.org/
7
+ type: software
8
+ url: 'https://matplotlib.org/'
9
+ repository-code: 'https://github.com/matplotlib/matplotlib/'
10
+ preferred-citation:
11
+ type: article
12
+ authors:
13
+ - family-names: Hunter
14
+ given-names: John D.
15
+ title: "Matplotlib: A 2D graphics environment"
16
+ year: 2007
17
+ date-published: 2007-06-18
18
+ journal: Computing in Science & Engineering
19
+ volume: 9
20
+ issue: 3
21
+ start: 90
22
+ end: 95
23
+ doi: 10.1109/MCSE.2007.55
24
+ publisher:
25
+ name: IEEE Computer Society
26
+ website: 'https://www.computer.org/'
27
+ 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.
testbed/matplotlib__matplotlib/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, religion, or sexual identity
11
+ and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the
27
+ overall community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or
32
+ advances of any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email
36
+ address, without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ## Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ## Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ## Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ [matplotlib-coc@numfocus.org](mailto:matplotlib-coc@numfocus.org)
65
+ (monitored by the [CoC subcommittee](https://matplotlib.org/governance/people.html#coc-subcommittee)) or a
66
+ report can be made using the [NumFOCUS Code of Conduct report form][numfocus
67
+ form]. If community leaders cannot come to a resolution about enforcement,
68
+ reports will be escalated to the NumFocus Code of Conduct committee
69
+ (conduct@numfocus.org). All complaints will be reviewed and investigated
70
+ promptly and fairly.
71
+
72
+ All community leaders are obligated to respect the privacy and security of the
73
+ reporter of any incident.
74
+
75
+ [numfocus form]: https://numfocus.typeform.com/to/ynjGdT
76
+
77
+ ## Enforcement Guidelines
78
+
79
+ Community leaders will follow these Community Impact Guidelines in determining
80
+ the consequences for any action they deem in violation of this Code of Conduct:
81
+
82
+ ### 1. Correction
83
+
84
+ **Community Impact**: Use of inappropriate language or other behavior deemed
85
+ unprofessional or unwelcome in the community.
86
+
87
+ **Consequence**: A private, written warning from community leaders, providing
88
+ clarity around the nature of the violation and an explanation of why the
89
+ behavior was inappropriate. A public apology may be requested.
90
+
91
+ ### 2. Warning
92
+
93
+ **Community Impact**: A violation through a single incident or series
94
+ of actions.
95
+
96
+ **Consequence**: A warning with consequences for continued behavior. No
97
+ interaction with the people involved, including unsolicited interaction with
98
+ those enforcing the Code of Conduct, for a specified period of time. This
99
+ includes avoiding interactions in community spaces as well as external channels
100
+ like social media. Violating these terms may lead to a temporary or
101
+ permanent ban.
102
+
103
+ ### 3. Temporary Ban
104
+
105
+ **Community Impact**: A serious violation of community standards, including
106
+ sustained inappropriate behavior.
107
+
108
+ **Consequence**: A temporary ban from any sort of interaction or public
109
+ communication with the community for a specified period of time. No public or
110
+ private interaction with the people involved, including unsolicited interaction
111
+ with those enforcing the Code of Conduct, is allowed during this period.
112
+ Violating these terms may lead to a permanent ban.
113
+
114
+ ### 4. Permanent Ban
115
+
116
+ **Community Impact**: Demonstrating a pattern of violation of community
117
+ standards, including sustained inappropriate behavior, harassment of an
118
+ individual, or aggression toward or disparagement of classes of individuals.
119
+
120
+ **Consequence**: A permanent ban from any sort of public interaction within
121
+ the community.
122
+
123
+ ## Attribution
124
+
125
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
126
+ version 2.0, available at
127
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
128
+
129
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
130
+ enforcement ladder](https://github.com/mozilla/diversity).
131
+
132
+ [homepage]: https://www.contributor-covenant.org
133
+
134
+ For answers to common questions about this code of conduct, see the FAQ at
135
+ https://www.contributor-covenant.org/faq. Translations are available at
136
+ https://www.contributor-covenant.org/translations.
testbed/matplotlib__matplotlib/INSTALL.rst ADDED
@@ -0,0 +1 @@
 
 
1
+ See doc/users/installing/index.rst
testbed/matplotlib__matplotlib/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![PyPi](https://img.shields.io/pypi/v/matplotlib)](https://pypi.org/project/matplotlib/)
2
+ [![Conda](https://img.shields.io/conda/vn/conda-forge/matplotlib)](https://anaconda.org/conda-forge/matplotlib)
3
+ [![Downloads](https://img.shields.io/pypi/dm/matplotlib)](https://pypi.org/project/matplotlib)
4
+ [![NUMFocus](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org)
5
+
6
+ [![Discourse help forum](https://img.shields.io/badge/help_forum-discourse-blue.svg)](https://discourse.matplotlib.org)
7
+ [![Gitter](https://badges.gitter.im/matplotlib/matplotlib.svg)](https://gitter.im/matplotlib/matplotlib)
8
+ [![GitHub issues](https://img.shields.io/badge/issue_tracking-github-blue.svg)](https://github.com/matplotlib/matplotlib/issues)
9
+ [![Contributing](https://img.shields.io/badge/PR-Welcome-%23FF8300.svg?)](https://matplotlib.org/stable/devel/index.html)
10
+
11
+ [![GitHub actions status](https://github.com/matplotlib/matplotlib/workflows/Tests/badge.svg)](https://github.com/matplotlib/matplotlib/actions?query=workflow%3ATests)
12
+ [![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)
13
+ [![AppVeyor status](https://ci.appveyor.com/api/projects/status/github/matplotlib/matplotlib?branch=main&svg=true)](https://ci.appveyor.com/project/matplotlib/matplotlib)
14
+ [![Codecov status](https://codecov.io/github/matplotlib/matplotlib/badge.svg?branch=main&service=github)](https://app.codecov.io/gh/matplotlib/matplotlib)
15
+
16
+ ![Matplotlib logotype](https://matplotlib.org/_static/logo2.svg)
17
+
18
+ Matplotlib is a comprehensive library for creating static, animated, and
19
+ interactive visualizations in Python.
20
+
21
+ Check out our [home page](https://matplotlib.org/) for more information.
22
+
23
+ ![image](https://matplotlib.org/_static/readme_preview.png)
24
+
25
+ Matplotlib produces publication-quality figures in a variety of hardcopy
26
+ formats and interactive environments across platforms. Matplotlib can be
27
+ used in Python scripts, Python/IPython shells, web application servers,
28
+ and various graphical user interface toolkits.
29
+
30
+ ## Install
31
+
32
+ See the [install
33
+ documentation](https://matplotlib.org/stable/users/installing/index.html),
34
+ which is generated from `/doc/users/installing/index.rst`
35
+
36
+ ## Contribute
37
+
38
+ You've discovered a bug or something else you want to change — excellent!
39
+
40
+ You've worked out a way to fix it — even better!
41
+
42
+ You want to tell us about it — best of all!
43
+
44
+ Start at the [contributing
45
+ guide](https://matplotlib.org/devdocs/devel/contributing.html)!
46
+
47
+ ## Contact
48
+
49
+ [Discourse](https://discourse.matplotlib.org/) is the discussion forum
50
+ for general questions and discussions and our recommended starting
51
+ point.
52
+
53
+ Our active mailing lists (which are mirrored on Discourse) are:
54
+
55
+ - [Users](https://mail.python.org/mailman/listinfo/matplotlib-users)
56
+ mailing list: <matplotlib-users@python.org>
57
+ - [Announcement](https://mail.python.org/mailman/listinfo/matplotlib-announce)
58
+ mailing list: <matplotlib-announce@python.org>
59
+ - [Development](https://mail.python.org/mailman/listinfo/matplotlib-devel)
60
+ mailing list: <matplotlib-devel@python.org>
61
+
62
+ [Gitter](https://gitter.im/matplotlib/matplotlib) is for coordinating
63
+ development and asking questions directly related to contributing to
64
+ matplotlib.
65
+
66
+ ## Citing Matplotlib
67
+
68
+ If Matplotlib contributes to a project that leads to publication, please
69
+ acknowledge this by citing Matplotlib.
70
+
71
+ [A ready-made citation
72
+ entry](https://matplotlib.org/stable/users/project/citing.html) is
73
+ available.
testbed/matplotlib__matplotlib/SECURITY.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ The following table lists versions and whether they are supported. Security
6
+ vulnerability reports will be accepted and acted upon for all supported
7
+ versions.
8
+
9
+ | Version | Supported |
10
+ | ------- | ------------------ |
11
+ | 3.7.x | :white_check_mark: |
12
+ | 3.6.x | :white_check_mark: |
13
+ | 3.5.x | :x: |
14
+ | 3.4.x | :x: |
15
+ | 3.3.x | :x: |
16
+ | < 3.3 | :x: |
17
+
18
+
19
+ ## Reporting a Vulnerability
20
+
21
+
22
+ To report a security vulnerability, please use the [Tidelift security
23
+ contact](https://tidelift.com/security). Tidelift will coordinate the fix and
24
+ disclosure.
25
+
26
+ If you have found a security vulnerability, in order to keep it confidential,
27
+ please do not report an issue on GitHub.
28
+
29
+ We do not award bounties for security vulnerabilities.
testbed/matplotlib__matplotlib/azure-pipelines.yml ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python package
2
+ # Create and test a Python package on multiple Python versions.
3
+ # Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more:
4
+ # https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python?view=azure-devops
5
+
6
+ trigger:
7
+ branches:
8
+ exclude:
9
+ - v*-doc
10
+ pr:
11
+ branches:
12
+ exclude:
13
+ - v*-doc
14
+ paths:
15
+ exclude:
16
+ - doc/**/*
17
+ - galleries/**/*
18
+
19
+ stages:
20
+
21
+ - stage: Check
22
+ jobs:
23
+ - job: Skip
24
+ pool:
25
+ vmImage: 'ubuntu-latest'
26
+ variables:
27
+ DECODE_PERCENTS: 'false'
28
+ RET: 'true'
29
+ steps:
30
+ - bash: |
31
+ git_log=`git log --max-count=1 --skip=1 --pretty=format:"%B" | tr "\n" " "`
32
+ echo "##vso[task.setvariable variable=log]$git_log"
33
+ - bash: echo "##vso[task.setvariable variable=RET]false"
34
+ 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]'))
35
+ - bash: echo "##vso[task.setvariable variable=start_main;isOutput=true]$RET"
36
+ name: result
37
+
38
+ - stage: Main
39
+ condition: and(succeeded(), eq(dependencies.Check.outputs['Skip.result.start_main'], 'true'))
40
+ dependsOn: Check
41
+ jobs:
42
+ - job: Pytest
43
+ strategy:
44
+ matrix:
45
+ Linux_py39:
46
+ vmImage: 'ubuntu-20.04' # keep one job pinned to the oldest image
47
+ python.version: '3.9'
48
+ Linux_py310:
49
+ vmImage: 'ubuntu-latest'
50
+ python.version: '3.10'
51
+ Linux_py311:
52
+ vmImage: 'ubuntu-latest'
53
+ python.version: '3.11'
54
+ macOS_py39:
55
+ vmImage: 'macOS-latest'
56
+ python.version: '3.9'
57
+ macOS_py310:
58
+ vmImage: 'macOS-latest'
59
+ python.version: '3.10'
60
+ macOS_py311:
61
+ vmImage: 'macOS-latest'
62
+ python.version: '3.11'
63
+ Windows_py39:
64
+ vmImage: 'windows-2019' # keep one job pinned to the oldest image
65
+ python.version: '3.9'
66
+ Windows_py310:
67
+ vmImage: 'windows-latest'
68
+ python.version: '3.10'
69
+ Windows_py311:
70
+ vmImage: 'windows-latest'
71
+ python.version: '3.11'
72
+ maxParallel: 4
73
+ pool:
74
+ vmImage: '$(vmImage)'
75
+ steps:
76
+ - task: UsePythonVersion@0
77
+ inputs:
78
+ versionSpec: '$(python.version)'
79
+ architecture: 'x64'
80
+ displayName: 'Use Python $(python.version)'
81
+ condition: and(succeeded(), ne(variables['python.version'], 'Pre'))
82
+
83
+ - task: stevedower.python.InstallPython.InstallPython@1
84
+ displayName: 'Use prerelease Python'
85
+ inputs:
86
+ prerelease: true
87
+ condition: and(succeeded(), eq(variables['python.version'], 'Pre'))
88
+
89
+ - bash: |
90
+ set -e
91
+ case "$(python -c 'import sys; print(sys.platform)')" in
92
+ linux)
93
+ echo 'Acquire::Retries "3";' | sudo tee /etc/apt/apt.conf.d/80-retries
94
+ sudo apt update
95
+ sudo apt install \
96
+ cm-super \
97
+ dvipng \
98
+ ffmpeg \
99
+ fonts-noto-cjk \
100
+ gdb \
101
+ gir1.2-gtk-3.0 \
102
+ graphviz \
103
+ inkscape \
104
+ libcairo2 \
105
+ libgirepository-1.0-1 \
106
+ lmodern \
107
+ fonts-freefont-otf \
108
+ poppler-utils \
109
+ texlive-pictures \
110
+ texlive-fonts-recommended \
111
+ texlive-latex-base \
112
+ texlive-latex-extra \
113
+ texlive-latex-recommended \
114
+ texlive-xetex texlive-luatex \
115
+ ttf-wqy-zenhei
116
+ ;;
117
+ darwin)
118
+ brew install --cask xquartz
119
+ brew install pkg-config ffmpeg imagemagick mplayer ccache
120
+ brew tap homebrew/cask-fonts
121
+ brew install font-noto-sans-cjk-sc
122
+ ;;
123
+ win32)
124
+ ;;
125
+ *)
126
+ exit 1
127
+ ;;
128
+ esac
129
+ displayName: 'Install dependencies'
130
+
131
+ - bash: |
132
+ python -m pip install --upgrade pip
133
+ python -m pip install -r requirements/testing/all.txt -r requirements/testing/extra.txt ||
134
+ [[ "$PYTHON_VERSION" = 'Pre' ]]
135
+ displayName: 'Install dependencies with pip'
136
+
137
+ - bash: |
138
+ python -m pip install -ve . ||
139
+ [[ "$PYTHON_VERSION" = 'Pre' ]]
140
+ displayName: "Install self"
141
+
142
+ - script: env
143
+ displayName: 'print env'
144
+
145
+ - script: pip list
146
+ displayName: 'print pip'
147
+
148
+ - bash: |
149
+ PYTHONFAULTHANDLER=1 python -m pytest --junitxml=junit/test-results.xml -raR --maxfail=50 --timeout=300 --durations=25 --cov-report= --cov=lib -n 2 ||
150
+ [[ "$PYTHON_VERSION" = 'Pre' ]]
151
+ displayName: 'pytest'
152
+
153
+ - bash: |
154
+ bash <(curl -s https://codecov.io/bash) -f "!*.gcov" -X gcov
155
+ displayName: 'Upload to codecov.io'
156
+
157
+ - task: PublishTestResults@2
158
+ inputs:
159
+ testResultsFiles: '**/test-results.xml'
160
+ testRunTitle: 'Python $(python.version)'
161
+ condition: succeededOrFailed()
162
+
163
+ - publish: $(System.DefaultWorkingDirectory)/result_images
164
+ artifact: $(Agent.JobName)-result_images
165
+ condition: and(failed(), ne(variables['python.version'], 'Pre'))
testbed/matplotlib__matplotlib/environment.yml ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To set up a development environment using conda run:
2
+ #
3
+ # conda env create -f environment.yml
4
+ # conda activate mpl-dev
5
+ # pip install -e .
6
+ #
7
+ name: mpl-dev
8
+ channels:
9
+ - conda-forge
10
+ dependencies:
11
+ # runtime dependencies
12
+ - cairocffi
13
+ - contourpy>=1.0.1
14
+ - cycler>=0.10.0
15
+ - fonttools>=4.22.0
16
+ - importlib-resources>=3.2.0
17
+ - kiwisolver>=1.0.1
18
+ - numpy>=1.21
19
+ - pillow>=6.2
20
+ - pybind11>=2.6.0
21
+ - pygobject
22
+ - pyparsing>=2.3.1
23
+ - pyqt
24
+ - python-dateutil>=2.1
25
+ - setuptools
26
+ - setuptools_scm
27
+ - wxpython
28
+ # building documentation
29
+ - colorspacious
30
+ - graphviz
31
+ - ipython
32
+ - ipywidgets
33
+ - numpydoc>=0.8
34
+ - packaging
35
+ - pydata-sphinx-theme
36
+ - pyyaml
37
+ - sphinx>=1.8.1,!=2.0.0
38
+ - sphinx-copybutton
39
+ - sphinx-gallery>=0.12
40
+ - sphinx-design
41
+ - pip
42
+ - pip:
43
+ - mpl-sphinx-theme
44
+ - sphinxcontrib-svg2pdfconverter
45
+ - pikepdf
46
+ # testing
47
+ - coverage
48
+ - flake8>=3.8
49
+ - flake8-docstrings>=1.4.0
50
+ - gtk4
51
+ - ipykernel
52
+ - nbconvert[execute]!=6.0.0,!=6.0.1,!=7.3.0,!=7.3.1
53
+ - nbformat!=5.0.0,!=5.0.1
54
+ - pandas!=0.25.0
55
+ - psutil
56
+ - pre-commit
57
+ - pydocstyle>=5.1.0
58
+ - pytest!=4.6.0,!=5.4.0
59
+ - pytest-cov
60
+ - pytest-rerunfailures
61
+ - pytest-timeout
62
+ - pytest-xdist
63
+ - tornado
64
+ - pytz
65
+ - black
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/README.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .. _subplots_axes_and_figures_examples:
2
+
3
+ Subplots, axes and figures
4
+ ==========================
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================
3
+ Axes Zoom Effect
4
+ ================
5
+
6
+ """
7
+
8
+ import matplotlib.pyplot as plt
9
+
10
+ from matplotlib.transforms import (Bbox, TransformedBbox,
11
+ blended_transform_factory)
12
+ from mpl_toolkits.axes_grid1.inset_locator import (BboxConnector,
13
+ BboxConnectorPatch,
14
+ BboxPatch)
15
+
16
+
17
+ def connect_bbox(bbox1, bbox2,
18
+ loc1a, loc2a, loc1b, loc2b,
19
+ prop_lines, prop_patches=None):
20
+ if prop_patches is None:
21
+ prop_patches = {
22
+ **prop_lines,
23
+ "alpha": prop_lines.get("alpha", 1) * 0.2,
24
+ "clip_on": False,
25
+ }
26
+
27
+ c1 = BboxConnector(
28
+ bbox1, bbox2, loc1=loc1a, loc2=loc2a, clip_on=False, **prop_lines)
29
+ c2 = BboxConnector(
30
+ bbox1, bbox2, loc1=loc1b, loc2=loc2b, clip_on=False, **prop_lines)
31
+
32
+ bbox_patch1 = BboxPatch(bbox1, **prop_patches)
33
+ bbox_patch2 = BboxPatch(bbox2, **prop_patches)
34
+
35
+ p = BboxConnectorPatch(bbox1, bbox2,
36
+ loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,
37
+ clip_on=False,
38
+ **prop_patches)
39
+
40
+ return c1, c2, bbox_patch1, bbox_patch2, p
41
+
42
+
43
+ def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):
44
+ """
45
+ Connect *ax1* and *ax2*. The *xmin*-to-*xmax* range in both axes will
46
+ be marked.
47
+
48
+ Parameters
49
+ ----------
50
+ ax1
51
+ The main axes.
52
+ ax2
53
+ The zoomed axes.
54
+ xmin, xmax
55
+ The limits of the colored area in both plot axes.
56
+ **kwargs
57
+ Arguments passed to the patch constructor.
58
+ """
59
+
60
+ bbox = Bbox.from_extents(xmin, 0, xmax, 1)
61
+
62
+ mybbox1 = TransformedBbox(bbox, ax1.get_xaxis_transform())
63
+ mybbox2 = TransformedBbox(bbox, ax2.get_xaxis_transform())
64
+
65
+ prop_patches = {**kwargs, "ec": "none", "alpha": 0.2}
66
+
67
+ c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(
68
+ mybbox1, mybbox2,
69
+ loc1a=3, loc2a=2, loc1b=4, loc2b=1,
70
+ prop_lines=kwargs, prop_patches=prop_patches)
71
+
72
+ ax1.add_patch(bbox_patch1)
73
+ ax2.add_patch(bbox_patch2)
74
+ ax2.add_patch(c1)
75
+ ax2.add_patch(c2)
76
+ ax2.add_patch(p)
77
+
78
+ return c1, c2, bbox_patch1, bbox_patch2, p
79
+
80
+
81
+ def zoom_effect02(ax1, ax2, **kwargs):
82
+ """
83
+ ax1 : the main axes
84
+ ax1 : the zoomed axes
85
+
86
+ Similar to zoom_effect01. The xmin & xmax will be taken from the
87
+ ax1.viewLim.
88
+ """
89
+
90
+ tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)
91
+ trans = blended_transform_factory(ax2.transData, tt)
92
+
93
+ mybbox1 = ax1.bbox
94
+ mybbox2 = TransformedBbox(ax1.viewLim, trans)
95
+
96
+ prop_patches = {**kwargs, "ec": "none", "alpha": 0.2}
97
+
98
+ c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(
99
+ mybbox1, mybbox2,
100
+ loc1a=3, loc2a=2, loc1b=4, loc2b=1,
101
+ prop_lines=kwargs, prop_patches=prop_patches)
102
+
103
+ ax1.add_patch(bbox_patch1)
104
+ ax2.add_patch(bbox_patch2)
105
+ ax2.add_patch(c1)
106
+ ax2.add_patch(c2)
107
+ ax2.add_patch(p)
108
+
109
+ return c1, c2, bbox_patch1, bbox_patch2, p
110
+
111
+
112
+ axs = plt.figure().subplot_mosaic([
113
+ ["zoom1", "zoom2"],
114
+ ["main", "main"],
115
+ ])
116
+
117
+ axs["main"].set(xlim=(0, 5))
118
+ zoom_effect01(axs["zoom1"], axs["main"], 0.2, 0.8)
119
+ axs["zoom2"].set(xlim=(2, 3))
120
+ zoom_effect02(axs["zoom2"], axs["main"])
121
+
122
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axhspan_demo.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============
3
+ axhspan Demo
4
+ ============
5
+
6
+ Create lines or rectangles that span the axes in either the horizontal or
7
+ vertical direction, and lines than span the axes with an arbitrary orientation.
8
+ """
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+
13
+ t = np.arange(-1, 2, .01)
14
+ s = np.sin(2 * np.pi * t)
15
+
16
+ fig, ax = plt.subplots()
17
+
18
+ ax.plot(t, s)
19
+ # Thick red horizontal line at y=0 that spans the xrange.
20
+ ax.axhline(linewidth=8, color='#d62728')
21
+ # Horizontal line at y=1 that spans the xrange.
22
+ ax.axhline(y=1)
23
+ # Vertical line at x=1 that spans the yrange.
24
+ ax.axvline(x=1)
25
+ # Thick blue vertical line at x=0 that spans the upper quadrant of the yrange.
26
+ ax.axvline(x=0, ymin=0.75, linewidth=8, color='#1f77b4')
27
+ # Default hline at y=.5 that spans the middle half of the axes.
28
+ ax.axhline(y=.5, xmin=0.25, xmax=0.75)
29
+ # Infinite black line going through (0, 0) to (1, 1).
30
+ ax.axline((0, 0), (1, 1), color='k')
31
+ # 50%-gray rectangle spanning the axes' width from y=0.25 to y=0.75.
32
+ ax.axhspan(0.25, 0.75, facecolor='0.5')
33
+ # Green rectangle spanning the axes' height from x=1.25 to x=1.55.
34
+ ax.axvspan(1.25, 1.55, facecolor='#2ca02c')
35
+
36
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_equal_demo.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =======================
3
+ Equal axis aspect ratio
4
+ =======================
5
+
6
+ How to set and adjust plots with equal axis aspect ratios.
7
+ """
8
+
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+
12
+ # Plot circle of radius 3.
13
+
14
+ an = np.linspace(0, 2 * np.pi, 100)
15
+ fig, axs = plt.subplots(2, 2)
16
+
17
+ axs[0, 0].plot(3 * np.cos(an), 3 * np.sin(an))
18
+ axs[0, 0].set_title('not equal, looks like ellipse', fontsize=10)
19
+
20
+ axs[0, 1].plot(3 * np.cos(an), 3 * np.sin(an))
21
+ axs[0, 1].axis('equal')
22
+ axs[0, 1].set_title('equal, looks like circle', fontsize=10)
23
+
24
+ axs[1, 0].plot(3 * np.cos(an), 3 * np.sin(an))
25
+ axs[1, 0].axis('equal')
26
+ axs[1, 0].set(xlim=(-3, 3), ylim=(-3, 3))
27
+ axs[1, 0].set_title('still a circle, even after changing limits', fontsize=10)
28
+
29
+ axs[1, 1].plot(3 * np.cos(an), 3 * np.sin(an))
30
+ axs[1, 1].set_aspect('equal', 'box')
31
+ axs[1, 1].set_title('still a circle, auto-adjusted data limits', fontsize=10)
32
+
33
+ fig.tight_layout()
34
+
35
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/axis_labels_demo.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ===================
3
+ Axis Label Position
4
+ ===================
5
+
6
+ Choose axis label position when calling `~.Axes.set_xlabel` and
7
+ `~.Axes.set_ylabel` as well as for colorbar.
8
+
9
+ """
10
+ import matplotlib.pyplot as plt
11
+
12
+ fig, ax = plt.subplots()
13
+
14
+ sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
15
+ ax.set_ylabel('YLabel', loc='top')
16
+ ax.set_xlabel('XLabel', loc='left')
17
+ cbar = fig.colorbar(sc)
18
+ cbar.set_label("ZLabel", loc='top')
19
+
20
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/custom_figure_class.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ========================
3
+ Custom Figure subclasses
4
+ ========================
5
+
6
+ You can pass a `.Figure` subclass to `.pyplot.figure` if you want to change
7
+ the default behavior of the figure.
8
+
9
+ This example defines a `.Figure` subclass ``WatermarkFigure`` that accepts an
10
+ additional parameter ``watermark`` to display a custom watermark text. The
11
+ figure is created using the ``FigureClass`` parameter of `.pyplot.figure`.
12
+ The additional ``watermark`` parameter is passed on to the subclass
13
+ constructor.
14
+ """
15
+
16
+ import matplotlib.pyplot as plt
17
+ import numpy as np
18
+
19
+ from matplotlib.figure import Figure
20
+
21
+
22
+ class WatermarkFigure(Figure):
23
+ """A figure with a text watermark."""
24
+
25
+ def __init__(self, *args, watermark=None, **kwargs):
26
+ super().__init__(*args, **kwargs)
27
+
28
+ if watermark is not None:
29
+ bbox = dict(boxstyle='square', lw=3, ec='gray',
30
+ fc=(0.9, 0.9, .9, .5), alpha=0.5)
31
+ self.text(0.5, 0.5, watermark,
32
+ ha='center', va='center', rotation=30,
33
+ fontsize=40, color='gray', alpha=0.5, bbox=bbox)
34
+
35
+
36
+ x = np.linspace(-3, 3, 201)
37
+ y = np.tanh(x) + 0.1 * np.cos(5 * x)
38
+
39
+ plt.figure(FigureClass=WatermarkFigure, watermark='draft')
40
+ plt.plot(x, y)
41
+
42
+
43
+ # %%
44
+ #
45
+ # .. admonition:: References
46
+ #
47
+ # The use of the following functions, methods, classes and modules is shown
48
+ # in this example:
49
+ #
50
+ # - `matplotlib.pyplot.figure`
51
+ # - `matplotlib.figure.Figure`
52
+ # - `matplotlib.figure.Figure.text`
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/demo_tight_layout.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ===============================
3
+ Resizing axes with tight layout
4
+ ===============================
5
+
6
+ `~.Figure.tight_layout` attempts to resize subplots in a figure so that there
7
+ are no overlaps between axes objects and labels on the axes.
8
+
9
+ See :ref:`tight_layout_guide` for more details and
10
+ :ref:`constrainedlayout_guide` for an alternative.
11
+
12
+ """
13
+
14
+ import itertools
15
+ import warnings
16
+
17
+ import matplotlib.pyplot as plt
18
+
19
+ fontsizes = itertools.cycle([8, 16, 24, 32])
20
+
21
+
22
+ def example_plot(ax):
23
+ ax.plot([1, 2])
24
+ ax.set_xlabel('x-label', fontsize=next(fontsizes))
25
+ ax.set_ylabel('y-label', fontsize=next(fontsizes))
26
+ ax.set_title('Title', fontsize=next(fontsizes))
27
+
28
+
29
+ # %%
30
+
31
+ fig, ax = plt.subplots()
32
+ example_plot(ax)
33
+ fig.tight_layout()
34
+
35
+ # %%
36
+
37
+ fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
38
+ example_plot(ax1)
39
+ example_plot(ax2)
40
+ example_plot(ax3)
41
+ example_plot(ax4)
42
+ fig.tight_layout()
43
+
44
+ # %%
45
+
46
+ fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
47
+ example_plot(ax1)
48
+ example_plot(ax2)
49
+ fig.tight_layout()
50
+
51
+ # %%
52
+
53
+ fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
54
+ example_plot(ax1)
55
+ example_plot(ax2)
56
+ fig.tight_layout()
57
+
58
+ # %%
59
+
60
+ fig, axs = plt.subplots(nrows=3, ncols=3)
61
+ for ax in axs.flat:
62
+ example_plot(ax)
63
+ fig.tight_layout()
64
+
65
+ # %%
66
+
67
+ plt.figure()
68
+ ax1 = plt.subplot(221)
69
+ ax2 = plt.subplot(223)
70
+ ax3 = plt.subplot(122)
71
+ example_plot(ax1)
72
+ example_plot(ax2)
73
+ example_plot(ax3)
74
+ plt.tight_layout()
75
+
76
+ # %%
77
+
78
+ plt.figure()
79
+ ax1 = plt.subplot2grid((3, 3), (0, 0))
80
+ ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
81
+ ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
82
+ ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
83
+ example_plot(ax1)
84
+ example_plot(ax2)
85
+ example_plot(ax3)
86
+ example_plot(ax4)
87
+ plt.tight_layout()
88
+
89
+ # %%
90
+
91
+ fig = plt.figure()
92
+
93
+ gs1 = fig.add_gridspec(3, 1)
94
+ ax1 = fig.add_subplot(gs1[0])
95
+ ax2 = fig.add_subplot(gs1[1])
96
+ ax3 = fig.add_subplot(gs1[2])
97
+ example_plot(ax1)
98
+ example_plot(ax2)
99
+ example_plot(ax3)
100
+ gs1.tight_layout(fig, rect=[None, None, 0.45, None])
101
+
102
+ gs2 = fig.add_gridspec(2, 1)
103
+ ax4 = fig.add_subplot(gs2[0])
104
+ ax5 = fig.add_subplot(gs2[1])
105
+ example_plot(ax4)
106
+ example_plot(ax5)
107
+ with warnings.catch_warnings():
108
+ # gs2.tight_layout cannot handle the subplots from the first gridspec
109
+ # (gs1), so it will raise a warning. We are going to match the gridspecs
110
+ # manually so we can filter the warning away.
111
+ warnings.simplefilter("ignore", UserWarning)
112
+ gs2.tight_layout(fig, rect=[0.45, None, None, None])
113
+
114
+ # now match the top and bottom of two gridspecs.
115
+ top = min(gs1.top, gs2.top)
116
+ bottom = max(gs1.bottom, gs2.bottom)
117
+
118
+ gs1.update(top=top, bottom=bottom)
119
+ gs2.update(top=top, bottom=bottom)
120
+
121
+ plt.show()
122
+
123
+ # %%
124
+ #
125
+ # .. admonition:: References
126
+ #
127
+ # The use of the following functions, methods, classes and modules is shown
128
+ # in this example:
129
+ #
130
+ # - `matplotlib.figure.Figure.tight_layout` /
131
+ # `matplotlib.pyplot.tight_layout`
132
+ # - `matplotlib.figure.Figure.add_gridspec`
133
+ # - `matplotlib.figure.Figure.add_subplot`
134
+ # - `matplotlib.pyplot.subplot2grid`
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/gridspec_nested.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================
3
+ Nested Gridspecs
4
+ ================
5
+
6
+ GridSpecs can be nested, so that a subplot from a parent GridSpec can
7
+ set the position for a nested grid of subplots.
8
+
9
+ Note that the same functionality can be achieved more directly with
10
+ `~.FigureBase.subfigures`; see
11
+ :doc:`/gallery/subplots_axes_and_figures/subfigures`.
12
+
13
+ """
14
+ import matplotlib.pyplot as plt
15
+
16
+ import matplotlib.gridspec as gridspec
17
+
18
+
19
+ def format_axes(fig):
20
+ for i, ax in enumerate(fig.axes):
21
+ ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
22
+ ax.tick_params(labelbottom=False, labelleft=False)
23
+
24
+
25
+ # gridspec inside gridspec
26
+ fig = plt.figure()
27
+
28
+ gs0 = gridspec.GridSpec(1, 2, figure=fig)
29
+
30
+ gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0])
31
+
32
+ ax1 = fig.add_subplot(gs00[:-1, :])
33
+ ax2 = fig.add_subplot(gs00[-1, :-1])
34
+ ax3 = fig.add_subplot(gs00[-1, -1])
35
+
36
+ # the following syntax does the same as the GridSpecFromSubplotSpec call above:
37
+ gs01 = gs0[1].subgridspec(3, 3)
38
+
39
+ ax4 = fig.add_subplot(gs01[:, :-1])
40
+ ax5 = fig.add_subplot(gs01[:-1, -1])
41
+ ax6 = fig.add_subplot(gs01[-1, -1])
42
+
43
+ plt.suptitle("GridSpec Inside GridSpec")
44
+ format_axes(fig)
45
+
46
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/multiple_figs_demo.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ===================================
3
+ Managing multiple figures in pyplot
4
+ ===================================
5
+
6
+ `matplotlib.pyplot` uses the concept of a *current figure* and *current axes*.
7
+ Figures are identified via a figure number that is passed to `~.pyplot.figure`.
8
+ The figure with the given number is set as *current figure*. Additionally, if
9
+ no figure with the number exists, a new one is created.
10
+
11
+ .. note::
12
+
13
+ We discourage working with multiple figures through the implicit pyplot
14
+ interface because managing the *current figure* is cumbersome and
15
+ error-prone. Instead, we recommend using the explicit approach and call
16
+ methods on Figure and Axes instances. See :ref:`api_interfaces` for an
17
+ explanation of the trade-offs between the implicit and explicit interfaces.
18
+
19
+ """
20
+ import matplotlib.pyplot as plt
21
+ import numpy as np
22
+
23
+ t = np.arange(0.0, 2.0, 0.01)
24
+ s1 = np.sin(2*np.pi*t)
25
+ s2 = np.sin(4*np.pi*t)
26
+
27
+ # %%
28
+ # Create figure 1
29
+
30
+ plt.figure(1)
31
+ plt.subplot(211)
32
+ plt.plot(t, s1)
33
+ plt.subplot(212)
34
+ plt.plot(t, 2*s1)
35
+
36
+ # %%
37
+ # Create figure 2
38
+
39
+ plt.figure(2)
40
+ plt.plot(t, s2)
41
+
42
+ # %%
43
+ # Now switch back to figure 1 and make some changes
44
+
45
+ plt.figure(1)
46
+ plt.subplot(211)
47
+ plt.plot(t, s2, 's')
48
+ ax = plt.gca()
49
+ ax.set_xticklabels([])
50
+
51
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/subplots_axes_and_figures/subplot.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =================
3
+ Multiple subplots
4
+ =================
5
+
6
+ Simple demo with multiple subplots.
7
+
8
+ For more options, see :doc:`/gallery/subplots_axes_and_figures/subplots_demo`.
9
+
10
+ .. redirect-from:: /gallery/subplots_axes_and_figures/subplot_demo
11
+ """
12
+
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+
16
+ # Create some fake data.
17
+ x1 = np.linspace(0.0, 5.0)
18
+ y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
19
+ x2 = np.linspace(0.0, 2.0)
20
+ y2 = np.cos(2 * np.pi * x2)
21
+
22
+ # %%
23
+ # `~.pyplot.subplots()` is the recommended method to generate simple subplot
24
+ # arrangements:
25
+
26
+ fig, (ax1, ax2) = plt.subplots(2, 1)
27
+ fig.suptitle('A tale of 2 subplots')
28
+
29
+ ax1.plot(x1, y1, 'o-')
30
+ ax1.set_ylabel('Damped oscillation')
31
+
32
+ ax2.plot(x2, y2, '.-')
33
+ ax2.set_xlabel('time (s)')
34
+ ax2.set_ylabel('Undamped')
35
+
36
+ plt.show()
37
+
38
+ # %%
39
+ # Subplots can also be generated one at a time using `~.pyplot.subplot()`:
40
+
41
+ plt.subplot(2, 1, 1)
42
+ plt.plot(x1, y1, 'o-')
43
+ plt.title('A tale of 2 subplots')
44
+ plt.ylabel('Damped oscillation')
45
+
46
+ plt.subplot(2, 1, 2)
47
+ plt.plot(x2, y2, '.-')
48
+ plt.xlabel('time (s)')
49
+ plt.ylabel('Undamped')
50
+
51
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/fancytextbox_demo.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==================
3
+ Styling text boxes
4
+ ==================
5
+
6
+ This example shows how to style text boxes using *bbox* parameters.
7
+ """
8
+ import matplotlib.pyplot as plt
9
+
10
+ plt.text(0.6, 0.7, "eggs", size=50, rotation=30.,
11
+ ha="center", va="center",
12
+ bbox=dict(boxstyle="round",
13
+ ec=(1., 0.5, 0.5),
14
+ fc=(1., 0.8, 0.8),
15
+ )
16
+ )
17
+
18
+ plt.text(0.55, 0.6, "spam", size=50, rotation=-25.,
19
+ ha="right", va="top",
20
+ bbox=dict(boxstyle="square",
21
+ ec=(1., 0.5, 0.5),
22
+ fc=(1., 0.8, 0.8),
23
+ )
24
+ )
25
+
26
+ plt.show()
testbed/matplotlib__matplotlib/galleries/examples/text_labels_and_annotations/mathtext_demo.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ========
3
+ Mathtext
4
+ ========
5
+
6
+ Use Matplotlib's internal LaTeX parser and layout engine. For true LaTeX
7
+ rendering, see the text.usetex option.
8
+ """
9
+
10
+ import matplotlib.pyplot as plt
11
+
12
+ fig, ax = plt.subplots()
13
+
14
+ ax.plot([1, 2, 3], label=r'$\sqrt{x^2}$')
15
+ ax.legend()
16
+
17
+ ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
18
+ ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
19
+ ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} '
20
+ r'\Delta_{i+1}^j$', fontsize=20)
21
+
22
+ tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
23
+ ax.text(1, 1.6, tex, fontsize=20, va='bottom')
24
+
25
+ fig.tight_layout()
26
+ plt.show()
testbed/matplotlib__matplotlib/galleries/plot_types/README.rst ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _plot_types:
2
+
3
+ .. redirect-from:: /tutorials/basic/sample_plots
4
+
5
+ Plot types
6
+ ==========
7
+
8
+ Overview of many common plotting commands provided by Matplotlib.
9
+
10
+ See the `gallery <../gallery/index.html>`_ for more examples and
11
+ the `tutorials page <../tutorials/index.html>`_ for longer examples.
testbed/matplotlib__matplotlib/galleries/plot_types/stats/hist2d.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============
3
+ hist2d(x, y)
4
+ ============
5
+
6
+ See `~matplotlib.axes.Axes.hist2d`.
7
+ """
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+
11
+ plt.style.use('_mpl-gallery-nogrid')
12
+
13
+ # make data: correlated + noise
14
+ np.random.seed(1)
15
+ x = np.random.randn(5000)
16
+ y = 1.2 * x + np.random.randn(5000) / 3
17
+
18
+ # plot:
19
+ fig, ax = plt.subplots()
20
+
21
+ ax.hist2d(x, y, bins=(np.arange(-3, 3, 0.1), np.arange(-3, 3, 0.1)))
22
+
23
+ ax.set(xlim=(-2, 2), ylim=(-3, 3))
24
+
25
+ plt.show()
testbed/matplotlib__matplotlib/galleries/plot_types/stats/pie.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ======
3
+ pie(x)
4
+ ======
5
+
6
+ See `~matplotlib.axes.Axes.pie`.
7
+ """
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+
11
+ plt.style.use('_mpl-gallery-nogrid')
12
+
13
+
14
+ # make data
15
+ x = [1, 2, 3, 4]
16
+ colors = plt.get_cmap('Blues')(np.linspace(0.2, 0.7, len(x)))
17
+
18
+ # plot
19
+ fig, ax = plt.subplots()
20
+ ax.pie(x, colors=colors, radius=3, center=(4, 4),
21
+ wedgeprops={"linewidth": 1, "edgecolor": "white"}, frame=True)
22
+
23
+ ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
24
+ ylim=(0, 8), yticks=np.arange(1, 8))
25
+
26
+ plt.show()
testbed/matplotlib__matplotlib/galleries/plot_types/stats/violin.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =============
3
+ violinplot(D)
4
+ =============
5
+
6
+ See `~matplotlib.axes.Axes.violinplot`.
7
+ """
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+
11
+ plt.style.use('_mpl-gallery')
12
+
13
+ # make data:
14
+ np.random.seed(10)
15
+ D = np.random.normal((3, 5, 4), (0.75, 1.00, 0.75), (200, 3))
16
+
17
+ # plot:
18
+ fig, ax = plt.subplots()
19
+
20
+ vp = ax.violinplot(D, [2, 4, 6], widths=2,
21
+ showmeans=False, showmedians=False, showextrema=False)
22
+ # styling:
23
+ for body in vp['bodies']:
24
+ body.set_alpha(0.9)
25
+ ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
26
+ ylim=(0, 8), yticks=np.arange(1, 8))
27
+
28
+ plt.show()
testbed/matplotlib__matplotlib/galleries/users_explain/animations/animations.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/introductory/animation_tutorial
3
+
4
+ .. _animations:
5
+
6
+ ===========================
7
+ Animations using Matplotlib
8
+ ===========================
9
+
10
+ Based on its plotting functionality, Matplotlib also provides an interface to
11
+ generate animations using the `~matplotlib.animation` module. An
12
+ animation is a sequence of frames where each frame corresponds to a plot on a
13
+ `~matplotlib.figure.Figure`. This tutorial covers a general guideline on
14
+ how to create such animations and the different options available.
15
+ """
16
+
17
+ import matplotlib.pyplot as plt
18
+ import numpy as np
19
+
20
+ import matplotlib.animation as animation
21
+
22
+ # %%
23
+ # Animation Classes
24
+ # =================
25
+ #
26
+ # The animation process in Matplotlib can be thought of in 2 different ways:
27
+ #
28
+ # - `~matplotlib.animation.FuncAnimation`: Generate data for first
29
+ # frame and then modify this data for each frame to create an animated plot.
30
+ #
31
+ # - `~matplotlib.animation.ArtistAnimation`: Generate a list (iterable)
32
+ # of artists that will draw in each frame in the animation.
33
+ #
34
+ # `~matplotlib.animation.FuncAnimation` is more efficient in terms of
35
+ # speed and memory as it draws an artist once and then modifies it. On the
36
+ # other hand `~matplotlib.animation.ArtistAnimation` is flexible as it
37
+ # allows any iterable of artists to be animated in a sequence.
38
+ #
39
+ # ``FuncAnimation``
40
+ # -----------------
41
+ #
42
+ # The `~matplotlib.animation.FuncAnimation` class allows us to create an
43
+ # animation by passing a function that iteratively modifies the data of a plot.
44
+ # This is achieved by using the *setter* methods on various
45
+ # `~matplotlib.artist.Artist` (examples: `~matplotlib.lines.Line2D`,
46
+ # `~matplotlib.collections.PathCollection`, etc.). A usual
47
+ # `~matplotlib.animation.FuncAnimation` object takes a
48
+ # `~matplotlib.figure.Figure` that we want to animate and a function
49
+ # *func* that modifies the data plotted on the figure. It uses the *frames*
50
+ # parameter to determine the length of the animation. The *interval* parameter
51
+ # is used to determine time in milliseconds between drawing of two frames.
52
+ # Animating using `.FuncAnimation` would usually follow the following
53
+ # structure:
54
+ #
55
+ # - Plot the initial figure, including all the required artists. Save all the
56
+ # artists in variables so that they can be updated later on during the
57
+ # animation.
58
+ # - Create an animation function that updates the data in each artist to
59
+ # generate the new frame at each function call.
60
+ # - Create a `.FuncAnimation` object with the `.Figure` and the animation
61
+ # function, along with the keyword arguments that determine the animation
62
+ # properties.
63
+ # - Use `.animation.Animation.save` or `.pyplot.show` to save or show the
64
+ # animation.
65
+ #
66
+ # The update function uses the ``set_*`` function for different artists to
67
+ # modify the data. The following table shows a few plotting methods, the artist
68
+ # types they return and some methods that can be used to update them.
69
+ #
70
+ # ======================================== ============================= ===========================
71
+ # Plotting method Artist Set method
72
+ # ======================================== ============================= ===========================
73
+ # `.Axes.plot` `.lines.Line2D` `~.lines.Line2D.set_data`
74
+ # `.Axes.scatter` `.collections.PathCollection` `~.collections.\
75
+ # PathCollection.set_offsets`
76
+ # `.Axes.imshow` `.image.AxesImage` ``AxesImage.set_data``
77
+ # `.Axes.annotate` `.text.Annotation` `~.text.Annotation.\
78
+ # update_positions`
79
+ # `.Axes.barh` `.patches.Rectangle` `~.Rectangle.set_angle`,
80
+ # `~.Rectangle.set_bounds`,
81
+ # `~.Rectangle.set_height`,
82
+ # `~.Rectangle.set_width`,
83
+ # `~.Rectangle.set_x`,
84
+ # `~.Rectangle.set_y`,
85
+ # `~.Rectangle.set_xy`
86
+ # `.Axes.fill` `.patches.Polygon` `~.Polygon.set_xy`
87
+ # `.Axes.add_patch`\(`.patches.Ellipse`\) `.patches.Ellipse` `~.Ellipse.set_angle`,
88
+ # `~.Ellipse.set_center`,
89
+ # `~.Ellipse.set_height`,
90
+ # `~.Ellipse.set_width`
91
+ # ======================================== ============================= ===========================
92
+ #
93
+ # Covering the set methods for all types of artists is beyond the scope of this
94
+ # tutorial but can be found in their respective documentations. An example of
95
+ # such update methods in use for `.Axes.scatter` and `.Axes.plot` is as follows.
96
+
97
+ fig, ax = plt.subplots()
98
+ t = np.linspace(0, 3, 40)
99
+ g = -9.81
100
+ v0 = 12
101
+ z = g * t**2 / 2 + v0 * t
102
+
103
+ v02 = 5
104
+ z2 = g * t**2 / 2 + v02 * t
105
+
106
+ scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s')
107
+ line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0]
108
+ ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]')
109
+ ax.legend()
110
+
111
+
112
+ def update(frame):
113
+ # for each frame, update the data stored on each artist.
114
+ x = t[:frame]
115
+ y = z[:frame]
116
+ # update the scatter plot:
117
+ data = np.stack([x, y]).T
118
+ scat.set_offsets(data)
119
+ # update the line plot:
120
+ line2.set_xdata(t[:frame])
121
+ line2.set_ydata(z2[:frame])
122
+ return (scat, line2)
123
+
124
+
125
+ ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
126
+ plt.show()
127
+
128
+
129
+ # %%
130
+ # ``ArtistAnimation``
131
+ # -------------------
132
+ #
133
+ # `~matplotlib.animation.ArtistAnimation` can be used
134
+ # to generate animations if there is data stored on various different artists.
135
+ # This list of artists is then converted frame by frame into an animation. For
136
+ # example, when we use `.Axes.barh` to plot a bar-chart, it creates a number of
137
+ # artists for each of the bar and error bars. To update the plot, one would
138
+ # need to update each of the bars from the container individually and redraw
139
+ # them. Instead, `.animation.ArtistAnimation` can be used to plot each frame
140
+ # individually and then stitched together to form an animation. A barchart race
141
+ # is a simple example for this.
142
+
143
+
144
+ fig, ax = plt.subplots()
145
+ rng = np.random.default_rng(19680801)
146
+ data = np.array([20, 20, 20, 20])
147
+ x = np.array([1, 2, 3, 4])
148
+
149
+ artists = []
150
+ colors = ['tab:blue', 'tab:red', 'tab:green', 'tab:purple']
151
+ for i in range(20):
152
+ data += rng.integers(low=0, high=10, size=data.shape)
153
+ container = ax.barh(x, data, color=colors)
154
+ artists.append(container)
155
+
156
+
157
+ ani = animation.ArtistAnimation(fig=fig, artists=artists, interval=400)
158
+ plt.show()
159
+
160
+ # %%
161
+ # Animation Writers
162
+ # =================
163
+ #
164
+ # Animation objects can be saved to disk using various multimedia writers
165
+ # (ex: Pillow, *ffpmeg*, *imagemagick*). Not all video formats are supported
166
+ # by all writers. There are 4 major types of writers:
167
+ #
168
+ # - `~matplotlib.animation.PillowWriter` - Uses the Pillow library to
169
+ # create the animation.
170
+ #
171
+ # - `~matplotlib.animation.HTMLWriter` - Used to create JavaScript-based
172
+ # animations.
173
+ #
174
+ # - Pipe-based writers - `~matplotlib.animation.FFMpegWriter` and
175
+ # `~matplotlib.animation.ImageMagickWriter` are pipe based writers.
176
+ # These writers pipe each frame to the utility (*ffmpeg* / *imagemagick*)
177
+ # which then stitches all of them together to create the animation.
178
+ #
179
+ # - File-based writers - `~matplotlib.animation.FFMpegFileWriter` and
180
+ # `~matplotlib.animation.ImageMagickFileWriter` are examples of
181
+ # file-based writers. These writers are slower than their pipe-based
182
+ # alternatives but are more useful for debugging as they save each frame in
183
+ # a file before stitching them together into an animation.
184
+ #
185
+ # Saving Animations
186
+ # -----------------
187
+ #
188
+ # .. list-table::
189
+ # :header-rows: 1
190
+ #
191
+ # * - Writer
192
+ # - Supported Formats
193
+ # * - `~matplotlib.animation.PillowWriter`
194
+ # - .gif, .apng, .webp
195
+ # * - `~matplotlib.animation.HTMLWriter`
196
+ # - .htm, .html, .png
197
+ # * - | `~matplotlib.animation.FFMpegWriter`
198
+ # | `~matplotlib.animation.FFMpegFileWriter`
199
+ # - All formats supported by |ffmpeg|_: ``ffmpeg -formats``
200
+ # * - | `~matplotlib.animation.ImageMagickWriter`
201
+ # | `~matplotlib.animation.ImageMagickFileWriter`
202
+ # - All formats supported by |imagemagick|_: ``magick -list format``
203
+ #
204
+ # .. _ffmpeg: https://www.ffmpeg.org/general.html#Supported-File-Formats_002c-Codecs-or-Features
205
+ # .. |ffmpeg| replace:: *ffmpeg*
206
+ #
207
+ # .. _imagemagick: https://imagemagick.org/script/formats.php#supported
208
+ # .. |imagemagick| replace:: *imagemagick*
209
+ #
210
+ # To save animations using any of the writers, we can use the
211
+ # `.animation.Animation.save` method. It takes the *filename* that we want to
212
+ # save the animation as and the *writer*, which is either a string or a writer
213
+ # object. It also takes an *fps* argument. This argument is different than the
214
+ # *interval* argument that `~.animation.FuncAnimation` or
215
+ # `~.animation.ArtistAnimation` uses. *fps* determines the frame rate that the
216
+ # **saved** animation uses, whereas *interval* determines the frame rate that
217
+ # the **displayed** animation uses.
218
+ #
219
+ # Below are a few examples that show how to save an animation with different
220
+ # writers.
221
+ #
222
+ #
223
+ # Pillow writers::
224
+ #
225
+ # ani.save(filename="/tmp/pillow_example.gif", writer="pillow")
226
+ # ani.save(filename="/tmp/pillow_example.apng", writer="pillow")
227
+ #
228
+ # HTML writers::
229
+ #
230
+ # ani.save(filename="/tmp/html_example.html", writer="html")
231
+ # ani.save(filename="/tmp/html_example.htm", writer="html")
232
+ # ani.save(filename="/tmp/html_example.png", writer="html")
233
+ #
234
+ # FFMpegWriter::
235
+ #
236
+ # ani.save(filename="/tmp/ffmpeg_example.mkv", writer="ffmpeg")
237
+ # ani.save(filename="/tmp/ffmpeg_example.mp4", writer="ffmpeg")
238
+ # ani.save(filename="/tmp/ffmpeg_example.mjpeg", writer="ffmpeg")
239
+ #
240
+ # Imagemagick writers::
241
+ #
242
+ # ani.save(filename="/tmp/imagemagick_example.gif", writer="imagemagick")
243
+ # ani.save(filename="/tmp/imagemagick_example.webp", writer="imagemagick")
244
+ # ani.save(filename="apng:/tmp/imagemagick_example.apng",
245
+ # writer="imagemagick", extra_args=["-quality", "100"])
246
+ #
247
+ # (the ``extra_args`` for *apng* are needed to reduce filesize by ~10x)
testbed/matplotlib__matplotlib/galleries/users_explain/animations/blitting.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/advanced/blitting
3
+
4
+ .. _blitting:
5
+
6
+ ==================================
7
+ Faster rendering by using blitting
8
+ ==================================
9
+
10
+ *Blitting* is a `standard technique
11
+ <https://en.wikipedia.org/wiki/Bit_blit>`__ in raster graphics that,
12
+ in the context of Matplotlib, can be used to (drastically) improve
13
+ performance of interactive figures. For example, the
14
+ :mod:`.animation` and :mod:`.widgets` modules use blitting
15
+ internally. Here, we demonstrate how to implement your own blitting, outside
16
+ of these classes.
17
+
18
+ Blitting speeds up repetitive drawing by rendering all non-changing
19
+ graphic elements into a background image once. Then, for every draw, only the
20
+ changing elements need to be drawn onto this background. For example,
21
+ if the limits of an Axes have not changed, we can render the empty Axes
22
+ including all ticks and labels once, and only draw the changing data later.
23
+
24
+ The strategy is
25
+
26
+ - Prepare the constant background:
27
+
28
+ - Draw the figure, but exclude all artists that you want to animate by
29
+ marking them as *animated* (see `.Artist.set_animated`).
30
+ - Save a copy of the RBGA buffer.
31
+
32
+ - Render the individual images:
33
+
34
+ - Restore the copy of the RGBA buffer.
35
+ - Redraw the animated artists using `.Axes.draw_artist` /
36
+ `.Figure.draw_artist`.
37
+ - Show the resulting image on the screen.
38
+
39
+ One consequence of this procedure is that your animated artists are always
40
+ drawn on top of the static artists.
41
+
42
+ Not all backends support blitting. You can check if a given canvas does via
43
+ the `.FigureCanvasBase.supports_blit` property.
44
+
45
+ .. warning::
46
+
47
+ This code does not work with the OSX backend (but does work with other
48
+ GUI backends on Mac).
49
+
50
+ Minimal example
51
+ ---------------
52
+
53
+ We can use the `.FigureCanvasAgg` methods
54
+ `~.FigureCanvasAgg.copy_from_bbox` and
55
+ `~.FigureCanvasAgg.restore_region` in conjunction with setting
56
+ ``animated=True`` on our artist to implement a minimal example that
57
+ uses blitting to accelerate rendering
58
+
59
+ """
60
+
61
+ import matplotlib.pyplot as plt
62
+ import numpy as np
63
+
64
+ x = np.linspace(0, 2 * np.pi, 100)
65
+
66
+ fig, ax = plt.subplots()
67
+
68
+ # animated=True tells matplotlib to only draw the artist when we
69
+ # explicitly request it
70
+ (ln,) = ax.plot(x, np.sin(x), animated=True)
71
+
72
+ # make sure the window is raised, but the script keeps going
73
+ plt.show(block=False)
74
+
75
+ # stop to admire our empty window axes and ensure it is rendered at
76
+ # least once.
77
+ #
78
+ # We need to fully draw the figure at its final size on the screen
79
+ # before we continue on so that :
80
+ # a) we have the correctly sized and drawn background to grab
81
+ # b) we have a cached renderer so that ``ax.draw_artist`` works
82
+ # so we spin the event loop to let the backend process any pending operations
83
+ plt.pause(0.1)
84
+
85
+ # get copy of entire figure (everything inside fig.bbox) sans animated artist
86
+ bg = fig.canvas.copy_from_bbox(fig.bbox)
87
+ # draw the animated artist, this uses a cached renderer
88
+ ax.draw_artist(ln)
89
+ # show the result to the screen, this pushes the updated RGBA buffer from the
90
+ # renderer to the GUI framework so you can see it
91
+ fig.canvas.blit(fig.bbox)
92
+
93
+ for j in range(100):
94
+ # reset the background back in the canvas state, screen unchanged
95
+ fig.canvas.restore_region(bg)
96
+ # update the artist, neither the canvas state nor the screen have changed
97
+ ln.set_ydata(np.sin(x + (j / 100) * np.pi))
98
+ # re-render the artist, updating the canvas state, but not the screen
99
+ ax.draw_artist(ln)
100
+ # copy the image to the GUI state, but screen might not be changed yet
101
+ fig.canvas.blit(fig.bbox)
102
+ # flush any pending GUI events, re-painting the screen if needed
103
+ fig.canvas.flush_events()
104
+ # you can put a pause in if you want to slow things down
105
+ # plt.pause(.1)
106
+
107
+ # %%
108
+ # This example works and shows a simple animation, however because we
109
+ # are only grabbing the background once, if the size of the figure in
110
+ # pixels changes (due to either the size or dpi of the figure
111
+ # changing) , the background will be invalid and result in incorrect
112
+ # (but sometimes cool looking!) images. There is also a global
113
+ # variable and a fair amount of boilerplate which suggests we should
114
+ # wrap this in a class.
115
+ #
116
+ # Class-based example
117
+ # -------------------
118
+ #
119
+ # We can use a class to encapsulate the boilerplate logic and state of
120
+ # restoring the background, drawing the artists, and then blitting the
121
+ # result to the screen. Additionally, we can use the ``'draw_event'``
122
+ # callback to capture a new background whenever a full re-draw
123
+ # happens to handle resizes correctly.
124
+
125
+
126
+ class BlitManager:
127
+ def __init__(self, canvas, animated_artists=()):
128
+ """
129
+ Parameters
130
+ ----------
131
+ canvas : FigureCanvasAgg
132
+ The canvas to work with, this only works for subclasses of the Agg
133
+ canvas which have the `~FigureCanvasAgg.copy_from_bbox` and
134
+ `~FigureCanvasAgg.restore_region` methods.
135
+
136
+ animated_artists : Iterable[Artist]
137
+ List of the artists to manage
138
+ """
139
+ self.canvas = canvas
140
+ self._bg = None
141
+ self._artists = []
142
+
143
+ for a in animated_artists:
144
+ self.add_artist(a)
145
+ # grab the background on every draw
146
+ self.cid = canvas.mpl_connect("draw_event", self.on_draw)
147
+
148
+ def on_draw(self, event):
149
+ """Callback to register with 'draw_event'."""
150
+ cv = self.canvas
151
+ if event is not None:
152
+ if event.canvas != cv:
153
+ raise RuntimeError
154
+ self._bg = cv.copy_from_bbox(cv.figure.bbox)
155
+ self._draw_animated()
156
+
157
+ def add_artist(self, art):
158
+ """
159
+ Add an artist to be managed.
160
+
161
+ Parameters
162
+ ----------
163
+ art : Artist
164
+
165
+ The artist to be added. Will be set to 'animated' (just
166
+ to be safe). *art* must be in the figure associated with
167
+ the canvas this class is managing.
168
+
169
+ """
170
+ if art.figure != self.canvas.figure:
171
+ raise RuntimeError
172
+ art.set_animated(True)
173
+ self._artists.append(art)
174
+
175
+ def _draw_animated(self):
176
+ """Draw all of the animated artists."""
177
+ fig = self.canvas.figure
178
+ for a in self._artists:
179
+ fig.draw_artist(a)
180
+
181
+ def update(self):
182
+ """Update the screen with animated artists."""
183
+ cv = self.canvas
184
+ fig = cv.figure
185
+ # paranoia in case we missed the draw event,
186
+ if self._bg is None:
187
+ self.on_draw(None)
188
+ else:
189
+ # restore the background
190
+ cv.restore_region(self._bg)
191
+ # draw all of the animated artists
192
+ self._draw_animated()
193
+ # update the GUI state
194
+ cv.blit(fig.bbox)
195
+ # let the GUI event loop process anything it has to do
196
+ cv.flush_events()
197
+
198
+
199
+ # %%
200
+ # Here is how we would use our class. This is a slightly more complicated
201
+ # example than the first case as we add a text frame counter as well.
202
+
203
+ # make a new figure
204
+ fig, ax = plt.subplots()
205
+ # add a line
206
+ (ln,) = ax.plot(x, np.sin(x), animated=True)
207
+ # add a frame number
208
+ fr_number = ax.annotate(
209
+ "0",
210
+ (0, 1),
211
+ xycoords="axes fraction",
212
+ xytext=(10, -10),
213
+ textcoords="offset points",
214
+ ha="left",
215
+ va="top",
216
+ animated=True,
217
+ )
218
+ bm = BlitManager(fig.canvas, [ln, fr_number])
219
+ # make sure our window is on the screen and drawn
220
+ plt.show(block=False)
221
+ plt.pause(.1)
222
+
223
+ for j in range(100):
224
+ # update the artists
225
+ ln.set_ydata(np.sin(x + (j / 100) * np.pi))
226
+ fr_number.set_text(f"frame: {j}")
227
+ # tell the blitting manager to do its thing
228
+ bm.update()
229
+
230
+ # %%
231
+ # This class does not depend on `.pyplot` and is suitable to embed
232
+ # into larger GUI application.
testbed/matplotlib__matplotlib/galleries/users_explain/artists/artist_intro.rst ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _users_artists:
2
+
3
+ Introduction to Artists
4
+ -----------------------
5
+
6
+ Almost all objects you interact with on a Matplotlib plot are called "Artist"
7
+ (and are subclasses of the `.Artist` class). :doc:`Figure <../figure/index>`
8
+ and :doc:`Axes <../axes/index>` are Artists, and generally contain
9
+ `~.axis.Axis` Artists and Artists that contain data or annotation information.
10
+
11
+
12
+ Creating Artists
13
+ ~~~~~~~~~~~~~~~~
14
+
15
+ Usually we do not instantiate Artists directly, but rather use a plotting
16
+ method on `~.axes.Axes`. Some examples of plotting methods and the Artist
17
+ object they create is given below:
18
+
19
+ ========================================= =================
20
+ Axes helper method Artist
21
+ ========================================= =================
22
+ `~.axes.Axes.annotate` - text annotations `.Annotation`
23
+ `~.axes.Axes.bar` - bar charts `.Rectangle`
24
+ `~.axes.Axes.errorbar` - error bar plots `.Line2D` and
25
+ `.Rectangle`
26
+ `~.axes.Axes.fill` - shared area `.Polygon`
27
+ `~.axes.Axes.hist` - histograms `.Rectangle`
28
+ `~.axes.Axes.imshow` - image data `.AxesImage`
29
+ `~.axes.Axes.legend` - Axes legend `.Legend`
30
+ `~.axes.Axes.plot` - xy plots `.Line2D`
31
+ `~.axes.Axes.scatter` - scatter charts `.PolyCollection`
32
+ `~.axes.Axes.text` - text `.Text`
33
+ ========================================= =================
34
+
35
+ As an example, we can save the Line2D Artist returned from `.axes.Axes.plot`:
36
+
37
+ .. sourcecode:: ipython
38
+
39
+ In [209]: import matplotlib.pyplot as plt
40
+ In [210]: import matplotlib.artist as martist
41
+ In [211]: import numpy as np
42
+
43
+ In [212]: fig, ax = plt.subplots()
44
+ In [213]: x, y = np.random.rand(2, 100)
45
+ In [214]: lines = ax.plot(x, y, '-', label='example')
46
+ In [215]: print(lines)
47
+ [<matplotlib.lines.Line2D at 0xd378b0c>]
48
+
49
+ Note that ``plot`` returns a _list_ of lines because you can pass in multiple x,
50
+ y pairs to plot. The line has been added to the Axes, and we can retrieve the
51
+ Artist via `~.Axes.get_lines()`:
52
+
53
+ .. sourcecode:: ipython
54
+
55
+ In [216]: print(ax.get_lines())
56
+ <a list of 1 Line2D objects>
57
+ In [217]: print(ax.get_lines()[0])
58
+ Line2D(example)
59
+
60
+ Changing Artist properties
61
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
62
+
63
+ Getting the ``lines`` object gives us access to all the properties of the
64
+ Line2D object. So if we want to change the *linewidth* after the fact, we can do so using `.Artist.set`.
65
+
66
+ .. plot::
67
+ :include-source:
68
+
69
+ fig, ax = plt.subplots(figsize=(4, 2.5))
70
+ x = np.arange(0, 13, 0.2)
71
+ y = np.sin(x)
72
+ lines = ax.plot(x, y, '-', label='example', linewidth=0.2, color='blue')
73
+ lines[0].set(color='green', linewidth=2)
74
+
75
+ We can interrogate the full list of settable properties with
76
+ `matplotlib.artist.getp`:
77
+
78
+ .. sourcecode:: ipython
79
+
80
+ In [218]: martist.getp(lines[0])
81
+ agg_filter = None
82
+ alpha = None
83
+ animated = False
84
+ antialiased or aa = True
85
+ bbox = Bbox(x0=0.004013842290585101, y0=0.013914221641967...
86
+ children = []
87
+ clip_box = TransformedBbox( Bbox(x0=0.0, y0=0.0, x1=1.0, ...
88
+ clip_on = True
89
+ clip_path = None
90
+ color or c = blue
91
+ dash_capstyle = butt
92
+ dash_joinstyle = round
93
+ data = (array([0.91377845, 0.58456834, 0.36492019, 0.0379...
94
+ drawstyle or ds = default
95
+ figure = Figure(550x450)
96
+ fillstyle = full
97
+ gapcolor = None
98
+ gid = None
99
+ in_layout = True
100
+ label = example
101
+ linestyle or ls = -
102
+ linewidth or lw = 2.0
103
+ marker = None
104
+ markeredgecolor or mec = blue
105
+ markeredgewidth or mew = 1.0
106
+ markerfacecolor or mfc = blue
107
+ markerfacecoloralt or mfcalt = none
108
+ markersize or ms = 6.0
109
+ markevery = None
110
+ mouseover = False
111
+ path = Path(array([[0.91377845, 0.51224793], [0.58...
112
+ path_effects = []
113
+ picker = None
114
+ pickradius = 5
115
+ rasterized = False
116
+ sketch_params = None
117
+ snap = None
118
+ solid_capstyle = projecting
119
+ solid_joinstyle = round
120
+ tightbbox = Bbox(x0=70.4609002763619, y0=54.321277798941786, x...
121
+ transform = CompositeGenericTransform( TransformWrapper( ...
122
+ transformed_clip_path_and_affine = (None, None)
123
+ url = None
124
+ visible = True
125
+ window_extent = Bbox(x0=70.4609002763619, y0=54.321277798941786, x...
126
+ xdata = [0.91377845 0.58456834 0.36492019 0.03796664 0.884...
127
+ xydata = [[0.91377845 0.51224793] [0.58456834 0.9820474 ] ...
128
+ ydata = [0.51224793 0.9820474 0.24469912 0.61647032 0.483...
129
+ zorder = 2
130
+
131
+ Note most Artists also have a distinct list of setters; e.g.
132
+ `.Line2D.set_color` or `.Line2D.set_linewidth`.
133
+
134
+ Changing Artist data
135
+ ~~~~~~~~~~~~~~~~~~~~
136
+
137
+ In addition to styling properties like *color* and *linewidth*, the Line2D
138
+ object has a *data* property. You can set the data after the line has been
139
+ created using `.Line2D.set_data`. This is often used for Animations, where the
140
+ same line is shown evolving over time (see :doc:`../animations/index`)
141
+
142
+ .. plot::
143
+ :include-source:
144
+
145
+ fig, ax = plt.subplots(figsize=(4, 2.5))
146
+ x = np.arange(0, 13, 0.2)
147
+ y = np.sin(x)
148
+ lines = ax.plot(x, y, '-', label='example')
149
+ lines[0].set_data([x, np.cos(x)])
150
+
151
+ Manually adding Artists
152
+ ~~~~~~~~~~~~~~~~~~~~~~~
153
+
154
+ Not all Artists have helper methods, or you may want to use a low-level method
155
+ for some reason. For example the `.patches.Circle` Artist does not have a
156
+ helper, but we can still create and add to an Axes using the
157
+ `.axes.Axes.add_artist` method:
158
+
159
+ .. plot::
160
+ :include-source:
161
+
162
+ import matplotlib.patches as mpatches
163
+
164
+ fig, ax = plt.subplots(figsize=(4, 2.5))
165
+ circle = mpatches.Circle((0.5, 0.5), 0.25, ec="none")
166
+ ax.add_artist(circle)
167
+ clipped_circle = mpatches.Circle((1, 0.5), 0.125, ec="none", facecolor='C1')
168
+ ax.add_artist(clipped_circle)
169
+ ax.set_aspect(1)
170
+
171
+ The Circle takes the center and radius of the Circle as arguments to its
172
+ constructor; optional arguments are passed as keyword arguments.
173
+
174
+ Note that when we add an Artist manually like this, it doesn't necessarily
175
+ adjust the axis limits like most of the helper methods do, so the Artists can
176
+ be clipped, as is the case above for the ``clipped_circle`` patch.
177
+
178
+ See :ref:`artist_reference` for other patches.
179
+
180
+ Removing Artists
181
+ ~~~~~~~~~~~~~~~~
182
+
183
+ Sometimes we want to remove an Artist from a figure without re-specifying the
184
+ whole figure from scratch. Most Artists have a usable *remove* method that
185
+ will remove the Artist from its Axes list. For instance ``lines[0].remove()``
186
+ would remove the *Line2D* artist created in the example above.
testbed/matplotlib__matplotlib/galleries/users_explain/artists/imshow_extent.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/intermediate/imshow_extent
3
+
4
+ .. _imshow_extent:
5
+
6
+ *origin* and *extent* in `~.Axes.imshow`
7
+ ========================================
8
+
9
+ :meth:`~.Axes.imshow` allows you to render an image (either a 2D array which
10
+ will be color-mapped (based on *norm* and *cmap*) or a 3D RGB(A) array which
11
+ will be used as-is) to a rectangular region in data space. The orientation of
12
+ the image in the final rendering is controlled by the *origin* and *extent*
13
+ keyword arguments (and attributes on the resulting `.AxesImage` instance) and
14
+ the data limits of the axes.
15
+
16
+ The *extent* keyword arguments controls the bounding box in data coordinates
17
+ that the image will fill specified as ``(left, right, bottom, top)`` in **data
18
+ coordinates**, the *origin* keyword argument controls how the image fills that
19
+ bounding box, and the orientation in the final rendered image is also affected
20
+ by the axes limits.
21
+
22
+ .. hint:: Most of the code below is used for adding labels and informative
23
+ text to the plots. The described effects of *origin* and *extent* can be
24
+ seen in the plots without the need to follow all code details.
25
+
26
+ For a quick understanding, you may want to skip the code details below and
27
+ directly continue with the discussion of the results.
28
+ """
29
+ import matplotlib.pyplot as plt
30
+ import numpy as np
31
+
32
+ from matplotlib.gridspec import GridSpec
33
+
34
+
35
+ def index_to_coordinate(index, extent, origin):
36
+ """Return the pixel center of an index."""
37
+ left, right, bottom, top = extent
38
+
39
+ hshift = 0.5 * np.sign(right - left)
40
+ left, right = left + hshift, right - hshift
41
+ vshift = 0.5 * np.sign(top - bottom)
42
+ bottom, top = bottom + vshift, top - vshift
43
+
44
+ if origin == 'upper':
45
+ bottom, top = top, bottom
46
+
47
+ return {
48
+ "[0, 0]": (left, bottom),
49
+ "[M', 0]": (left, top),
50
+ "[0, N']": (right, bottom),
51
+ "[M', N']": (right, top),
52
+ }[index]
53
+
54
+
55
+ def get_index_label_pos(index, extent, origin, inverted_xindex):
56
+ """
57
+ Return the desired position and horizontal alignment of an index label.
58
+ """
59
+ if extent is None:
60
+ extent = lookup_extent(origin)
61
+ left, right, bottom, top = extent
62
+ x, y = index_to_coordinate(index, extent, origin)
63
+
64
+ is_x0 = index[-2:] == "0]"
65
+ halign = 'left' if is_x0 ^ inverted_xindex else 'right'
66
+ hshift = 0.5 * np.sign(left - right)
67
+ x += hshift * (1 if is_x0 else -1)
68
+ return x, y, halign
69
+
70
+
71
+ def get_color(index, data, cmap):
72
+ """Return the data color of an index."""
73
+ val = {
74
+ "[0, 0]": data[0, 0],
75
+ "[0, N']": data[0, -1],
76
+ "[M', 0]": data[-1, 0],
77
+ "[M', N']": data[-1, -1],
78
+ }[index]
79
+ return cmap(val / data.max())
80
+
81
+
82
+ def lookup_extent(origin):
83
+ """Return extent for label positioning when not given explicitly."""
84
+ if origin == 'lower':
85
+ return (-0.5, 6.5, -0.5, 5.5)
86
+ else:
87
+ return (-0.5, 6.5, 5.5, -0.5)
88
+
89
+
90
+ def set_extent_None_text(ax):
91
+ ax.text(3, 2.5, 'equals\nextent=None', size='large',
92
+ ha='center', va='center', color='w')
93
+
94
+
95
+ def plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim):
96
+ """Actually run ``imshow()`` and add extent and index labels."""
97
+ im = ax.imshow(data, origin=origin, extent=extent)
98
+
99
+ # extent labels (left, right, bottom, top)
100
+ left, right, bottom, top = im.get_extent()
101
+ if xlim is None or top > bottom:
102
+ upper_string, lower_string = 'top', 'bottom'
103
+ else:
104
+ upper_string, lower_string = 'bottom', 'top'
105
+ if ylim is None or left < right:
106
+ port_string, starboard_string = 'left', 'right'
107
+ inverted_xindex = False
108
+ else:
109
+ port_string, starboard_string = 'right', 'left'
110
+ inverted_xindex = True
111
+ bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': "round4"}
112
+ ann_kwargs = {'xycoords': 'axes fraction',
113
+ 'textcoords': 'offset points',
114
+ 'bbox': bbox_kwargs}
115
+ ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1),
116
+ ha='center', va='top', **ann_kwargs)
117
+ ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1),
118
+ ha='center', va='bottom', **ann_kwargs)
119
+ ax.annotate(port_string, xy=(0, .5), xytext=(1, 0),
120
+ ha='left', va='center', rotation=90,
121
+ **ann_kwargs)
122
+ ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0),
123
+ ha='right', va='center', rotation=-90,
124
+ **ann_kwargs)
125
+ ax.set_title(f'origin: {origin}')
126
+
127
+ # index labels
128
+ for index in ["[0, 0]", "[0, N']", "[M', 0]", "[M', N']"]:
129
+ tx, ty, halign = get_index_label_pos(index, extent, origin,
130
+ inverted_xindex)
131
+ facecolor = get_color(index, data, im.get_cmap())
132
+ ax.text(tx, ty, index, color='white', ha=halign, va='center',
133
+ bbox={'boxstyle': 'square', 'facecolor': facecolor})
134
+ if xlim:
135
+ ax.set_xlim(*xlim)
136
+ if ylim:
137
+ ax.set_ylim(*ylim)
138
+
139
+
140
+ def generate_imshow_demo_grid(extents, xlim=None, ylim=None):
141
+ N = len(extents)
142
+ fig = plt.figure(tight_layout=True)
143
+ fig.set_size_inches(6, N * (11.25) / 5)
144
+ gs = GridSpec(N, 5, figure=fig)
145
+
146
+ columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)],
147
+ 'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)],
148
+ 'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]}
149
+ x, y = np.ogrid[0:6, 0:7]
150
+ data = x + y
151
+
152
+ for origin in ['upper', 'lower']:
153
+ for ax, extent in zip(columns[origin], extents):
154
+ plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim)
155
+
156
+ columns['label'][0].set_title('extent=')
157
+ for ax, extent in zip(columns['label'], extents):
158
+ if extent is None:
159
+ text = 'None'
160
+ else:
161
+ left, right, bottom, top = extent
162
+ text = (f'left: {left:0.1f}\nright: {right:0.1f}\n'
163
+ f'bottom: {bottom:0.1f}\ntop: {top:0.1f}\n')
164
+ ax.text(1., .5, text, transform=ax.transAxes, ha='right', va='center')
165
+ ax.axis('off')
166
+ return columns
167
+
168
+
169
+ # %%
170
+ #
171
+ # Default extent
172
+ # --------------
173
+ #
174
+ # First, let's have a look at the default ``extent=None``
175
+
176
+ generate_imshow_demo_grid(extents=[None])
177
+
178
+ # %%
179
+ #
180
+ # Generally, for an array of shape (M, N), the first index runs along the
181
+ # vertical, the second index runs along the horizontal.
182
+ # The pixel centers are at integer positions ranging from 0 to ``N' = N - 1``
183
+ # horizontally and from 0 to ``M' = M - 1`` vertically.
184
+ # *origin* determines how the data is filled in the bounding box.
185
+ #
186
+ # For ``origin='lower'``:
187
+ #
188
+ # - [0, 0] is at (left, bottom)
189
+ # - [M', 0] is at (left, top)
190
+ # - [0, N'] is at (right, bottom)
191
+ # - [M', N'] is at (right, top)
192
+ #
193
+ # ``origin='upper'`` reverses the vertical axes direction and filling:
194
+ #
195
+ # - [0, 0] is at (left, top)
196
+ # - [M', 0] is at (left, bottom)
197
+ # - [0, N'] is at (right, top)
198
+ # - [M', N'] is at (right, bottom)
199
+ #
200
+ # In summary, the position of the [0, 0] index as well as the extent are
201
+ # influenced by *origin*:
202
+ #
203
+ # ====== =============== ==========================================
204
+ # origin [0, 0] position extent
205
+ # ====== =============== ==========================================
206
+ # upper top left ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``
207
+ # lower bottom left ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``
208
+ # ====== =============== ==========================================
209
+ #
210
+ # The default value of *origin* is set by :rc:`image.origin` which defaults
211
+ # to ``'upper'`` to match the matrix indexing conventions in math and
212
+ # computer graphics image indexing conventions.
213
+ #
214
+ #
215
+ # Explicit extent
216
+ # ---------------
217
+ #
218
+ # By setting *extent* we define the coordinates of the image area. The
219
+ # underlying image data is interpolated/resampled to fill that area.
220
+ #
221
+ # If the axes is set to autoscale, then the view limits of the axes are set
222
+ # to match the *extent* which ensures that the coordinate set by
223
+ # ``(left, bottom)`` is at the bottom left of the axes! However, this
224
+ # may invert the axis so they do not increase in the 'natural' direction.
225
+ #
226
+
227
+ extents = [(-0.5, 6.5, -0.5, 5.5),
228
+ (-0.5, 6.5, 5.5, -0.5),
229
+ (6.5, -0.5, -0.5, 5.5),
230
+ (6.5, -0.5, 5.5, -0.5)]
231
+
232
+ columns = generate_imshow_demo_grid(extents)
233
+ set_extent_None_text(columns['upper'][1])
234
+ set_extent_None_text(columns['lower'][0])
235
+
236
+
237
+ # %%
238
+ #
239
+ # Explicit extent and axes limits
240
+ # -------------------------------
241
+ #
242
+ # If we fix the axes limits by explicitly setting `~.axes.Axes.set_xlim` /
243
+ # `~.axes.Axes.set_ylim`, we force a certain size and orientation of the axes.
244
+ # This can decouple the 'left-right' and 'top-bottom' sense of the image from
245
+ # the orientation on the screen.
246
+ #
247
+ # In the example below we have chosen the limits slightly larger than the
248
+ # extent (note the white areas within the Axes).
249
+ #
250
+ # While we keep the extents as in the examples before, the coordinate (0, 0)
251
+ # is now explicitly put at the bottom left and values increase to up and to
252
+ # the right (from the viewer's point of view).
253
+ # We can see that:
254
+ #
255
+ # - The coordinate ``(left, bottom)`` anchors the image which then fills the
256
+ # box going towards the ``(right, top)`` point in data space.
257
+ # - The first column is always closest to the 'left'.
258
+ # - *origin* controls if the first row is closest to 'top' or 'bottom'.
259
+ # - The image may be inverted along either direction.
260
+ # - The 'left-right' and 'top-bottom' sense of the image may be uncoupled from
261
+ # the orientation on the screen.
262
+
263
+ generate_imshow_demo_grid(extents=[None] + extents,
264
+ xlim=(-2, 8), ylim=(-1, 6))
265
+
266
+ plt.show()
testbed/matplotlib__matplotlib/galleries/users_explain/artists/index.rst ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ +++++++
2
+ Artists
3
+ +++++++
4
+
5
+ Almost all objects you interact with on a Matplotlib plot are called "Artist"
6
+ (and are subclasses of the `.Artist` class). :doc:`Figure <../figure/index>`
7
+ and :doc:`Axes <../axes/index>` are Artists, and generally contain
8
+ `~.axis.Axis` Artists and Artists that contain data or annotation information.
9
+
10
+ .. toctree::
11
+ :maxdepth: 2
12
+
13
+ artist_intro
14
+
15
+ .. toctree::
16
+ :maxdepth: 1
17
+
18
+ Automated color cycle <color_cycle>
19
+ Optimizing Artists for performance <performance>
20
+ Paths <paths>
21
+ Path effects guide <patheffects_guide>
22
+ Understanding the extent keyword argument of imshow <imshow_extent>
23
+ transforms_tutorial
testbed/matplotlib__matplotlib/galleries/users_explain/artists/paths.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/advanced/path_tutorial
3
+
4
+ .. _paths:
5
+
6
+ =============
7
+ Path Tutorial
8
+ =============
9
+
10
+ Defining paths in your Matplotlib visualization.
11
+
12
+ The object underlying all of the :mod:`matplotlib.patches` objects is
13
+ the :class:`~matplotlib.path.Path`, which supports the standard set of
14
+ moveto, lineto, curveto commands to draw simple and compound outlines
15
+ consisting of line segments and splines. The ``Path`` is instantiated
16
+ with a (N, 2) array of (x, y) vertices, and an N-length array of path
17
+ codes. For example to draw the unit rectangle from (0, 0) to (1, 1), we
18
+ could use this code:
19
+ """
20
+
21
+ import matplotlib.pyplot as plt
22
+
23
+ import matplotlib.patches as patches
24
+ from matplotlib.path import Path
25
+
26
+ verts = [
27
+ (0., 0.), # left, bottom
28
+ (0., 1.), # left, top
29
+ (1., 1.), # right, top
30
+ (1., 0.), # right, bottom
31
+ (0., 0.), # ignored
32
+ ]
33
+
34
+ codes = [
35
+ Path.MOVETO,
36
+ Path.LINETO,
37
+ Path.LINETO,
38
+ Path.LINETO,
39
+ Path.CLOSEPOLY,
40
+ ]
41
+
42
+ path = Path(verts, codes)
43
+
44
+ fig, ax = plt.subplots()
45
+ patch = patches.PathPatch(path, facecolor='orange', lw=2)
46
+ ax.add_patch(patch)
47
+ ax.set_xlim(-2, 2)
48
+ ax.set_ylim(-2, 2)
49
+ plt.show()
50
+
51
+
52
+ # %%
53
+ # The following path codes are recognized
54
+ #
55
+ # ============= ======================== ======================================
56
+ # Code Vertices Description
57
+ # ============= ======================== ======================================
58
+ # ``STOP`` 1 (ignored) A marker for the end of the entire
59
+ # path (currently not required and
60
+ # ignored).
61
+ # ``MOVETO`` 1 Pick up the pen and move to the given
62
+ # vertex.
63
+ # ``LINETO`` 1 Draw a line from the current position
64
+ # to the given vertex.
65
+ # ``CURVE3`` 2: Draw a quadratic Bézier curve from the
66
+ # 1 control point, current position, with the given
67
+ # 1 end point control point, to the given end point.
68
+ # ``CURVE4`` 3: Draw a cubic Bézier curve from the
69
+ # 2 control points, current position, with the given
70
+ # 1 end point control points, to the given end
71
+ # point.
72
+ # ``CLOSEPOLY`` 1 (the point is ignored) Draw a line segment to the start point
73
+ # of the current polyline.
74
+ # ============= ======================== ======================================
75
+ #
76
+ #
77
+ # .. path-curves:
78
+ #
79
+ #
80
+ # Bézier example
81
+ # ==============
82
+ #
83
+ # Some of the path components require multiple vertices to specify them:
84
+ # for example CURVE 3 is a `Bézier
85
+ # <https://en.wikipedia.org/wiki/B%C3%A9zier_curve>`_ curve with one
86
+ # control point and one end point, and CURVE4 has three vertices for the
87
+ # two control points and the end point. The example below shows a
88
+ # CURVE4 Bézier spline -- the Bézier curve will be contained in the
89
+ # convex hull of the start point, the two control points, and the end
90
+ # point
91
+
92
+ verts = [
93
+ (0., 0.), # P0
94
+ (0.2, 1.), # P1
95
+ (1., 0.8), # P2
96
+ (0.8, 0.), # P3
97
+ ]
98
+
99
+ codes = [
100
+ Path.MOVETO,
101
+ Path.CURVE4,
102
+ Path.CURVE4,
103
+ Path.CURVE4,
104
+ ]
105
+
106
+ path = Path(verts, codes)
107
+
108
+ fig, ax = plt.subplots()
109
+ patch = patches.PathPatch(path, facecolor='none', lw=2)
110
+ ax.add_patch(patch)
111
+
112
+ xs, ys = zip(*verts)
113
+ ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10)
114
+
115
+ ax.text(-0.05, -0.05, 'P0')
116
+ ax.text(0.15, 1.05, 'P1')
117
+ ax.text(1.05, 0.85, 'P2')
118
+ ax.text(0.85, -0.05, 'P3')
119
+
120
+ ax.set_xlim(-0.1, 1.1)
121
+ ax.set_ylim(-0.1, 1.1)
122
+ plt.show()
123
+
124
+ # %%
125
+ # .. compound_paths:
126
+ #
127
+ # Compound paths
128
+ # ==============
129
+ #
130
+ # All of the simple patch primitives in matplotlib, Rectangle, Circle,
131
+ # Polygon, etc, are implemented with simple path. Plotting functions
132
+ # like :meth:`~matplotlib.axes.Axes.hist` and
133
+ # :meth:`~matplotlib.axes.Axes.bar`, which create a number of
134
+ # primitives, e.g., a bunch of Rectangles, can usually be implemented more
135
+ # efficiently using a compound path. The reason ``bar`` creates a list
136
+ # of rectangles and not a compound path is largely historical: the
137
+ # :class:`~matplotlib.path.Path` code is comparatively new and ``bar``
138
+ # predates it. While we could change it now, it would break old code,
139
+ # so here we will cover how to create compound paths, replacing the
140
+ # functionality in bar, in case you need to do so in your own code for
141
+ # efficiency reasons, e.g., you are creating an animated bar plot.
142
+ #
143
+ # We will make the histogram chart by creating a series of rectangles
144
+ # for each histogram bar: the rectangle width is the bin width and the
145
+ # rectangle height is the number of datapoints in that bin. First we'll
146
+ # create some random normally distributed data and compute the
147
+ # histogram. Because NumPy returns the bin edges and not centers, the
148
+ # length of ``bins`` is one greater than the length of ``n`` in the
149
+ # example below::
150
+ #
151
+ # # histogram our data with numpy
152
+ # data = np.random.randn(1000)
153
+ # n, bins = np.histogram(data, 100)
154
+ #
155
+ # We'll now extract the corners of the rectangles. Each of the
156
+ # ``left``, ``bottom``, etc., arrays below is ``len(n)``, where ``n`` is
157
+ # the array of counts for each histogram bar::
158
+ #
159
+ # # get the corners of the rectangles for the histogram
160
+ # left = np.array(bins[:-1])
161
+ # right = np.array(bins[1:])
162
+ # bottom = np.zeros(len(left))
163
+ # top = bottom + n
164
+ #
165
+ # Now we have to construct our compound path, which will consist of a
166
+ # series of ``MOVETO``, ``LINETO`` and ``CLOSEPOLY`` for each rectangle.
167
+ # For each rectangle, we need five vertices: one for the ``MOVETO``,
168
+ # three for the ``LINETO``, and one for the ``CLOSEPOLY``. As indicated
169
+ # in the table above, the vertex for the closepoly is ignored, but we still
170
+ # need it to keep the codes aligned with the vertices::
171
+ #
172
+ # nverts = nrects*(1+3+1)
173
+ # verts = np.zeros((nverts, 2))
174
+ # codes = np.ones(nverts, int) * path.Path.LINETO
175
+ # codes[0::5] = path.Path.MOVETO
176
+ # codes[4::5] = path.Path.CLOSEPOLY
177
+ # verts[0::5, 0] = left
178
+ # verts[0::5, 1] = bottom
179
+ # verts[1::5, 0] = left
180
+ # verts[1::5, 1] = top
181
+ # verts[2::5, 0] = right
182
+ # verts[2::5, 1] = top
183
+ # verts[3::5, 0] = right
184
+ # verts[3::5, 1] = bottom
185
+ #
186
+ # All that remains is to create the path, attach it to a
187
+ # :class:`~matplotlib.patches.PathPatch`, and add it to our axes::
188
+ #
189
+ # barpath = path.Path(verts, codes)
190
+ # patch = patches.PathPatch(barpath, facecolor='green',
191
+ # edgecolor='yellow', alpha=0.5)
192
+ # ax.add_patch(patch)
193
+
194
+ import numpy as np
195
+
196
+ import matplotlib.patches as patches
197
+ import matplotlib.path as path
198
+
199
+ fig, ax = plt.subplots()
200
+ # Fixing random state for reproducibility
201
+ np.random.seed(19680801)
202
+
203
+ # histogram our data with numpy
204
+ data = np.random.randn(1000)
205
+ n, bins = np.histogram(data, 100)
206
+
207
+ # get the corners of the rectangles for the histogram
208
+ left = np.array(bins[:-1])
209
+ right = np.array(bins[1:])
210
+ bottom = np.zeros(len(left))
211
+ top = bottom + n
212
+ nrects = len(left)
213
+
214
+ nverts = nrects*(1+3+1)
215
+ verts = np.zeros((nverts, 2))
216
+ codes = np.ones(nverts, int) * path.Path.LINETO
217
+ codes[0::5] = path.Path.MOVETO
218
+ codes[4::5] = path.Path.CLOSEPOLY
219
+ verts[0::5, 0] = left
220
+ verts[0::5, 1] = bottom
221
+ verts[1::5, 0] = left
222
+ verts[1::5, 1] = top
223
+ verts[2::5, 0] = right
224
+ verts[2::5, 1] = top
225
+ verts[3::5, 0] = right
226
+ verts[3::5, 1] = bottom
227
+
228
+ barpath = path.Path(verts, codes)
229
+ patch = patches.PathPatch(barpath, facecolor='green',
230
+ edgecolor='yellow', alpha=0.5)
231
+ ax.add_patch(patch)
232
+
233
+ ax.set_xlim(left[0], right[-1])
234
+ ax.set_ylim(bottom.min(), top.max())
235
+
236
+ plt.show()
testbed/matplotlib__matplotlib/galleries/users_explain/artists/performance.rst ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. redirect-from:: /users/explain/performance
2
+
3
+ .. _performance:
4
+
5
+ Performance
6
+ ===========
7
+
8
+ Whether exploring data in interactive mode or programmatically
9
+ saving lots of plots, rendering performance can be a challenging
10
+ bottleneck in your pipeline. Matplotlib provides multiple
11
+ ways to greatly reduce rendering time at the cost of a slight
12
+ change (to a settable tolerance) in your plot's appearance.
13
+ The methods available to reduce rendering time depend on the
14
+ type of plot that is being created.
15
+
16
+ Line segment simplification
17
+ ---------------------------
18
+
19
+ For plots that have line segments (e.g. typical line plots, outlines
20
+ of polygons, etc.), rendering performance can be controlled by
21
+ :rc:`path.simplify` and :rc:`path.simplify_threshold`, which
22
+ can be defined e.g. in the :file:`matplotlibrc` file (see
23
+ :ref:`customizing` for more information about
24
+ the :file:`matplotlibrc` file). :rc:`path.simplify` is a Boolean
25
+ indicating whether or not line segments are simplified at all.
26
+ :rc:`path.simplify_threshold` controls how much line segments are simplified;
27
+ higher thresholds result in quicker rendering.
28
+
29
+ The following script will first display the data without any
30
+ simplification, and then display the same data with simplification.
31
+ Try interacting with both of them::
32
+
33
+ import numpy as np
34
+ import matplotlib.pyplot as plt
35
+ import matplotlib as mpl
36
+
37
+ # Setup, and create the data to plot
38
+ y = np.random.rand(100000)
39
+ y[50000:] *= 2
40
+ y[np.geomspace(10, 50000, 400).astype(int)] = -1
41
+ mpl.rcParams['path.simplify'] = True
42
+
43
+ mpl.rcParams['path.simplify_threshold'] = 0.0
44
+ plt.plot(y)
45
+ plt.show()
46
+
47
+ mpl.rcParams['path.simplify_threshold'] = 1.0
48
+ plt.plot(y)
49
+ plt.show()
50
+
51
+ Matplotlib currently defaults to a conservative simplification
52
+ threshold of ``1/9``. To change default settings to use a different
53
+ value, change the :file:`matplotlibrc` file. Alternatively, users
54
+ can create a new style for interactive plotting (with maximal
55
+ simplification) and another style for publication quality plotting
56
+ (with minimal simplification) and activate them as necessary. See
57
+ :ref:`customizing` for instructions on
58
+ how to perform these actions.
59
+
60
+ The simplification works by iteratively merging line segments
61
+ into a single vector until the next line segment's perpendicular
62
+ distance to the vector (measured in display-coordinate space)
63
+ is greater than the ``path.simplify_threshold`` parameter.
64
+
65
+ .. note::
66
+ Changes related to how line segments are simplified were made
67
+ in version 2.1. Rendering time will still be improved by these
68
+ parameters prior to 2.1, but rendering time for some kinds of
69
+ data will be vastly improved in versions 2.1 and greater.
70
+
71
+ Marker subsampling
72
+ ------------------
73
+
74
+ Markers can also be simplified, albeit less robustly than line
75
+ segments. Marker subsampling is only available to `.Line2D` objects
76
+ (through the ``markevery`` property). Wherever `.Line2D` construction
77
+ parameters are passed through, such as `.pyplot.plot` and `.Axes.plot`,
78
+ the ``markevery`` parameter can be used::
79
+
80
+ plt.plot(x, y, markevery=10)
81
+
82
+ The ``markevery`` argument allows for naive subsampling, or an
83
+ attempt at evenly spaced (along the *x* axis) sampling. See the
84
+ :doc:`/gallery/lines_bars_and_markers/markevery_demo`
85
+ for more information.
86
+
87
+ Splitting lines into smaller chunks
88
+ -----------------------------------
89
+
90
+ If you are using the Agg backend (see :ref:`what-is-a-backend`),
91
+ then you can make use of :rc:`agg.path.chunksize`
92
+ This allows users to specify a chunk size, and any lines with
93
+ greater than that many vertices will be split into multiple
94
+ lines, each of which has no more than ``agg.path.chunksize``
95
+ many vertices. (Unless ``agg.path.chunksize`` is zero, in
96
+ which case there is no chunking.) For some kind of data,
97
+ chunking the line up into reasonable sizes can greatly
98
+ decrease rendering time.
99
+
100
+ The following script will first display the data without any
101
+ chunk size restriction, and then display the same data with
102
+ a chunk size of 10,000. The difference can best be seen when
103
+ the figures are large, try maximizing the GUI and then
104
+ interacting with them::
105
+
106
+ import numpy as np
107
+ import matplotlib.pyplot as plt
108
+ import matplotlib as mpl
109
+ mpl.rcParams['path.simplify_threshold'] = 1.0
110
+
111
+ # Setup, and create the data to plot
112
+ y = np.random.rand(100000)
113
+ y[50000:] *= 2
114
+ y[np.geomspace(10, 50000, 400).astype(int)] = -1
115
+ mpl.rcParams['path.simplify'] = True
116
+
117
+ mpl.rcParams['agg.path.chunksize'] = 0
118
+ plt.plot(y)
119
+ plt.show()
120
+
121
+ mpl.rcParams['agg.path.chunksize'] = 10000
122
+ plt.plot(y)
123
+ plt.show()
124
+
125
+ Legends
126
+ -------
127
+
128
+ The default legend behavior for axes attempts to find the location
129
+ that covers the fewest data points (``loc='best'``). This can be a
130
+ very expensive computation if there are lots of data points. In
131
+ this case, you may want to provide a specific location.
132
+
133
+ Using the *fast* style
134
+ ----------------------
135
+
136
+ The *fast* style can be used to automatically set
137
+ simplification and chunking parameters to reasonable
138
+ settings to speed up plotting large amounts of data.
139
+ The following code runs it::
140
+
141
+ import matplotlib.style as mplstyle
142
+ mplstyle.use('fast')
143
+
144
+ It is very lightweight, so it works well with other
145
+ styles. Be sure the fast style is applied last
146
+ so that other styles do not overwrite the settings::
147
+
148
+ mplstyle.use(['dark_background', 'ggplot', 'fast'])
testbed/matplotlib__matplotlib/galleries/users_explain/artists/transforms_tutorial.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/advanced/transforms_tutorial
3
+
4
+ .. _transforms_tutorial:
5
+
6
+ ========================
7
+ Transformations Tutorial
8
+ ========================
9
+
10
+ Like any graphics packages, Matplotlib is built on top of a transformation
11
+ framework to easily move between coordinate systems, the userland *data*
12
+ coordinate system, the *axes* coordinate system, the *figure* coordinate
13
+ system, and the *display* coordinate system. In 95% of your plotting, you
14
+ won't need to think about this, as it happens under the hood, but as you push
15
+ the limits of custom figure generation, it helps to have an understanding of
16
+ these objects, so you can reuse the existing transformations Matplotlib makes
17
+ available to you, or create your own (see :mod:`matplotlib.transforms`). The
18
+ table below summarizes some useful coordinate systems, a description of each
19
+ system, and the transformation object for going from each coordinate system to
20
+ the *display* coordinates. In the "Transformation Object" column, ``ax`` is a
21
+ :class:`~matplotlib.axes.Axes` instance, ``fig`` is a
22
+ :class:`~matplotlib.figure.Figure` instance, and ``subfigure`` is a
23
+ :class:`~matplotlib.figure.SubFigure` instance.
24
+
25
+
26
+ +----------------+-----------------------------------+---------------------------------------------------+
27
+ |Coordinate |Description |Transformation object |
28
+ |system | |from system to display |
29
+ +================+===================================+===================================================+
30
+ |"data" |The coordinate system of the data |``ax.transData`` |
31
+ | |in the Axes. | |
32
+ +----------------+-----------------------------------+---------------------------------------------------+
33
+ |"axes" |The coordinate system of the |``ax.transAxes`` |
34
+ | |`~matplotlib.axes.Axes`; (0, 0) | |
35
+ | |is bottom left of the axes, and | |
36
+ | |(1, 1) is top right of the axes. | |
37
+ +----------------+-----------------------------------+---------------------------------------------------+
38
+ |"subfigure" |The coordinate system of the |``subfigure.transSubfigure`` |
39
+ | |`.SubFigure`; (0, 0) is bottom left| |
40
+ | |of the subfigure, and (1, 1) is top| |
41
+ | |right of the subfigure. If a | |
42
+ | |figure has no subfigures, this is | |
43
+ | |the same as ``transFigure``. | |
44
+ +----------------+-----------------------------------+---------------------------------------------------+
45
+ |"figure" |The coordinate system of the |``fig.transFigure`` |
46
+ | |`.Figure`; (0, 0) is bottom left | |
47
+ | |of the figure, and (1, 1) is top | |
48
+ | |right of the figure. | |
49
+ +----------------+-----------------------------------+---------------------------------------------------+
50
+ |"figure-inches" |The coordinate system of the |``fig.dpi_scale_trans`` |
51
+ | |`.Figure` in inches; (0, 0) is | |
52
+ | |bottom left of the figure, and | |
53
+ | |(width, height) is the top right | |
54
+ | |of the figure in inches. | |
55
+ +----------------+-----------------------------------+---------------------------------------------------+
56
+ |"xaxis", |Blended coordinate systems, using |``ax.get_xaxis_transform()``, |
57
+ |"yaxis" |data coordinates on one direction |``ax.get_yaxis_transform()`` |
58
+ | |and axes coordinates on the other. | |
59
+ +----------------+-----------------------------------+---------------------------------------------------+
60
+ |"display" |The native coordinate system of the|`None`, or |
61
+ | |output ; (0, 0) is the bottom left |:class:`~matplotlib.transforms.IdentityTransform()`|
62
+ | |of the window, and (width, height) | |
63
+ | |is top right of the output in | |
64
+ | |"display units". | |
65
+ | | | |
66
+ | |The exact interpretation of the | |
67
+ | |units depends on the back end. For | |
68
+ | |example it is pixels for Agg and | |
69
+ | |points for svg/pdf. | |
70
+ +----------------+-----------------------------------+---------------------------------------------------+
71
+
72
+
73
+
74
+
75
+
76
+ The `~matplotlib.transforms.Transform` objects are naive to the source and
77
+ destination coordinate systems, however the objects referred to in the table
78
+ above are constructed to take inputs in their coordinate system, and transform
79
+ the input to the *display* coordinate system. That is why the *display*
80
+ coordinate system has `None` for the "Transformation Object" column -- it
81
+ already is in *display* coordinates. The naming and destination conventions
82
+ are an aid to keeping track of the available "standard" coordinate systems and
83
+ transforms.
84
+
85
+ The transformations also know how to invert themselves (via
86
+ `.Transform.inverted`) to generate a transform from output coordinate system
87
+ back to the input coordinate system. For example, ``ax.transData`` converts
88
+ values in data coordinates to display coordinates and
89
+ ``ax.transData.inversed()`` is a :class:`matplotlib.transforms.Transform` that
90
+ goes from display coordinates to data coordinates. This is particularly useful
91
+ when processing events from the user interface, which typically occur in
92
+ display space, and you want to know where the mouse click or key-press occurred
93
+ in your *data* coordinate system.
94
+
95
+ Note that specifying the position of Artists in *display* coordinates may
96
+ change their relative location if the ``dpi`` or size of the figure changes.
97
+ This can cause confusion when printing or changing screen resolution, because
98
+ the object can change location and size. Therefore, it is most common for
99
+ artists placed in an Axes or figure to have their transform set to something
100
+ *other* than the `~.transforms.IdentityTransform()`; the default when an artist
101
+ is added to an Axes using `~.axes.Axes.add_artist` is for the transform to be
102
+ ``ax.transData`` so that you can work and think in *data* coordinates and let
103
+ Matplotlib take care of the transformation to *display*.
104
+
105
+ .. _data-coords:
106
+
107
+ Data coordinates
108
+ ================
109
+
110
+ Let's start with the most commonly used coordinate, the *data* coordinate
111
+ system. Whenever you add data to the axes, Matplotlib updates the datalimits,
112
+ most commonly updated with the :meth:`~matplotlib.axes.Axes.set_xlim` and
113
+ :meth:`~matplotlib.axes.Axes.set_ylim` methods. For example, in the figure
114
+ below, the data limits stretch from 0 to 10 on the x-axis, and -1 to 1 on the
115
+ y-axis.
116
+
117
+ """
118
+
119
+ import matplotlib.pyplot as plt
120
+ import numpy as np
121
+
122
+ import matplotlib.patches as mpatches
123
+
124
+ x = np.arange(0, 10, 0.005)
125
+ y = np.exp(-x/2.) * np.sin(2*np.pi*x)
126
+
127
+ fig, ax = plt.subplots()
128
+ ax.plot(x, y)
129
+ ax.set_xlim(0, 10)
130
+ ax.set_ylim(-1, 1)
131
+
132
+ plt.show()
133
+
134
+ # %%
135
+ # You can use the ``ax.transData`` instance to transform from your
136
+ # *data* to your *display* coordinate system, either a single point or a
137
+ # sequence of points as shown below:
138
+ #
139
+ # .. sourcecode:: ipython
140
+ #
141
+ # In [14]: type(ax.transData)
142
+ # Out[14]: <class 'matplotlib.transforms.CompositeGenericTransform'>
143
+ #
144
+ # In [15]: ax.transData.transform((5, 0))
145
+ # Out[15]: array([ 335.175, 247. ])
146
+ #
147
+ # In [16]: ax.transData.transform([(5, 0), (1, 2)])
148
+ # Out[16]:
149
+ # array([[ 335.175, 247. ],
150
+ # [ 132.435, 642.2 ]])
151
+ #
152
+ # You can use the :meth:`~matplotlib.transforms.Transform.inverted`
153
+ # method to create a transform which will take you from *display* to *data*
154
+ # coordinates:
155
+ #
156
+ # .. sourcecode:: ipython
157
+ #
158
+ # In [41]: inv = ax.transData.inverted()
159
+ #
160
+ # In [42]: type(inv)
161
+ # Out[42]: <class 'matplotlib.transforms.CompositeGenericTransform'>
162
+ #
163
+ # In [43]: inv.transform((335.175, 247.))
164
+ # Out[43]: array([ 5., 0.])
165
+ #
166
+ # If your are typing along with this tutorial, the exact values of the
167
+ # *display* coordinates may differ if you have a different window size or
168
+ # dpi setting. Likewise, in the figure below, the display labeled
169
+ # points are probably not the same as in the ipython session because the
170
+ # documentation figure size defaults are different.
171
+
172
+ x = np.arange(0, 10, 0.005)
173
+ y = np.exp(-x/2.) * np.sin(2*np.pi*x)
174
+
175
+ fig, ax = plt.subplots()
176
+ ax.plot(x, y)
177
+ ax.set_xlim(0, 10)
178
+ ax.set_ylim(-1, 1)
179
+
180
+ xdata, ydata = 5, 0
181
+ # This computing the transform now, if anything
182
+ # (figure size, dpi, axes placement, data limits, scales..)
183
+ # changes re-calling transform will get a different value.
184
+ xdisplay, ydisplay = ax.transData.transform((xdata, ydata))
185
+
186
+ bbox = dict(boxstyle="round", fc="0.8")
187
+ arrowprops = dict(
188
+ arrowstyle="->",
189
+ connectionstyle="angle,angleA=0,angleB=90,rad=10")
190
+
191
+ offset = 72
192
+ ax.annotate(f'data = ({xdata:.1f}, {ydata:.1f})',
193
+ (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
194
+ bbox=bbox, arrowprops=arrowprops)
195
+
196
+ disp = ax.annotate(f'display = ({xdisplay:.1f}, {ydisplay:.1f})',
197
+ (xdisplay, ydisplay), xytext=(0.5*offset, -offset),
198
+ xycoords='figure pixels',
199
+ textcoords='offset points',
200
+ bbox=bbox, arrowprops=arrowprops)
201
+
202
+ plt.show()
203
+
204
+ # %%
205
+ # .. warning::
206
+ #
207
+ # If you run the source code in the example above in a GUI backend,
208
+ # you may also find that the two arrows for the *data* and *display*
209
+ # annotations do not point to exactly the same point. This is because
210
+ # the display point was computed before the figure was displayed, and
211
+ # the GUI backend may slightly resize the figure when it is created.
212
+ # The effect is more pronounced if you resize the figure yourself.
213
+ # This is one good reason why you rarely want to work in *display*
214
+ # space, but you can connect to the ``'on_draw'``
215
+ # :class:`~matplotlib.backend_bases.Event` to update *figure*
216
+ # coordinates on figure draws; see :ref:`event-handling`.
217
+ #
218
+ # When you change the x or y limits of your axes, the data limits are
219
+ # updated so the transformation yields a new display point. Note that
220
+ # when we just change the ylim, only the y-display coordinate is
221
+ # altered, and when we change the xlim too, both are altered. More on
222
+ # this later when we talk about the
223
+ # :class:`~matplotlib.transforms.Bbox`.
224
+ #
225
+ # .. sourcecode:: ipython
226
+ #
227
+ # In [54]: ax.transData.transform((5, 0))
228
+ # Out[54]: array([ 335.175, 247. ])
229
+ #
230
+ # In [55]: ax.set_ylim(-1, 2)
231
+ # Out[55]: (-1, 2)
232
+ #
233
+ # In [56]: ax.transData.transform((5, 0))
234
+ # Out[56]: array([ 335.175 , 181.13333333])
235
+ #
236
+ # In [57]: ax.set_xlim(10, 20)
237
+ # Out[57]: (10, 20)
238
+ #
239
+ # In [58]: ax.transData.transform((5, 0))
240
+ # Out[58]: array([-171.675 , 181.13333333])
241
+ #
242
+ #
243
+ # .. _axes-coords:
244
+ #
245
+ # Axes coordinates
246
+ # ================
247
+ #
248
+ # After the *data* coordinate system, *axes* is probably the second most
249
+ # useful coordinate system. Here the point (0, 0) is the bottom left of
250
+ # your axes or subplot, (0.5, 0.5) is the center, and (1.0, 1.0) is the
251
+ # top right. You can also refer to points outside the range, so (-0.1,
252
+ # 1.1) is to the left and above your axes. This coordinate system is
253
+ # extremely useful when placing text in your axes, because you often
254
+ # want a text bubble in a fixed, location, e.g., the upper left of the axes
255
+ # pane, and have that location remain fixed when you pan or zoom. Here
256
+ # is a simple example that creates four panels and labels them 'A', 'B',
257
+ # 'C', 'D' as you often see in journals.
258
+
259
+ fig = plt.figure()
260
+ for i, label in enumerate(('A', 'B', 'C', 'D')):
261
+ ax = fig.add_subplot(2, 2, i+1)
262
+ ax.text(0.05, 0.95, label, transform=ax.transAxes,
263
+ fontsize=16, fontweight='bold', va='top')
264
+
265
+ plt.show()
266
+
267
+ # %%
268
+ # You can also make lines or patches in the *axes* coordinate system, but
269
+ # this is less useful in my experience than using ``ax.transAxes`` for
270
+ # placing text. Nonetheless, here is a silly example which plots some
271
+ # random dots in data space, and overlays a semi-transparent
272
+ # :class:`~matplotlib.patches.Circle` centered in the middle of the axes
273
+ # with a radius one quarter of the axes -- if your axes does not
274
+ # preserve aspect ratio (see :meth:`~matplotlib.axes.Axes.set_aspect`),
275
+ # this will look like an ellipse. Use the pan/zoom tool to move around,
276
+ # or manually change the data xlim and ylim, and you will see the data
277
+ # move, but the circle will remain fixed because it is not in *data*
278
+ # coordinates and will always remain at the center of the axes.
279
+
280
+ fig, ax = plt.subplots()
281
+ x, y = 10*np.random.rand(2, 1000)
282
+ ax.plot(x, y, 'go', alpha=0.2) # plot some data in data coordinates
283
+
284
+ circ = mpatches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes,
285
+ facecolor='blue', alpha=0.75)
286
+ ax.add_patch(circ)
287
+ plt.show()
288
+
289
+ # %%
290
+ # .. _blended_transformations:
291
+ #
292
+ # Blended transformations
293
+ # =======================
294
+ #
295
+ # Drawing in *blended* coordinate spaces which mix *axes* with *data*
296
+ # coordinates is extremely useful, for example to create a horizontal
297
+ # span which highlights some region of the y-data but spans across the
298
+ # x-axis regardless of the data limits, pan or zoom level, etc. In fact
299
+ # these blended lines and spans are so useful, we have built-in
300
+ # functions to make them easy to plot (see
301
+ # :meth:`~matplotlib.axes.Axes.axhline`,
302
+ # :meth:`~matplotlib.axes.Axes.axvline`,
303
+ # :meth:`~matplotlib.axes.Axes.axhspan`,
304
+ # :meth:`~matplotlib.axes.Axes.axvspan`) but for didactic purposes we
305
+ # will implement the horizontal span here using a blended
306
+ # transformation. This trick only works for separable transformations,
307
+ # like you see in normal Cartesian coordinate systems, but not on
308
+ # inseparable transformations like the
309
+ # :class:`~matplotlib.projections.polar.PolarAxes.PolarTransform`.
310
+
311
+ import matplotlib.transforms as transforms
312
+
313
+ fig, ax = plt.subplots()
314
+ x = np.random.randn(1000)
315
+
316
+ ax.hist(x, 30)
317
+ ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16)
318
+
319
+ # the x coords of this transformation are data, and the y coord are axes
320
+ trans = transforms.blended_transform_factory(
321
+ ax.transData, ax.transAxes)
322
+ # highlight the 1..2 stddev region with a span.
323
+ # We want x to be in data coordinates and y to span from 0..1 in axes coords.
324
+ rect = mpatches.Rectangle((1, 0), width=1, height=1, transform=trans,
325
+ color='yellow', alpha=0.5)
326
+ ax.add_patch(rect)
327
+
328
+ plt.show()
329
+
330
+ # %%
331
+ # .. note::
332
+ #
333
+ # The blended transformations where x is in *data* coords and y in *axes*
334
+ # coordinates is so useful that we have helper methods to return the
335
+ # versions Matplotlib uses internally for drawing ticks, ticklabels, etc.
336
+ # The methods are :meth:`matplotlib.axes.Axes.get_xaxis_transform` and
337
+ # :meth:`matplotlib.axes.Axes.get_yaxis_transform`. So in the example
338
+ # above, the call to
339
+ # :meth:`~matplotlib.transforms.blended_transform_factory` can be
340
+ # replaced by ``get_xaxis_transform``::
341
+ #
342
+ # trans = ax.get_xaxis_transform()
343
+ #
344
+ # .. _transforms-fig-scale-dpi:
345
+ #
346
+ # Plotting in physical coordinates
347
+ # ================================
348
+ #
349
+ # Sometimes we want an object to be a certain physical size on the plot.
350
+ # Here we draw the same circle as above, but in physical coordinates. If done
351
+ # interactively, you can see that changing the size of the figure does
352
+ # not change the offset of the circle from the lower-left corner,
353
+ # does not change its size, and the circle remains a circle regardless of
354
+ # the aspect ratio of the axes.
355
+
356
+ fig, ax = plt.subplots(figsize=(5, 4))
357
+ x, y = 10*np.random.rand(2, 1000)
358
+ ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates
359
+ # add a circle in fixed-coordinates
360
+ circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans,
361
+ facecolor='blue', alpha=0.75)
362
+ ax.add_patch(circ)
363
+ plt.show()
364
+
365
+ # %%
366
+ # If we change the figure size, the circle does not change its absolute
367
+ # position and is cropped.
368
+
369
+ fig, ax = plt.subplots(figsize=(7, 2))
370
+ x, y = 10*np.random.rand(2, 1000)
371
+ ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates
372
+ # add a circle in fixed-coordinates
373
+ circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans,
374
+ facecolor='blue', alpha=0.75)
375
+ ax.add_patch(circ)
376
+ plt.show()
377
+
378
+ # %%
379
+ # Another use is putting a patch with a set physical dimension around a
380
+ # data point on the axes. Here we add together two transforms. The
381
+ # first sets the scaling of how large the ellipse should be and the second
382
+ # sets its position. The ellipse is then placed at the origin, and then
383
+ # we use the helper transform :class:`~matplotlib.transforms.ScaledTranslation`
384
+ # to move it
385
+ # to the right place in the ``ax.transData`` coordinate system.
386
+ # This helper is instantiated with::
387
+ #
388
+ # trans = ScaledTranslation(xt, yt, scale_trans)
389
+ #
390
+ # where *xt* and *yt* are the translation offsets, and *scale_trans* is
391
+ # a transformation which scales *xt* and *yt* at transformation time
392
+ # before applying the offsets.
393
+ #
394
+ # Note the use of the plus operator on the transforms below.
395
+ # This code says: first apply the scale transformation ``fig.dpi_scale_trans``
396
+ # to make the ellipse the proper size, but still centered at (0, 0),
397
+ # and then translate the data to ``xdata[0]`` and ``ydata[0]`` in data space.
398
+ #
399
+ # In interactive use, the ellipse stays the same size even if the
400
+ # axes limits are changed via zoom.
401
+ #
402
+
403
+ fig, ax = plt.subplots()
404
+ xdata, ydata = (0.2, 0.7), (0.5, 0.5)
405
+ ax.plot(xdata, ydata, "o")
406
+ ax.set_xlim((0, 1))
407
+
408
+ trans = (fig.dpi_scale_trans +
409
+ transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData))
410
+
411
+ # plot an ellipse around the point that is 150 x 130 points in diameter...
412
+ circle = mpatches.Ellipse((0, 0), 150/72, 130/72, angle=40,
413
+ fill=None, transform=trans)
414
+ ax.add_patch(circle)
415
+ plt.show()
416
+
417
+ # %%
418
+ # .. note::
419
+ #
420
+ # The order of transformation matters. Here the ellipse
421
+ # is given the right dimensions in display space *first* and then moved
422
+ # in data space to the correct spot.
423
+ # If we had done the ``ScaledTranslation`` first, then
424
+ # ``xdata[0]`` and ``ydata[0]`` would
425
+ # first be transformed to *display* coordinates (``[ 358.4 475.2]`` on
426
+ # a 200-dpi monitor) and then those coordinates
427
+ # would be scaled by ``fig.dpi_scale_trans`` pushing the center of
428
+ # the ellipse well off the screen (i.e. ``[ 71680. 95040.]``).
429
+ #
430
+ # .. _offset-transforms-shadow:
431
+ #
432
+ # Using offset transforms to create a shadow effect
433
+ # =================================================
434
+ #
435
+ # Another use of :class:`~matplotlib.transforms.ScaledTranslation` is to create
436
+ # a new transformation that is
437
+ # offset from another transformation, e.g., to place one object shifted a
438
+ # bit relative to another object. Typically, you want the shift to be in
439
+ # some physical dimension, like points or inches rather than in *data*
440
+ # coordinates, so that the shift effect is constant at different zoom
441
+ # levels and dpi settings.
442
+ #
443
+ # One use for an offset is to create a shadow effect, where you draw one
444
+ # object identical to the first just to the right of it, and just below
445
+ # it, adjusting the zorder to make sure the shadow is drawn first and
446
+ # then the object it is shadowing above it.
447
+ #
448
+ # Here we apply the transforms in the *opposite* order to the use of
449
+ # :class:`~matplotlib.transforms.ScaledTranslation` above. The plot is
450
+ # first made in data coordinates (``ax.transData``) and then shifted by
451
+ # ``dx`` and ``dy`` points using ``fig.dpi_scale_trans``. (In typography,
452
+ # a `point <https://en.wikipedia.org/wiki/Point_%28typography%29>`_ is
453
+ # 1/72 inches, and by specifying your offsets in points, your figure
454
+ # will look the same regardless of the dpi resolution it is saved in.)
455
+
456
+ fig, ax = plt.subplots()
457
+
458
+ # make a simple sine wave
459
+ x = np.arange(0., 2., 0.01)
460
+ y = np.sin(2*np.pi*x)
461
+ line, = ax.plot(x, y, lw=3, color='blue')
462
+
463
+ # shift the object over 2 points, and down 2 points
464
+ dx, dy = 2/72., -2/72.
465
+ offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
466
+ shadow_transform = ax.transData + offset
467
+
468
+ # now plot the same data with our offset transform;
469
+ # use the zorder to make sure we are below the line
470
+ ax.plot(x, y, lw=3, color='gray',
471
+ transform=shadow_transform,
472
+ zorder=0.5*line.get_zorder())
473
+
474
+ ax.set_title('creating a shadow effect with an offset transform')
475
+ plt.show()
476
+
477
+
478
+ # %%
479
+ # .. note::
480
+ #
481
+ # The dpi and inches offset is a
482
+ # common-enough use case that we have a special helper function to
483
+ # create it in :func:`matplotlib.transforms.offset_copy`, which returns
484
+ # a new transform with an added offset. So above we could have done::
485
+ #
486
+ # shadow_transform = transforms.offset_copy(ax.transData,
487
+ # fig, dx, dy, units='inches')
488
+ #
489
+ #
490
+ # .. _transformation-pipeline:
491
+ #
492
+ # The transformation pipeline
493
+ # ===========================
494
+ #
495
+ # The ``ax.transData`` transform we have been working with in this
496
+ # tutorial is a composite of three different transformations that
497
+ # comprise the transformation pipeline from *data* -> *display*
498
+ # coordinates. Michael Droettboom implemented the transformations
499
+ # framework, taking care to provide a clean API that segregated the
500
+ # nonlinear projections and scales that happen in polar and logarithmic
501
+ # plots, from the linear affine transformations that happen when you pan
502
+ # and zoom. There is an efficiency here, because you can pan and zoom
503
+ # in your axes which affects the affine transformation, but you may not
504
+ # need to compute the potentially expensive nonlinear scales or
505
+ # projections on simple navigation events. It is also possible to
506
+ # multiply affine transformation matrices together, and then apply them
507
+ # to coordinates in one step. This is not true of all possible
508
+ # transformations.
509
+ #
510
+ #
511
+ # Here is how the ``ax.transData`` instance is defined in the basic
512
+ # separable axis :class:`~matplotlib.axes.Axes` class::
513
+ #
514
+ # self.transData = self.transScale + (self.transLimits + self.transAxes)
515
+ #
516
+ # We've been introduced to the ``transAxes`` instance above in
517
+ # :ref:`axes-coords`, which maps the (0, 0), (1, 1) corners of the
518
+ # axes or subplot bounding box to *display* space, so let's look at
519
+ # these other two pieces.
520
+ #
521
+ # ``self.transLimits`` is the transformation that takes you from
522
+ # *data* to *axes* coordinates; i.e., it maps your view xlim and ylim
523
+ # to the unit space of the axes (and ``transAxes`` then takes that unit
524
+ # space to display space). We can see this in action here
525
+ #
526
+ # .. sourcecode:: ipython
527
+ #
528
+ # In [80]: ax = plt.subplot()
529
+ #
530
+ # In [81]: ax.set_xlim(0, 10)
531
+ # Out[81]: (0, 10)
532
+ #
533
+ # In [82]: ax.set_ylim(-1, 1)
534
+ # Out[82]: (-1, 1)
535
+ #
536
+ # In [84]: ax.transLimits.transform((0, -1))
537
+ # Out[84]: array([ 0., 0.])
538
+ #
539
+ # In [85]: ax.transLimits.transform((10, -1))
540
+ # Out[85]: array([ 1., 0.])
541
+ #
542
+ # In [86]: ax.transLimits.transform((10, 1))
543
+ # Out[86]: array([ 1., 1.])
544
+ #
545
+ # In [87]: ax.transLimits.transform((5, 0))
546
+ # Out[87]: array([ 0.5, 0.5])
547
+ #
548
+ # and we can use this same inverted transformation to go from the unit
549
+ # *axes* coordinates back to *data* coordinates.
550
+ #
551
+ # .. sourcecode:: ipython
552
+ #
553
+ # In [90]: inv.transform((0.25, 0.25))
554
+ # Out[90]: array([ 2.5, -0.5])
555
+ #
556
+ # The final piece is the ``self.transScale`` attribute, which is
557
+ # responsible for the optional non-linear scaling of the data, e.g., for
558
+ # logarithmic axes. When an Axes is initially setup, this is just set to
559
+ # the identity transform, since the basic Matplotlib axes has linear
560
+ # scale, but when you call a logarithmic scaling function like
561
+ # :meth:`~matplotlib.axes.Axes.semilogx` or explicitly set the scale to
562
+ # logarithmic with :meth:`~matplotlib.axes.Axes.set_xscale`, then the
563
+ # ``ax.transScale`` attribute is set to handle the nonlinear projection.
564
+ # The scales transforms are properties of the respective ``xaxis`` and
565
+ # ``yaxis`` :class:`~matplotlib.axis.Axis` instances. For example, when
566
+ # you call ``ax.set_xscale('log')``, the xaxis updates its scale to a
567
+ # :class:`matplotlib.scale.LogScale` instance.
568
+ #
569
+ # For non-separable axes the PolarAxes, there is one more piece to
570
+ # consider, the projection transformation. The ``transData``
571
+ # :class:`matplotlib.projections.polar.PolarAxes` is similar to that for
572
+ # the typical separable matplotlib Axes, with one additional piece
573
+ # ``transProjection``::
574
+ #
575
+ # self.transData = (
576
+ # self.transScale + self.transShift + self.transProjection +
577
+ # (self.transProjectionAffine + self.transWedge + self.transAxes))
578
+ #
579
+ # ``transProjection`` handles the projection from the space,
580
+ # e.g., latitude and longitude for map data, or radius and theta for polar
581
+ # data, to a separable Cartesian coordinate system. There are several
582
+ # projection examples in the :mod:`matplotlib.projections` package, and the
583
+ # best way to learn more is to open the source for those packages and
584
+ # see how to make your own, since Matplotlib supports extensible axes
585
+ # and projections. Michael Droettboom has provided a nice tutorial
586
+ # example of creating a Hammer projection axes; see
587
+ # :doc:`/gallery/misc/custom_projection`.
testbed/matplotlib__matplotlib/galleries/users_explain/axes/autoscale.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. redirect-from:: /tutorials/intermediate/autoscale
3
+
4
+ .. _autoscale:
5
+
6
+ Autoscaling
7
+ ===========
8
+
9
+ The limits on an axis can be set manually (e.g. ``ax.set_xlim(xmin, xmax)``)
10
+ or Matplotlib can set them automatically based on the data already on the axes.
11
+ There are a number of options to this autoscaling behaviour, discussed below.
12
+ """
13
+
14
+ # %%
15
+ # We will start with a simple line plot showing that autoscaling
16
+ # extends the axis limits 5% beyond the data limits (-2π, 2π).
17
+
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+
21
+ import matplotlib as mpl
22
+
23
+ x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
24
+ y = np.sinc(x)
25
+
26
+ fig, ax = plt.subplots()
27
+ ax.plot(x, y)
28
+
29
+ # %%
30
+ # Margins
31
+ # -------
32
+ # The default margin around the data limits is 5%, which is based on the
33
+ # default configuration setting of :rc:`axes.xmargin`, :rc:`axes.ymargin`,
34
+ # and :rc:`axes.zmargin`:
35
+
36
+ print(ax.margins())
37
+
38
+ # %%
39
+ # The margin size can be overridden to make them smaller or larger using
40
+ # `~matplotlib.axes.Axes.margins`:
41
+
42
+ fig, ax = plt.subplots()
43
+ ax.plot(x, y)
44
+ ax.margins(0.2, 0.2)
45
+
46
+ # %%
47
+ # In general, margins can be in the range (-0.5, ∞), where negative margins set
48
+ # the axes limits to a subrange of the data range, i.e. they clip data.
49
+ # Using a single number for margins affects both axes, a single margin can be
50
+ # customized using keyword arguments ``x`` or ``y``, but positional and keyword
51
+ # interface cannot be combined.
52
+
53
+ fig, ax = plt.subplots()
54
+ ax.plot(x, y)
55
+ ax.margins(y=-0.2)
56
+
57
+ # %%
58
+ # Sticky edges
59
+ # ------------
60
+ # There are plot elements (`.Artist`\s) that are usually used without margins.
61
+ # For example false-color images (e.g. created with `.Axes.imshow`) are not
62
+ # considered in the margins calculation.
63
+ #
64
+
65
+ xx, yy = np.meshgrid(x, x)
66
+ zz = np.sinc(np.sqrt((xx - 1)**2 + (yy - 1)**2))
67
+
68
+ fig, ax = plt.subplots(ncols=2, figsize=(12, 8))
69
+ ax[0].imshow(zz)
70
+ ax[0].set_title("default margins")
71
+ ax[1].imshow(zz)
72
+ ax[1].margins(0.2)
73
+ ax[1].set_title("margins(0.2)")
74
+
75
+ # %%
76
+ # This override of margins is determined by "sticky edges", a
77
+ # property of `.Artist` class that can suppress adding margins to axis
78
+ # limits. The effect of sticky edges can be disabled on an Axes by changing
79
+ # `~matplotlib.axes.Axes.use_sticky_edges`.
80
+ # Artists have a property `.Artist.sticky_edges`, and the values of
81
+ # sticky edges can be changed by writing to ``Artist.sticky_edges.x`` or
82
+ # ``Artist.sticky_edges.y``.
83
+ #
84
+ # The following example shows how overriding works and when it is needed.
85
+
86
+ fig, ax = plt.subplots(ncols=3, figsize=(16, 10))
87
+ ax[0].imshow(zz)
88
+ ax[0].margins(0.2)
89
+ ax[0].set_title("default use_sticky_edges\nmargins(0.2)")
90
+ ax[1].imshow(zz)
91
+ ax[1].margins(0.2)
92
+ ax[1].use_sticky_edges = False
93
+ ax[1].set_title("use_sticky_edges=False\nmargins(0.2)")
94
+ ax[2].imshow(zz)
95
+ ax[2].margins(-0.2)
96
+ ax[2].set_title("default use_sticky_edges\nmargins(-0.2)")
97
+
98
+ # %%
99
+ # We can see that setting ``use_sticky_edges`` to *False* renders the image
100
+ # with requested margins.
101
+ #
102
+ # While sticky edges don't increase the axis limits through extra margins,
103
+ # negative margins are still taken into account. This can be seen in
104
+ # the reduced limits of the third image.
105
+ #
106
+ # Controlling autoscale
107
+ # ---------------------
108
+ #
109
+ # By default, the limits are
110
+ # recalculated every time you add a new curve to the plot:
111
+
112
+ fig, ax = plt.subplots(ncols=2, figsize=(12, 8))
113
+ ax[0].plot(x, y)
114
+ ax[0].set_title("Single curve")
115
+ ax[1].plot(x, y)
116
+ ax[1].plot(x * 2.0, y)
117
+ ax[1].set_title("Two curves")
118
+
119
+ # %%
120
+ # However, there are cases when you don't want to automatically adjust the
121
+ # viewport to new data.
122
+ #
123
+ # One way to disable autoscaling is to manually set the
124
+ # axis limit. Let's say that we want to see only a part of the data in
125
+ # greater detail. Setting the ``xlim`` persists even if we add more curves to
126
+ # the data. To recalculate the new limits calling `.Axes.autoscale` will
127
+ # toggle the functionality manually.
128
+
129
+ fig, ax = plt.subplots(ncols=2, figsize=(12, 8))
130
+ ax[0].plot(x, y)
131
+ ax[0].set_xlim(left=-1, right=1)
132
+ ax[0].plot(x + np.pi * 0.5, y)
133
+ ax[0].set_title("set_xlim(left=-1, right=1)\n")
134
+ ax[1].plot(x, y)
135
+ ax[1].set_xlim(left=-1, right=1)
136
+ ax[1].plot(x + np.pi * 0.5, y)
137
+ ax[1].autoscale()
138
+ ax[1].set_title("set_xlim(left=-1, right=1)\nautoscale()")
139
+
140
+ # %%
141
+ # We can check that the first plot has autoscale disabled and that the second
142
+ # plot has it enabled again by using `.Axes.get_autoscale_on()`:
143
+
144
+ print(ax[0].get_autoscale_on()) # False means disabled
145
+ print(ax[1].get_autoscale_on()) # True means enabled -> recalculated
146
+
147
+ # %%
148
+ # Arguments of the autoscale function give us precise control over the process
149
+ # of autoscaling. A combination of arguments ``enable``, and ``axis`` sets the
150
+ # autoscaling feature for the selected axis (or both). The argument ``tight``
151
+ # sets the margin of the selected axis to zero. To preserve settings of either
152
+ # ``enable`` or ``tight`` you can set the opposite one to *None*, that way
153
+ # it should not be modified. However, setting ``enable`` to *None* and tight
154
+ # to *True* affects both axes regardless of the ``axis`` argument.
155
+
156
+ fig, ax = plt.subplots()
157
+ ax.plot(x, y)
158
+ ax.margins(0.2, 0.2)
159
+ ax.autoscale(enable=None, axis="x", tight=True)
160
+
161
+ print(ax.margins())
162
+
163
+ # %%
164
+ # Working with collections
165
+ # ------------------------
166
+ #
167
+ # Autoscale works out of the box for all lines, patches, and images added to
168
+ # the axes. One of the artists that it won't work with is a `.Collection`.
169
+ # After adding a collection to the axes, one has to manually trigger the
170
+ # `~matplotlib.axes.Axes.autoscale_view()` to recalculate
171
+ # axes limits.
172
+
173
+ fig, ax = plt.subplots()
174
+ collection = mpl.collections.StarPolygonCollection(
175
+ 5, rotation=0, sizes=(250,), # five point star, zero angle, size 250px
176
+ offsets=np.column_stack([x, y]), # Set the positions
177
+ offset_transform=ax.transData, # Propagate transformations of the Axes
178
+ )
179
+ ax.add_collection(collection)
180
+ ax.autoscale_view()
testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_intro.rst ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##################################
2
+ Introduction to Axes (or Subplots)
3
+ ##################################
4
+
5
+
6
+ Matplotlib `~.axes.Axes` are the gateway to creating your data visualizations.
7
+ Once an Axes is placed on a figure there are many methods that can be used to
8
+ add data to the Axes. An Axes typically has a pair of `~.axis.Axis`
9
+ Artists that define the data coordinate system, and include methods to add
10
+ annotations like x- and y-labels, titles, and legends.
11
+
12
+ .. _anatomy_local:
13
+
14
+ .. figure:: /_static/anatomy.png
15
+ :width: 80%
16
+
17
+ Anatomy of a Figure
18
+
19
+ In the picture above, the Axes object was created with ``ax = fig.subplots()``.
20
+ Everything else on the figure was created with methods on this ``ax`` object,
21
+ or can be accessed from it. If we want to change the label on the x-axis, we
22
+ call ``ax.set_xlabel('New Label')``, if we want to plot some data we call
23
+ ``ax.plot(x, y)``. Indeed, in the figure above, the only Artist that is not
24
+ part of the Axes is the Figure itself, so the `.axes.Axes` class is really the
25
+ gateway to much of Matplotlib's functionality.
26
+
27
+ Note that Axes are so fundamental to the operation of Matplotlib that a lot of
28
+ material here is duplicate of that in :ref:`quick_start`.
29
+
30
+ Creating Axes
31
+ -------------
32
+
33
+ .. plot::
34
+ :include-source:
35
+
36
+ import matplotlib.pyplot as plt
37
+ import numpy as np
38
+
39
+ fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(3.5, 2.5),
40
+ layout="constrained")
41
+ # for each Axes, add an artist, in this case a nice label in the middle...
42
+ for row in range(2):
43
+ for col in range(2):
44
+ axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5),
45
+ transform=axs[row, col].transAxes,
46
+ ha='center', va='center', fontsize=18,
47
+ color='darkgrey')
48
+ fig.suptitle('plt.subplots()')
49
+
50
+
51
+ 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.
52
+
53
+ There are a number of other methods for adding Axes to a Figure:
54
+
55
+ * `.Figure.add_axes`: manually position an Axes. ``fig.add_axes([0, 0, 1,
56
+ 1])`` makes an Axes that fills the whole figure.
57
+ * `.pyplot.subplots` and `.Figure.subplots`: add a grid of Axes as in the example
58
+ above. The pyplot version returns both the Figure object and an array of
59
+ Axes. Note that ``fig, ax = plt.subplots()`` adds a single Axes to a Figure.
60
+ * `.pyplot.subplot_mosaic` and `.Figure.subplot_mosaic`: add a grid of named
61
+ Axes and return a dictionary of axes. For ``fig, axs =
62
+ plt.subplot_mosaic([['left', 'right'], ['bottom', 'bottom']])``,
63
+ ``axs['left']`` is an Axes in the top row on the left, and ``axs['bottom']``
64
+ is an Axes that spans both columns on the bottom.
65
+
66
+ See :doc:`arranging_axes` for more detail on how to arrange grids of Axes on a
67
+ Figure.
68
+
69
+
70
+ Axes plotting methods
71
+ ---------------------
72
+
73
+ Most of the high-level plotting methods are accessed from the `.axes.Axes`
74
+ class. See the API documentation for a full curated list, and
75
+ :ref:`plot_types` for examples. A basic example is `.axes.Axes.plot`:
76
+
77
+ .. plot::
78
+ :include-source:
79
+
80
+ fig, ax = plt.subplots(figsize=(4, 3))
81
+ np.random.seed(19680801)
82
+ t = np.arange(100)
83
+ x = np.cumsum(np.random.randn(100))
84
+ lines = ax.plot(t, x)
85
+
86
+ Note that ``plot`` returns a list of *lines* Artists which can subsequently be
87
+ manipulated, as discussed in :ref:`users_artists`.
88
+
89
+ A very incomplete list of plotting methods is below. Again, see :ref:`plot_types`
90
+ for more examples, and `.axes.Axes` for the full list of methods.
91
+
92
+ ========================= ==================================================
93
+ :ref:`basic_plots` `~.axes.Axes.plot`, `~.axes.Axes.scatter`,
94
+ `~.axes.Axes.bar`, `~.axes.Axes.step`,
95
+ :ref:`arrays` `~.axes.Axes.pcolormesh`, `~.axes.Axes.contour`,
96
+ `~.axes.Axes.quiver`, `~.axes.Axes.streamplot`,
97
+ `~.axes.Axes.imshow`
98
+ :ref:`stats_plots` `~.axes.Axes.hist`, `~.axes.Axes.errorbar`,
99
+ `~.axes.Axes.hist2d`, `~.axes.Axes.pie`,
100
+ `~.axes.Axes.boxplot`, `~.axes.Axes.violinplot`
101
+ :ref:`unstructured_plots` `~.axes.Axes.tricontour`, `~.axes.Axes.tripcolor`
102
+ ========================= ==================================================
103
+
104
+ Axes labelling and annotation
105
+ -----------------------------
106
+
107
+ 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.
108
+
109
+ .. plot::
110
+ :include-source:
111
+
112
+ fig, ax = plt.subplots(figsize=(5, 3), layout='constrained')
113
+ np.random.seed(19680801)
114
+ t = np.arange(200)
115
+ x = np.cumsum(np.random.randn(200))
116
+ y = np.cumsum(np.random.randn(200))
117
+ linesx = ax.plot(t, x, label='Random walk x')
118
+ linesy = ax.plot(t, y, label='Random walk y')
119
+
120
+ ax.set_xlabel('Time [s]')
121
+ ax.set_ylabel('Distance [km]')
122
+ ax.set_title('Random walk example')
123
+ ax.legend()
124
+
125
+ 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.
126
+
127
+ 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.
128
+
129
+
130
+ Axes limits, scales, and ticking
131
+ --------------------------------
132
+
133
+ 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`.
134
+
135
+ 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:
136
+
137
+ .. plot::
138
+ :include-source:
139
+
140
+ fig, ax = plt.subplots(figsize=(4, 2.5), layout='constrained')
141
+ np.random.seed(19680801)
142
+ t = np.arange(200)
143
+ x = 2**np.cumsum(np.random.randn(200))
144
+ linesx = ax.plot(t, x)
145
+ ax.set_yscale('log')
146
+ ax.set_xlim([20, 180])
147
+
148
+ 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`.
149
+
150
+ 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:
151
+
152
+ .. plot::
153
+ :include-source:
154
+
155
+ fig, ax = plt.subplots(figsize=(4, 2.5))
156
+ ax.plot(np.arange(10))
157
+ ax.tick_params(top=True, labeltop=True, color='red', axis='x',
158
+ labelcolor='green')
159
+
160
+
161
+ More fine-grained control on ticks, setting scales, and controlling the Axis can be highly customized beyond these Axes-level helpers.
162
+
163
+ Axes layout
164
+ -----------
165
+
166
+ Sometimes it is important to set the aspect ratio of a plot in data space, which we can do with `~.axes.Axes.set_aspect`:
167
+
168
+ .. plot::
169
+ :include-source:
170
+
171
+ fig, axs = plt.subplots(ncols=2, figsize=(7, 2.5), layout='constrained')
172
+ np.random.seed(19680801)
173
+ t = np.arange(200)
174
+ x = np.cumsum(np.random.randn(200))
175
+ axs[0].plot(t, x)
176
+ axs[0].set_title('aspect="auto"')
177
+
178
+ axs[1].plot(t, x)
179
+ axs[1].set_aspect(3)
180
+ axs[1].set_title('aspect=3')
testbed/matplotlib__matplotlib/galleries/users_explain/axes/axes_ticks.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. _user_axes_ticks:
3
+
4
+ ==========
5
+ Axis Ticks
6
+ ==========
7
+
8
+ The x and y Axis on each Axes have default tick "locators" and "formatters"
9
+ that depend on the scale being used (see :ref:`user_axes_scales`). It is
10
+ possible to customize the ticks and tick labels with either high-level methods
11
+ like `~.axes.Axes.set_xticks` or set the locators and formatters directly on
12
+ the axis.
13
+
14
+ Manual location and formats
15
+ ===========================
16
+
17
+ The simplest method to customize the tick locations and formats is to use
18
+ `~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks`. These can be used on
19
+ either the major or the minor ticks.
20
+ """
21
+ import numpy as np
22
+ import matplotlib.pyplot as plt
23
+
24
+ import matplotlib.ticker as ticker
25
+
26
+
27
+ fig, axs = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained')
28
+ x = np.arange(100)
29
+ for nn, ax in enumerate(axs):
30
+ ax.plot(x, x)
31
+ if nn == 1:
32
+ ax.set_title('Manual ticks')
33
+ ax.set_yticks(np.arange(0, 100.1, 100/3))
34
+ xticks = np.arange(0.50, 101, 20)
35
+ xlabels = [f'\\${x:1.2f}' for x in xticks]
36
+ ax.set_xticks(xticks, labels=xlabels)
37
+ else:
38
+ ax.set_title('Automatic ticks')
39
+
40
+ # %%
41
+ #
42
+ # Note that the length of the ``labels`` argument must have the same length as
43
+ # the array used to specify the ticks.
44
+ #
45
+ # By default `~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks` act on the
46
+ # major ticks of an Axis, however it is possible to add minor ticks:
47
+
48
+ fig, axs = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained')
49
+ x = np.arange(100)
50
+ for nn, ax in enumerate(axs):
51
+ ax.plot(x, x)
52
+ if nn == 1:
53
+ ax.set_title('Manual ticks')
54
+ ax.set_yticks(np.arange(0, 100.1, 100/3))
55
+ ax.set_yticks(np.arange(0, 100.1, 100/30), minor=True)
56
+ else:
57
+ ax.set_title('Automatic ticks')
58
+
59
+
60
+ # %%
61
+ #
62
+ # Locators and Formatters
63
+ # =======================
64
+ #
65
+ # Manually setting the ticks as above works well for specific final plots, but
66
+ # does not adapt as the user interacts with the axes. At a lower level,
67
+ # Matplotlib has ``Locators`` that are meant to automatically choose ticks
68
+ # depending on the current view limits of the axis, and ``Formatters`` that are
69
+ # meant to format the tick labels automatically.
70
+ #
71
+ # The full list of locators provided by Matplotlib are listed at
72
+ # :ref:`locators`, and the formatters at :ref:`formatters`.
73
+
74
+
75
+ # %%
76
+
77
+ def setup(ax, title):
78
+ """Set up common parameters for the Axes in the example."""
79
+ # only show the bottom spine
80
+ ax.yaxis.set_major_locator(ticker.NullLocator())
81
+ ax.spines[['left', 'right', 'top']].set_visible(False)
82
+
83
+ ax.xaxis.set_ticks_position('bottom')
84
+ ax.tick_params(which='major', width=1.00, length=5)
85
+ ax.tick_params(which='minor', width=0.75, length=2.5)
86
+ ax.set_xlim(0, 5)
87
+ ax.set_ylim(0, 1)
88
+ ax.text(0.0, 0.2, title, transform=ax.transAxes,
89
+ fontsize=14, fontname='Monospace', color='tab:blue')
90
+
91
+
92
+ fig, axs = plt.subplots(8, 1, layout='constrained')
93
+
94
+ # Null Locator
95
+ setup(axs[0], title="NullLocator()")
96
+ axs[0].xaxis.set_major_locator(ticker.NullLocator())
97
+ axs[0].xaxis.set_minor_locator(ticker.NullLocator())
98
+
99
+ # Multiple Locator
100
+ setup(axs[1], title="MultipleLocator(0.5)")
101
+ axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5))
102
+ axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
103
+
104
+ # Fixed Locator
105
+ setup(axs[2], title="FixedLocator([0, 1, 5])")
106
+ axs[2].xaxis.set_major_locator(ticker.FixedLocator([0, 1, 5]))
107
+ axs[2].xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4)))
108
+
109
+ # Linear Locator
110
+ setup(axs[3], title="LinearLocator(numticks=3)")
111
+ axs[3].xaxis.set_major_locator(ticker.LinearLocator(3))
112
+ axs[3].xaxis.set_minor_locator(ticker.LinearLocator(31))
113
+
114
+ # Index Locator
115
+ setup(axs[4], title="IndexLocator(base=0.5, offset=0.25)")
116
+ axs[4].plot(range(0, 5), [0]*5, color='white')
117
+ axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25))
118
+
119
+ # Auto Locator
120
+ setup(axs[5], title="AutoLocator()")
121
+ axs[5].xaxis.set_major_locator(ticker.AutoLocator())
122
+ axs[5].xaxis.set_minor_locator(ticker.AutoMinorLocator())
123
+
124
+ # MaxN Locator
125
+ setup(axs[6], title="MaxNLocator(n=4)")
126
+ axs[6].xaxis.set_major_locator(ticker.MaxNLocator(4))
127
+ axs[6].xaxis.set_minor_locator(ticker.MaxNLocator(40))
128
+
129
+ # Log Locator
130
+ setup(axs[7], title="LogLocator(base=10, numticks=15)")
131
+ axs[7].set_xlim(10**3, 10**10)
132
+ axs[7].set_xscale('log')
133
+ axs[7].xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15))
134
+ plt.show()
135
+
136
+ # %%
137
+ #
138
+ # Similarly, we can specify "Formatters" for the major and minor ticks on each
139
+ # axis.
140
+ #
141
+ # The tick format is configured via the function `~.Axis.set_major_formatter`
142
+ # or `~.Axis.set_minor_formatter`. It accepts:
143
+ #
144
+ # - a format string, which implicitly creates a `.StrMethodFormatter`.
145
+ # - a function, implicitly creates a `.FuncFormatter`.
146
+ # - an instance of a `.Formatter` subclass. The most common are
147
+ #
148
+ # - `.NullFormatter`: No labels on the ticks.
149
+ # - `.StrMethodFormatter`: Use string `str.format` method.
150
+ # - `.FormatStrFormatter`: Use %-style formatting.
151
+ # - `.FuncFormatter`: Define labels through a function.
152
+ # - `.FixedFormatter`: Set the label strings explicitly.
153
+ # - `.ScalarFormatter`: Default formatter for scalars: auto-pick the format string.
154
+ # - `.PercentFormatter`: Format labels as a percentage.
155
+ #
156
+ # See :ref:`formatters` for the complete list.
157
+
158
+
159
+ def setup(ax, title):
160
+ """Set up common parameters for the Axes in the example."""
161
+ # only show the bottom spine
162
+ ax.yaxis.set_major_locator(ticker.NullLocator())
163
+ ax.spines[['left', 'right', 'top']].set_visible(False)
164
+
165
+ # define tick positions
166
+ ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
167
+ ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
168
+
169
+ ax.xaxis.set_ticks_position('bottom')
170
+ ax.tick_params(which='major', width=1.00, length=5)
171
+ ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
172
+ ax.set_xlim(0, 5)
173
+ ax.set_ylim(0, 1)
174
+ ax.text(0.0, 0.2, title, transform=ax.transAxes,
175
+ fontsize=14, fontname='Monospace', color='tab:blue')
176
+
177
+
178
+ fig = plt.figure(figsize=(8, 8), layout='constrained')
179
+ fig0, fig1, fig2 = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5])
180
+
181
+ fig0.suptitle('String Formatting', fontsize=16, x=0, ha='left')
182
+ ax0 = fig0.subplots()
183
+
184
+ setup(ax0, title="'{x} km'")
185
+ ax0.xaxis.set_major_formatter('{x} km')
186
+
187
+ fig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left')
188
+ ax1 = fig1.subplots()
189
+
190
+ setup(ax1, title="def(x, pos): return str(x-5)")
191
+ ax1.xaxis.set_major_formatter(lambda x, pos: str(x-5))
192
+
193
+ fig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left')
194
+ axs2 = fig2.subplots(7, 1)
195
+
196
+ setup(axs2[0], title="NullFormatter()")
197
+ axs2[0].xaxis.set_major_formatter(ticker.NullFormatter())
198
+
199
+ setup(axs2[1], title="StrMethodFormatter('{x:.3f}')")
200
+ axs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
201
+
202
+ setup(axs2[2], title="FormatStrFormatter('#%d')")
203
+ axs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
204
+
205
+
206
+ def fmt_two_digits(x, pos):
207
+ return f'[{x:.2f}]'
208
+
209
+
210
+ setup(axs2[3], title='FuncFormatter("[{:.2f}]".format)')
211
+ axs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits))
212
+
213
+ setup(axs2[4], title="FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])")
214
+ # FixedFormatter should only be used together with FixedLocator.
215
+ # Otherwise, one cannot be sure where the labels will end up.
216
+ positions = [0, 1, 2, 3, 4, 5]
217
+ labels = ['A', 'B', 'C', 'D', 'E', 'F']
218
+ axs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions))
219
+ axs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels))
220
+
221
+ setup(axs2[5], title="ScalarFormatter()")
222
+ axs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
223
+
224
+ setup(axs2[6], title="PercentFormatter(xmax=5)")
225
+ axs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
226
+
227
+
228
+ # %%
229
+ #
230
+ # Styling ticks (tick parameters)
231
+ # ===============================
232
+ #
233
+ # The appearance of ticks can be controlled at a low level by finding the
234
+ # individual `~.axis.Tick` on the axis. However, usually it is simplest to
235
+ # use `~.axes.Axes.tick_params` to change all the objects at once.
236
+ #
237
+ # The ``tick_params`` method can change the properties of ticks:
238
+ #
239
+ # - length
240
+ # - direction (in or out of the frame)
241
+ # - colors
242
+ # - width and length
243
+ # - and whether the ticks are drawn at the bottom, top, left, or right of the
244
+ # Axes.
245
+ #
246
+ # It also can control the tick labels:
247
+ #
248
+ # - labelsize (fontsize)
249
+ # - labelcolor (color of the label)
250
+ # - labelrotation
251
+ # - labelbottom, labeltop, labelleft, labelright
252
+ #
253
+ # In addition there is a *pad* keyword argument that specifies how far the tick
254
+ # label is from the tick.
255
+ #
256
+ # Finally, the grid linestyles can be set:
257
+ #
258
+ # - grid_color
259
+ # - grid_alpha
260
+ # - grid_linewidth
261
+ # - grid_linestyle
262
+ #
263
+ # All these properties can be restricted to one axis, and can be applied to
264
+ # just the major or minor ticks
265
+
266
+ fig, axs = plt.subplots(1, 2, figsize=(6.4, 3.2), layout='constrained')
267
+
268
+ for nn, ax in enumerate(axs):
269
+ ax.plot(np.arange(100))
270
+ if nn == 1:
271
+ ax.grid('on')
272
+ ax.tick_params(right=True, left=False, axis='y', color='r', length=16,
273
+ grid_color='none')
274
+ ax.tick_params(axis='x', color='m', length=4, direction='in', width=4,
275
+ labelcolor='g', grid_color='b')
testbed/matplotlib__matplotlib/galleries/users_explain/axes/colorbar_placement.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. _colorbar_placement:
3
+
4
+ .. redirect-from:: /gallery/subplots_axes_and_figures/colorbar_placement
5
+
6
+ =================
7
+ Placing Colorbars
8
+ =================
9
+
10
+ Colorbars indicate the quantitative extent of image data. Placing in
11
+ a figure is non-trivial because room needs to be made for them.
12
+
13
+ The simplest case is just attaching a colorbar to each axes:
14
+ """
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+
18
+ # Fixing random state for reproducibility
19
+ np.random.seed(19680801)
20
+
21
+ fig, axs = plt.subplots(2, 2)
22
+ cmaps = ['RdBu_r', 'viridis']
23
+ for col in range(2):
24
+ for row in range(2):
25
+ ax = axs[row, col]
26
+ pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
27
+ cmap=cmaps[col])
28
+ fig.colorbar(pcm, ax=ax)
29
+
30
+ # %%
31
+ # The first column has the same type of data in both rows, so it may
32
+ # be desirable to combine the colorbar which we do by calling
33
+ # `.Figure.colorbar` with a list of axes instead of a single axes.
34
+
35
+ fig, axs = plt.subplots(2, 2)
36
+ cmaps = ['RdBu_r', 'viridis']
37
+ for col in range(2):
38
+ for row in range(2):
39
+ ax = axs[row, col]
40
+ pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
41
+ cmap=cmaps[col])
42
+ fig.colorbar(pcm, ax=axs[:, col], shrink=0.6)
43
+
44
+ # %%
45
+ # Relatively complicated colorbar layouts are possible using this
46
+ # paradigm. Note that this example works far better with
47
+ # ``layout='constrained'``
48
+
49
+ fig, axs = plt.subplots(3, 3, layout='constrained')
50
+ for ax in axs.flat:
51
+ pcm = ax.pcolormesh(np.random.random((20, 20)))
52
+
53
+ fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom')
54
+ fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom')
55
+ fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6)
56
+ fig.colorbar(pcm, ax=[axs[2, 1]], location='left')
57
+
58
+ # %%
59
+ # Colorbars with fixed-aspect-ratio axes
60
+ # ======================================
61
+ #
62
+ # Placing colorbars for axes with a fixed aspect ratio pose a particular
63
+ # challenge as the parent axes changes size depending on the data view.
64
+
65
+ fig, axs = plt.subplots(2, 2, layout='constrained')
66
+ cmaps = ['RdBu_r', 'viridis']
67
+ for col in range(2):
68
+ for row in range(2):
69
+ ax = axs[row, col]
70
+ pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
71
+ cmap=cmaps[col])
72
+ if col == 0:
73
+ ax.set_aspect(2)
74
+ else:
75
+ ax.set_aspect(1/2)
76
+ if row == 1:
77
+ fig.colorbar(pcm, ax=ax, shrink=0.6)
78
+
79
+ # %%
80
+ # One way around this issue is to use an `.Axes.inset_axes` to locate the
81
+ # axes in axes coordinates. Note that if you zoom in on the axes, and
82
+ # change the shape of the axes, the colorbar will also change position.
83
+
84
+ fig, axs = plt.subplots(2, 2, layout='constrained')
85
+ cmaps = ['RdBu_r', 'viridis']
86
+ for col in range(2):
87
+ for row in range(2):
88
+ ax = axs[row, col]
89
+ pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
90
+ cmap=cmaps[col])
91
+ if col == 0:
92
+ ax.set_aspect(2)
93
+ else:
94
+ ax.set_aspect(1/2)
95
+ if row == 1:
96
+ cax = ax.inset_axes([1.04, 0.2, 0.05, 0.6])
97
+ fig.colorbar(pcm, ax=ax, cax=cax)
98
+
99
+ plt.show()
testbed/matplotlib__matplotlib/galleries/users_explain/axes/constrainedlayout_guide.py ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ .. redirect-from:: /tutorials/intermediate/constrainedlayout_guide
4
+
5
+ .. _constrainedlayout_guide:
6
+
7
+ ================================
8
+ Constrained Layout Guide
9
+ ================================
10
+
11
+ Use *constrained layout* to fit plots within your figure cleanly.
12
+
13
+ *Constrained layout* automatically adjusts subplots so that decorations like tick
14
+ labels, legends, and colorbars do not overlap, while still preserving the
15
+ logical layout requested by the user.
16
+
17
+ *Constrained layout* is similar to :ref:`Tight
18
+ layout<tight_layout_guide>`, but is substantially more
19
+ flexible. It handles colorbars placed on multiple Axes
20
+ (:ref:`colorbar_placement`) nested layouts (`~.Figure.subfigures`) and Axes that
21
+ span rows or columns (`~.pyplot.subplot_mosaic`), striving to align spines from
22
+ Axes in the same row or column. In addition, :ref:`Compressed layout
23
+ <compressed_layout>` will try and move fixed aspect-ratio Axes closer together.
24
+ These features are described in this document, as well as some
25
+ :ref:`implementation details <cl_notes_on_algorithm>` discussed at the end.
26
+
27
+ *Constrained layout* typically needs to be activated before any Axes are added to
28
+ a figure. Two ways of doing so are
29
+
30
+ * using the respective argument to `~.pyplot.subplots`,
31
+ `~.pyplot.figure`, `~.pyplot.subplot_mosaic` e.g.::
32
+
33
+ plt.subplots(layout="constrained")
34
+
35
+ * activate it via :ref:`rcParams<customizing-with-dynamic-rc-settings>`, like::
36
+
37
+ plt.rcParams['figure.constrained_layout.use'] = True
38
+
39
+ Those are described in detail throughout the following sections.
40
+
41
+ .. warning::
42
+
43
+ Calling ``plt.tight_layout()`` will turn off *constrained layout*!
44
+
45
+ Simple example
46
+ ==============
47
+
48
+ In Matplotlib, the location of Axes (including subplots) are specified in
49
+ normalized figure coordinates. It can happen that your axis labels or titles
50
+ (or sometimes even ticklabels) go outside the figure area, and are thus
51
+ clipped.
52
+ """
53
+
54
+ # sphinx_gallery_thumbnail_number = 18
55
+
56
+
57
+ import matplotlib.pyplot as plt
58
+ import numpy as np
59
+
60
+ import matplotlib.colors as mcolors
61
+ import matplotlib.gridspec as gridspec
62
+
63
+ plt.rcParams['savefig.facecolor'] = "0.8"
64
+ plt.rcParams['figure.figsize'] = 4.5, 4.
65
+ plt.rcParams['figure.max_open_warning'] = 50
66
+
67
+
68
+ def example_plot(ax, fontsize=12, hide_labels=False):
69
+ ax.plot([1, 2])
70
+
71
+ ax.locator_params(nbins=3)
72
+ if hide_labels:
73
+ ax.set_xticklabels([])
74
+ ax.set_yticklabels([])
75
+ else:
76
+ ax.set_xlabel('x-label', fontsize=fontsize)
77
+ ax.set_ylabel('y-label', fontsize=fontsize)
78
+ ax.set_title('Title', fontsize=fontsize)
79
+
80
+ fig, ax = plt.subplots(layout=None)
81
+ example_plot(ax, fontsize=24)
82
+
83
+ # %%
84
+ # To prevent this, the location of Axes needs to be adjusted. For
85
+ # subplots, this can be done manually by adjusting the subplot parameters
86
+ # using `.Figure.subplots_adjust`. However, specifying your figure with the
87
+ # ``layout="constrained"`` keyword argument will do the adjusting
88
+ # automatically.
89
+
90
+ fig, ax = plt.subplots(layout="constrained")
91
+ example_plot(ax, fontsize=24)
92
+
93
+ # %%
94
+ # When you have multiple subplots, often you see labels of different
95
+ # Axes overlapping each other.
96
+
97
+ fig, axs = plt.subplots(2, 2, layout=None)
98
+ for ax in axs.flat:
99
+ example_plot(ax)
100
+
101
+ # %%
102
+ # Specifying ``layout="constrained"`` in the call to ``plt.subplots``
103
+ # causes the layout to be properly constrained.
104
+
105
+ fig, axs = plt.subplots(2, 2, layout="constrained")
106
+ for ax in axs.flat:
107
+ example_plot(ax)
108
+
109
+ # %%
110
+ #
111
+ # Colorbars
112
+ # =========
113
+ #
114
+ # If you create a colorbar with `.Figure.colorbar`, you need to make room for
115
+ # it. *Constrained layout* does this automatically. Note that if you
116
+ # specify ``use_gridspec=True`` it will be ignored because this option is made
117
+ # for improving the layout via ``tight_layout``.
118
+ #
119
+ # .. note::
120
+ #
121
+ # For the `~.axes.Axes.pcolormesh` keyword arguments (``pc_kwargs``) we use a
122
+ # dictionary to keep the calls consistent across this document.
123
+
124
+ arr = np.arange(100).reshape((10, 10))
125
+ norm = mcolors.Normalize(vmin=0., vmax=100.)
126
+ # see note above: this makes all pcolormesh calls consistent:
127
+ pc_kwargs = {'rasterized': True, 'cmap': 'viridis', 'norm': norm}
128
+ fig, ax = plt.subplots(figsize=(4, 4), layout="constrained")
129
+ im = ax.pcolormesh(arr, **pc_kwargs)
130
+ fig.colorbar(im, ax=ax, shrink=0.6)
131
+
132
+ # %%
133
+ # If you specify a list of Axes (or other iterable container) to the
134
+ # ``ax`` argument of ``colorbar``, *constrained layout* will take space from
135
+ # the specified Axes.
136
+
137
+ fig, axs = plt.subplots(2, 2, figsize=(4, 4), layout="constrained")
138
+ for ax in axs.flat:
139
+ im = ax.pcolormesh(arr, **pc_kwargs)
140
+ fig.colorbar(im, ax=axs, shrink=0.6)
141
+
142
+ # %%
143
+ # If you specify a list of Axes from inside a grid of Axes, the colorbar
144
+ # will steal space appropriately, and leave a gap, but all subplots will
145
+ # still be the same size.
146
+
147
+ fig, axs = plt.subplots(3, 3, figsize=(4, 4), layout="constrained")
148
+ for ax in axs.flat:
149
+ im = ax.pcolormesh(arr, **pc_kwargs)
150
+ fig.colorbar(im, ax=axs[1:, 1], shrink=0.8)
151
+ fig.colorbar(im, ax=axs[:, -1], shrink=0.6)
152
+
153
+ # %%
154
+ # Suptitle
155
+ # =========
156
+ #
157
+ # *Constrained layout* can also make room for `~.Figure.suptitle`.
158
+
159
+ fig, axs = plt.subplots(2, 2, figsize=(4, 4), layout="constrained")
160
+ for ax in axs.flat:
161
+ im = ax.pcolormesh(arr, **pc_kwargs)
162
+ fig.colorbar(im, ax=axs, shrink=0.6)
163
+ fig.suptitle('Big Suptitle')
164
+
165
+ # %%
166
+ # Legends
167
+ # =======
168
+ #
169
+ # Legends can be placed outside of their parent axis.
170
+ # *Constrained layout* is designed to handle this for :meth:`.Axes.legend`.
171
+ # However, *constrained layout* does *not* handle legends being created via
172
+ # :meth:`.Figure.legend` (yet).
173
+
174
+ fig, ax = plt.subplots(layout="constrained")
175
+ ax.plot(np.arange(10), label='This is a plot')
176
+ ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
177
+
178
+ # %%
179
+ # However, this will steal space from a subplot layout:
180
+
181
+ fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained")
182
+ axs[0].plot(np.arange(10))
183
+ axs[1].plot(np.arange(10), label='This is a plot')
184
+ axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
185
+
186
+ # %%
187
+ # In order for a legend or other artist to *not* steal space
188
+ # from the subplot layout, we can ``leg.set_in_layout(False)``.
189
+ # Of course this can mean the legend ends up
190
+ # cropped, but can be useful if the plot is subsequently called
191
+ # with ``fig.savefig('outname.png', bbox_inches='tight')``. Note,
192
+ # however, that the legend's ``get_in_layout`` status will have to be
193
+ # toggled again to make the saved file work, and we must manually
194
+ # trigger a draw if we want *constrained layout* to adjust the size
195
+ # of the Axes before printing.
196
+
197
+ fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained")
198
+
199
+ axs[0].plot(np.arange(10))
200
+ axs[1].plot(np.arange(10), label='This is a plot')
201
+ leg = axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
202
+ leg.set_in_layout(False)
203
+ # trigger a draw so that constrained layout is executed once
204
+ # before we turn it off when printing....
205
+ fig.canvas.draw()
206
+ # we want the legend included in the bbox_inches='tight' calcs.
207
+ leg.set_in_layout(True)
208
+ # we don't want the layout to change at this point.
209
+ fig.set_layout_engine('none')
210
+ try:
211
+ fig.savefig('../../../doc/_static/constrained_layout_1b.png',
212
+ bbox_inches='tight', dpi=100)
213
+ except FileNotFoundError:
214
+ # this allows the script to keep going if run interactively and
215
+ # the directory above doesn't exist
216
+ pass
217
+
218
+ # %%
219
+ # The saved file looks like:
220
+ #
221
+ # .. image:: /_static/constrained_layout_1b.png
222
+ # :align: center
223
+ #
224
+ # A better way to get around this awkwardness is to simply
225
+ # use the legend method provided by `.Figure.legend`:
226
+ fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained")
227
+ axs[0].plot(np.arange(10))
228
+ lines = axs[1].plot(np.arange(10), label='This is a plot')
229
+ labels = [l.get_label() for l in lines]
230
+ leg = fig.legend(lines, labels, loc='center left',
231
+ bbox_to_anchor=(0.8, 0.5), bbox_transform=axs[1].transAxes)
232
+ try:
233
+ fig.savefig('../../../doc/_static/constrained_layout_2b.png',
234
+ bbox_inches='tight', dpi=100)
235
+ except FileNotFoundError:
236
+ # this allows the script to keep going if run interactively and
237
+ # the directory above doesn't exist
238
+ pass
239
+
240
+
241
+ # %%
242
+ # The saved file looks like:
243
+ #
244
+ # .. image:: /_static/constrained_layout_2b.png
245
+ # :align: center
246
+ #
247
+
248
+ # %%
249
+ # Padding and spacing
250
+ # ===================
251
+ #
252
+ # Padding between Axes is controlled in the horizontal by *w_pad* and
253
+ # *wspace*, and vertical by *h_pad* and *hspace*. These can be edited
254
+ # via `~.layout_engine.ConstrainedLayoutEngine.set`. *w/h_pad* are
255
+ # the minimum space around the Axes in units of inches:
256
+
257
+ fig, axs = plt.subplots(2, 2, layout="constrained")
258
+ for ax in axs.flat:
259
+ example_plot(ax, hide_labels=True)
260
+ fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0,
261
+ wspace=0)
262
+
263
+ # %%
264
+ # Spacing between subplots is further set by *wspace* and *hspace*. These
265
+ # are specified as a fraction of the size of the subplot group as a whole.
266
+ # If these values are smaller than *w_pad* or *h_pad*, then the fixed pads are
267
+ # used instead. Note in the below how the space at the edges doesn't change
268
+ # from the above, but the space between subplots does.
269
+
270
+ fig, axs = plt.subplots(2, 2, layout="constrained")
271
+ for ax in axs.flat:
272
+ example_plot(ax, hide_labels=True)
273
+ fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2,
274
+ wspace=0.2)
275
+
276
+ # %%
277
+ # If there are more than two columns, the *wspace* is shared between them,
278
+ # so here the wspace is divided in two, with a *wspace* of 0.1 between each
279
+ # column:
280
+
281
+ fig, axs = plt.subplots(2, 3, layout="constrained")
282
+ for ax in axs.flat:
283
+ example_plot(ax, hide_labels=True)
284
+ fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2,
285
+ wspace=0.2)
286
+
287
+ # %%
288
+ # GridSpecs also have optional *hspace* and *wspace* keyword arguments,
289
+ # that will be used instead of the pads set by *constrained layout*:
290
+
291
+ fig, axs = plt.subplots(2, 2, layout="constrained",
292
+ gridspec_kw={'wspace': 0.3, 'hspace': 0.2})
293
+ for ax in axs.flat:
294
+ example_plot(ax, hide_labels=True)
295
+ # this has no effect because the space set in the gridspec trumps the
296
+ # space set in *constrained layout*.
297
+ fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.0,
298
+ wspace=0.0)
299
+
300
+ # %%
301
+ # Spacing with colorbars
302
+ # -----------------------
303
+ #
304
+ # Colorbars are placed a distance *pad* from their parent, where *pad*
305
+ # is a fraction of the width of the parent(s). The spacing to the
306
+ # next subplot is then given by *w/hspace*.
307
+
308
+ fig, axs = plt.subplots(2, 2, layout="constrained")
309
+ pads = [0, 0.05, 0.1, 0.2]
310
+ for pad, ax in zip(pads, axs.flat):
311
+ pc = ax.pcolormesh(arr, **pc_kwargs)
312
+ fig.colorbar(pc, ax=ax, shrink=0.6, pad=pad)
313
+ ax.set_xticklabels([])
314
+ ax.set_yticklabels([])
315
+ ax.set_title(f'pad: {pad}')
316
+ fig.get_layout_engine().set(w_pad=2 / 72, h_pad=2 / 72, hspace=0.2,
317
+ wspace=0.2)
318
+
319
+ # %%
320
+ # rcParams
321
+ # ========
322
+ #
323
+ # There are five :ref:`rcParams<customizing-with-dynamic-rc-settings>`
324
+ # that can be set, either in a script or in the :file:`matplotlibrc`
325
+ # file. They all have the prefix ``figure.constrained_layout``:
326
+ #
327
+ # - *use*: Whether to use *constrained layout*. Default is False
328
+ # - *w_pad*, *h_pad*: Padding around Axes objects.
329
+ # Float representing inches. Default is 3./72. inches (3 pts)
330
+ # - *wspace*, *hspace*: Space between subplot groups.
331
+ # Float representing a fraction of the subplot widths being separated.
332
+ # Default is 0.02.
333
+
334
+ plt.rcParams['figure.constrained_layout.use'] = True
335
+ fig, axs = plt.subplots(2, 2, figsize=(3, 3))
336
+ for ax in axs.flat:
337
+ example_plot(ax)
338
+
339
+ # %%
340
+ # Use with GridSpec
341
+ # =================
342
+ #
343
+ # *Constrained layout* is meant to be used
344
+ # with :func:`~matplotlib.figure.Figure.subplots`,
345
+ # :func:`~matplotlib.figure.Figure.subplot_mosaic`, or
346
+ # :func:`~matplotlib.gridspec.GridSpec` with
347
+ # :func:`~matplotlib.figure.Figure.add_subplot`.
348
+ #
349
+ # Note that in what follows ``layout="constrained"``
350
+
351
+ plt.rcParams['figure.constrained_layout.use'] = False
352
+ fig = plt.figure(layout="constrained")
353
+
354
+ gs1 = gridspec.GridSpec(2, 1, figure=fig)
355
+ ax1 = fig.add_subplot(gs1[0])
356
+ ax2 = fig.add_subplot(gs1[1])
357
+
358
+ example_plot(ax1)
359
+ example_plot(ax2)
360
+
361
+ # %%
362
+ # More complicated gridspec layouts are possible. Note here we use the
363
+ # convenience functions `~.Figure.add_gridspec` and
364
+ # `~.SubplotSpec.subgridspec`.
365
+
366
+ fig = plt.figure(layout="constrained")
367
+
368
+ gs0 = fig.add_gridspec(1, 2)
369
+
370
+ gs1 = gs0[0].subgridspec(2, 1)
371
+ ax1 = fig.add_subplot(gs1[0])
372
+ ax2 = fig.add_subplot(gs1[1])
373
+
374
+ example_plot(ax1)
375
+ example_plot(ax2)
376
+
377
+ gs2 = gs0[1].subgridspec(3, 1)
378
+
379
+ for ss in gs2:
380
+ ax = fig.add_subplot(ss)
381
+ example_plot(ax)
382
+ ax.set_title("")
383
+ ax.set_xlabel("")
384
+
385
+ ax.set_xlabel("x-label", fontsize=12)
386
+
387
+ # %%
388
+ # Note that in the above the left and right columns don't have the same
389
+ # vertical extent. If we want the top and bottom of the two grids to line up
390
+ # then they need to be in the same gridspec. We need to make this figure
391
+ # larger as well in order for the Axes not to collapse to zero height:
392
+
393
+ fig = plt.figure(figsize=(4, 6), layout="constrained")
394
+
395
+ gs0 = fig.add_gridspec(6, 2)
396
+
397
+ ax1 = fig.add_subplot(gs0[:3, 0])
398
+ ax2 = fig.add_subplot(gs0[3:, 0])
399
+
400
+ example_plot(ax1)
401
+ example_plot(ax2)
402
+
403
+ ax = fig.add_subplot(gs0[0:2, 1])
404
+ example_plot(ax, hide_labels=True)
405
+ ax = fig.add_subplot(gs0[2:4, 1])
406
+ example_plot(ax, hide_labels=True)
407
+ ax = fig.add_subplot(gs0[4:, 1])
408
+ example_plot(ax, hide_labels=True)
409
+ fig.suptitle('Overlapping Gridspecs')
410
+
411
+ # %%
412
+ # This example uses two gridspecs to have the colorbar only pertain to
413
+ # one set of pcolors. Note how the left column is wider than the
414
+ # two right-hand columns because of this. Of course, if you wanted the
415
+ # subplots to be the same size you only needed one gridspec. Note that
416
+ # the same effect can be achieved using `~.Figure.subfigures`.
417
+
418
+ fig = plt.figure(layout="constrained")
419
+ gs0 = fig.add_gridspec(1, 2, figure=fig, width_ratios=[1, 2])
420
+ gs_left = gs0[0].subgridspec(2, 1)
421
+ gs_right = gs0[1].subgridspec(2, 2)
422
+
423
+ for gs in gs_left:
424
+ ax = fig.add_subplot(gs)
425
+ example_plot(ax)
426
+ axs = []
427
+ for gs in gs_right:
428
+ ax = fig.add_subplot(gs)
429
+ pcm = ax.pcolormesh(arr, **pc_kwargs)
430
+ ax.set_xlabel('x-label')
431
+ ax.set_ylabel('y-label')
432
+ ax.set_title('title')
433
+ axs += [ax]
434
+ fig.suptitle('Nested plots using subgridspec')
435
+ fig.colorbar(pcm, ax=axs)
436
+
437
+ # %%
438
+ # Rather than using subgridspecs, Matplotlib now provides `~.Figure.subfigures`
439
+ # which also work with *constrained layout*:
440
+
441
+ fig = plt.figure(layout="constrained")
442
+ sfigs = fig.subfigures(1, 2, width_ratios=[1, 2])
443
+
444
+ axs_left = sfigs[0].subplots(2, 1)
445
+ for ax in axs_left.flat:
446
+ example_plot(ax)
447
+
448
+ axs_right = sfigs[1].subplots(2, 2)
449
+ for ax in axs_right.flat:
450
+ pcm = ax.pcolormesh(arr, **pc_kwargs)
451
+ ax.set_xlabel('x-label')
452
+ ax.set_ylabel('y-label')
453
+ ax.set_title('title')
454
+ fig.colorbar(pcm, ax=axs_right)
455
+ fig.suptitle('Nested plots using subfigures')
456
+
457
+ # %%
458
+ # Manually setting Axes positions
459
+ # ================================
460
+ #
461
+ # There can be good reasons to manually set an Axes position. A manual call
462
+ # to `~.axes.Axes.set_position` will set the Axes so *constrained layout* has
463
+ # no effect on it anymore. (Note that *constrained layout* still leaves the
464
+ # space for the Axes that is moved).
465
+
466
+ fig, axs = plt.subplots(1, 2, layout="constrained")
467
+ example_plot(axs[0], fontsize=12)
468
+ axs[1].set_position([0.2, 0.2, 0.4, 0.4])
469
+
470
+ # %%
471
+ # .. _compressed_layout:
472
+ #
473
+ # Grids of fixed aspect-ratio Axes: "compressed" layout
474
+ # =====================================================
475
+ #
476
+ # *Constrained layout* operates on the grid of "original" positions for
477
+ # Axes. However, when Axes have fixed aspect ratios, one side is usually made
478
+ # shorter, and leaves large gaps in the shortened direction. In the following,
479
+ # the Axes are square, but the figure quite wide so there is a horizontal gap:
480
+
481
+ fig, axs = plt.subplots(2, 2, figsize=(5, 3),
482
+ sharex=True, sharey=True, layout="constrained")
483
+ for ax in axs.flat:
484
+ ax.imshow(arr)
485
+ fig.suptitle("fixed-aspect plots, layout='constrained'")
486
+
487
+ # %%
488
+ # One obvious way of fixing this is to make the figure size more square,
489
+ # however, closing the gaps exactly requires trial and error. For simple grids
490
+ # of Axes we can use ``layout="compressed"`` to do the job for us:
491
+
492
+ fig, axs = plt.subplots(2, 2, figsize=(5, 3),
493
+ sharex=True, sharey=True, layout='compressed')
494
+ for ax in axs.flat:
495
+ ax.imshow(arr)
496
+ fig.suptitle("fixed-aspect plots, layout='compressed'")
497
+
498
+
499
+ # %%
500
+ # Manually turning off *constrained layout*
501
+ # ===========================================
502
+ #
503
+ # *Constrained layout* usually adjusts the Axes positions on each draw
504
+ # of the figure. If you want to get the spacing provided by
505
+ # *constrained layout* but not have it update, then do the initial
506
+ # draw and then call ``fig.set_layout_engine('none')``.
507
+ # This is potentially useful for animations where the tick labels may
508
+ # change length.
509
+ #
510
+ # Note that *constrained layout* is turned off for ``ZOOM`` and ``PAN``
511
+ # GUI events for the backends that use the toolbar. This prevents the
512
+ # Axes from changing position during zooming and panning.
513
+ #
514
+ #
515
+ # Limitations
516
+ # ===========
517
+ #
518
+ # Incompatible functions
519
+ # ----------------------
520
+ #
521
+ # *Constrained layout* will work with `.pyplot.subplot`, but only if the
522
+ # number of rows and columns is the same for each call.
523
+ # The reason is that each call to `.pyplot.subplot` will create a new
524
+ # `.GridSpec` instance if the geometry is not the same, and
525
+ # *constrained layout*. So the following works fine:
526
+
527
+ fig = plt.figure(layout="constrained")
528
+
529
+ ax1 = plt.subplot(2, 2, 1)
530
+ ax2 = plt.subplot(2, 2, 3)
531
+ # third Axes that spans both rows in second column:
532
+ ax3 = plt.subplot(2, 2, (2, 4))
533
+
534
+ example_plot(ax1)
535
+ example_plot(ax2)
536
+ example_plot(ax3)
537
+ plt.suptitle('Homogenous nrows, ncols')
538
+
539
+ # %%
540
+ # but the following leads to a poor layout:
541
+
542
+ fig = plt.figure(layout="constrained")
543
+
544
+ ax1 = plt.subplot(2, 2, 1)
545
+ ax2 = plt.subplot(2, 2, 3)
546
+ ax3 = plt.subplot(1, 2, 2)
547
+
548
+ example_plot(ax1)
549
+ example_plot(ax2)
550
+ example_plot(ax3)
551
+ plt.suptitle('Mixed nrows, ncols')
552
+
553
+ # %%
554
+ # Similarly,
555
+ # `~matplotlib.pyplot.subplot2grid` works with the same limitation
556
+ # that nrows and ncols cannot change for the layout to look good.
557
+
558
+ fig = plt.figure(layout="constrained")
559
+
560
+ ax1 = plt.subplot2grid((3, 3), (0, 0))
561
+ ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
562
+ ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
563
+ ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
564
+
565
+ example_plot(ax1)
566
+ example_plot(ax2)
567
+ example_plot(ax3)
568
+ example_plot(ax4)
569
+ fig.suptitle('subplot2grid')
570
+
571
+ # %%
572
+ # Other caveats
573
+ # -------------
574
+ #
575
+ # * *Constrained layout* only considers ticklabels, axis labels, titles, and
576
+ # legends. Thus, other artists may be clipped and also may overlap.
577
+ #
578
+ # * It assumes that the extra space needed for ticklabels, axis labels,
579
+ # and titles is independent of original location of Axes. This is
580
+ # often true, but there are rare cases where it is not.
581
+ #
582
+ # * There are small differences in how the backends handle rendering fonts,
583
+ # so the results will not be pixel-identical.
584
+ #
585
+ # * An artist using Axes coordinates that extend beyond the Axes
586
+ # boundary will result in unusual layouts when added to an
587
+ # Axes. This can be avoided by adding the artist directly to the
588
+ # :class:`~matplotlib.figure.Figure` using
589
+ # :meth:`~matplotlib.figure.Figure.add_artist`. See
590
+ # :class:`~matplotlib.patches.ConnectionPatch` for an example.
591
+
592
+ # %%
593
+ # Debugging
594
+ # =========
595
+ #
596
+ # *Constrained layout* can fail in somewhat unexpected ways. Because it uses
597
+ # a constraint solver the solver can find solutions that are mathematically
598
+ # correct, but that aren't at all what the user wants. The usual failure
599
+ # mode is for all sizes to collapse to their smallest allowable value. If
600
+ # this happens, it is for one of two reasons:
601
+ #
602
+ # 1. There was not enough room for the elements you were requesting to draw.
603
+ # 2. There is a bug - in which case open an issue at
604
+ # https://github.com/matplotlib/matplotlib/issues.
605
+ #
606
+ # If there is a bug, please report with a self-contained example that does
607
+ # not require outside data or dependencies (other than numpy).
608
+
609
+ # %%
610
+ # .. _cl_notes_on_algorithm:
611
+ #
612
+ # Notes on the algorithm
613
+ # ======================
614
+ #
615
+ # The algorithm for the constraint is relatively straightforward, but
616
+ # has some complexity due to the complex ways we can lay out a figure.
617
+ #
618
+ # Layout in Matplotlib is carried out with gridspecs
619
+ # via the `.GridSpec` class. A gridspec is a logical division of the figure
620
+ # into rows and columns, with the relative width of the Axes in those
621
+ # rows and columns set by *width_ratios* and *height_ratios*.
622
+ #
623
+ # In *constrained layout*, each gridspec gets a *layoutgrid* associated with
624
+ # it. The *layoutgrid* has a series of ``left`` and ``right`` variables
625
+ # for each column, and ``bottom`` and ``top`` variables for each row, and
626
+ # further it has a margin for each of left, right, bottom and top. In each
627
+ # row, the bottom/top margins are widened until all the decorators
628
+ # in that row are accommodated. Similarly, for columns and the left/right
629
+ # margins.
630
+ #
631
+ #
632
+ # Simple case: one Axes
633
+ # ---------------------
634
+ #
635
+ # For a single Axes the layout is straight forward. There is one parent
636
+ # layoutgrid for the figure consisting of one column and row, and
637
+ # a child layoutgrid for the gridspec that contains the Axes, again
638
+ # consisting of one row and column. Space is made for the "decorations" on
639
+ # each side of the Axes. In the code, this is accomplished by the entries in
640
+ # ``do_constrained_layout()`` like::
641
+ #
642
+ # gridspec._layoutgrid[0, 0].edit_margin_min('left',
643
+ # -bbox.x0 + pos.x0 + w_pad)
644
+ #
645
+ # where ``bbox`` is the tight bounding box of the Axes, and ``pos`` its
646
+ # position. Note how the four margins encompass the Axes decorations.
647
+
648
+ from matplotlib._layoutgrid import plot_children
649
+
650
+ fig, ax = plt.subplots(layout="constrained")
651
+ example_plot(ax, fontsize=24)
652
+ plot_children(fig)
653
+
654
+ # %%
655
+ # Simple case: two Axes
656
+ # ---------------------
657
+ # When there are multiple Axes they have their layouts bound in
658
+ # simple ways. In this example the left Axes has much larger decorations
659
+ # than the right, but they share a bottom margin, which is made large
660
+ # enough to accommodate the larger xlabel. Same with the shared top
661
+ # margin. The left and right margins are not shared, and hence are
662
+ # allowed to be different.
663
+
664
+ fig, ax = plt.subplots(1, 2, layout="constrained")
665
+ example_plot(ax[0], fontsize=32)
666
+ example_plot(ax[1], fontsize=8)
667
+ plot_children(fig)
668
+
669
+ # %%
670
+ # Two Axes and colorbar
671
+ # ---------------------
672
+ #
673
+ # A colorbar is simply another item that expands the margin of the parent
674
+ # layoutgrid cell:
675
+
676
+ fig, ax = plt.subplots(1, 2, layout="constrained")
677
+ im = ax[0].pcolormesh(arr, **pc_kwargs)
678
+ fig.colorbar(im, ax=ax[0], shrink=0.6)
679
+ im = ax[1].pcolormesh(arr, **pc_kwargs)
680
+ plot_children(fig)
681
+
682
+ # %%
683
+ # Colorbar associated with a Gridspec
684
+ # -----------------------------------
685
+ #
686
+ # If a colorbar belongs to more than one cell of the grid, then
687
+ # it makes a larger margin for each:
688
+
689
+ fig, axs = plt.subplots(2, 2, layout="constrained")
690
+ for ax in axs.flat:
691
+ im = ax.pcolormesh(arr, **pc_kwargs)
692
+ fig.colorbar(im, ax=axs, shrink=0.6)
693
+ plot_children(fig)
694
+
695
+ # %%
696
+ # Uneven sized Axes
697
+ # -----------------
698
+ #
699
+ # There are two ways to make Axes have an uneven size in a
700
+ # Gridspec layout, either by specifying them to cross Gridspecs rows
701
+ # or columns, or by specifying width and height ratios.
702
+ #
703
+ # The first method is used here. Note that the middle ``top`` and
704
+ # ``bottom`` margins are not affected by the left-hand column. This
705
+ # is a conscious decision of the algorithm, and leads to the case where
706
+ # the two right-hand Axes have the same height, but it is not 1/2 the height
707
+ # of the left-hand Axes. This is consistent with how ``gridspec`` works
708
+ # without *constrained layout*.
709
+
710
+ fig = plt.figure(layout="constrained")
711
+ gs = gridspec.GridSpec(2, 2, figure=fig)
712
+ ax = fig.add_subplot(gs[:, 0])
713
+ im = ax.pcolormesh(arr, **pc_kwargs)
714
+ ax = fig.add_subplot(gs[0, 1])
715
+ im = ax.pcolormesh(arr, **pc_kwargs)
716
+ ax = fig.add_subplot(gs[1, 1])
717
+ im = ax.pcolormesh(arr, **pc_kwargs)
718
+ plot_children(fig)
719
+
720
+ # %%
721
+ # One case that requires finessing is if margins do not have any artists
722
+ # constraining their width. In the case below, the right margin for column 0
723
+ # and the left margin for column 3 have no margin artists to set their width,
724
+ # so we take the maximum width of the margin widths that do have artists.
725
+ # This makes all the Axes have the same size:
726
+
727
+ fig = plt.figure(layout="constrained")
728
+ gs = fig.add_gridspec(2, 4)
729
+ ax00 = fig.add_subplot(gs[0, 0:2])
730
+ ax01 = fig.add_subplot(gs[0, 2:])
731
+ ax10 = fig.add_subplot(gs[1, 1:3])
732
+ example_plot(ax10, fontsize=14)
733
+ plot_children(fig)
734
+ plt.show()