diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index b0e0bcf9cbc9..000000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,106 +0,0 @@ -# With infos from -# http://tjelvarolsson.com/blog/how-to-continuously-test-your-python-code-on-windows-using-appveyor/ -# https://packaging.python.org/en/latest/appveyor/ ---- - -# Backslashes in quotes need to be escaped: \ -> "\\" -branches: - except: - - /auto-backport-.*/ - - /^v\d+\.\d+\.[\dx]+-doc$/ - -skip_commits: - message: /\[ci doc\]/ - files: - - doc/ - - galleries/ - -clone_depth: 50 - -image: Visual Studio 2022 - -environment: - - global: - PYTHONFAULTHANDLER: 1 - PYTHONIOENCODING: UTF-8 - PYTEST_ARGS: -rfEsXR --numprocesses=auto --timeout=300 --durations=25 - --cov-report= --cov=lib --log-level=DEBUG - - matrix: - - PYTHON_VERSION: "3.12" - -# We always use a 64-bit machine, but can build x86 distributions -# with the PYTHON_ARCH variable -platform: - - x64 - -cache: - - '%LOCALAPPDATA%\pip\Cache' - - '%USERPROFILE%\.cache\matplotlib' - -init: - # Force enable long path support, because micromamba isn't doing it correctly. - # https://github.com/mamba-org/mamba/issues/4392 - - ps: - New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" - -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force - - ps: - Invoke-Webrequest - -URI https://micro.mamba.pm/api/micromamba/win-64/latest - -OutFile C:\projects\micromamba.tar.bz2 - - ps: C:\PROGRA~1\7-Zip\7z.exe x C:\projects\micromamba.tar.bz2 -aoa -oC:\projects\ - - ps: C:\PROGRA~1\7-Zip\7z.exe x C:\projects\micromamba.tar -ttar -aoa -oC:\projects\ - - 'set PATH=C:\projects\Library\bin;%PATH%' - - micromamba shell init --shell cmd.exe - - micromamba config set always_yes true - - micromamba config prepend channels conda-forge - - micromamba info - -install: - - set EXTRA_PACKAGES=pywin32 codecov - # These are optional dependencies so that we don't skip so many tests... - - set EXTRA_PACKAGES=%EXTRA_PACKAGES% ffmpeg inkscape - # miktex is available on conda, but seems to fail with permission errors. - # missing packages on conda-forge for imagemagick - # This install sometimes failed randomly :-( - # - choco install imagemagick - - - micromamba env create -f environment.yml python=%PYTHON_VERSION% %EXTRA_PACKAGES% - - micromamba activate mpl-dev - -build_script: - # Now build the thing.. - - set LINK=/LIBPATH:%cd%\lib - - pip install -v --no-build-isolation --editable .[dev] - # this should show no freetype dll... - - set "DUMPBIN=%VS140COMNTOOLS%\..\..\VC\bin\dumpbin.exe" - - '"%DUMPBIN%" /DEPENDENTS lib\matplotlib\ft2font*.pyd | findstr freetype.*.dll && exit /b 1 || exit /b 0' - -test_script: - # Test import of tkagg backend - - python -c - "import matplotlib as m; m.use('tkagg'); - import matplotlib.pyplot as plt; - print(plt.get_backend())" - # tests - - echo The following args are passed to pytest %PYTEST_ARGS% - - pytest %PYTEST_ARGS% - -artifacts: - - path: result_images\* - name: result_images - type: Zip - -on_finish: - - codecov -e PYTHON_VERSION PLATFORM -n "%PYTHON_VERSION% Windows" - -on_failure: - # Generate an html for visual tests - - python tools/visualize_tests.py --no-browser - - echo zipping images after a failure... - - 7z a result_images.zip result_images\ | grep -v "Compressing" - - appveyor PushArtifact result_images.zip - -matrix: - fast_finish: true diff --git a/.coveragerc b/.coveragerc index f8d90f93e600..00059575f610 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,5 +1,6 @@ [run] branch = true +patch = subprocess source = matplotlib mpl_toolkits diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index ddec2754d03a..2761017f6c5d 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,16 +1,16 @@ { - "hostRequirements": { - "memory": "8gb", - "cpus": 4 - }, - "image": "mcr.microsoft.com/devcontainers/universal:2", + "image": "mcr.microsoft.com/devcontainers/base:ubuntu", "features": { + "ghcr.io/devcontainers/features/sshd:1": { + "version": "latest" + }, "ghcr.io/devcontainers/features/desktop-lite:1": {}, "ghcr.io/rocker-org/devcontainer-features/apt-packages:1": { "packages": "inkscape,ffmpeg,dvipng,lmodern,cm-super,texlive-latex-base,texlive-latex-extra,texlive-fonts-recommended,texlive-latex-recommended,texlive-pictures,texlive-xetex,fonts-wqy-zenhei,graphviz,fonts-crosextra-carlito,fonts-freefont-otf,fonts-comic-neue,fonts-noto-cjk,optipng" - } + }, + "ghcr.io/devcontainers/features/conda:1": {} }, - "onCreateCommand": ".devcontainer/setup.sh", + "onCreateCommand": "bash .devcontainer/setup.sh", "postCreateCommand": "", "forwardPorts": [6080], "portsAttributes": { diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh index 88da5baf69e2..48ec0933bef1 100755 --- a/.devcontainer/setup.sh +++ b/.devcontainer/setup.sh @@ -10,4 +10,4 @@ micromamba env create -f environment.yml --yes # Note that `micromamba activate mpl-dev` doesn't work, it must be run by the # user (same applies to `conda activate`) echo "envs_dirs: - - /home/codespace/micromamba/envs" > /opt/conda/.condarc + - $HOME/micromamba/envs" > ~/.condarc diff --git a/.github/labeler.yml b/.github/labeler.yml index ee49868c8d7f..f1d8b357ffca 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -247,7 +247,6 @@ "topic: text/fonts": - changed-files: - any-glob-to-any-file: - - 'src/checkdep_freetype2.c' - 'src/ft2font*' "topic: text/mathtext": - changed-files: diff --git a/.github/workflows/autoclose_schedule.yml b/.github/workflows/autoclose_schedule.yml index f09a1ff42fb1..c2e52ddb95fe 100644 --- a/.github/workflows/autoclose_schedule.yml +++ b/.github/workflows/autoclose_schedule.yml @@ -25,7 +25,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.13' - name: Install PyGithub diff --git a/.github/workflows/cibuildwheel.yml b/.github/workflows/cibuildwheel.yml index 186e066be4b5..edd04098949e 100644 --- a/.github/workflows/cibuildwheel.yml +++ b/.github/workflows/cibuildwheel.yml @@ -47,19 +47,11 @@ jobs: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 name: Install Python with: python-version: '3.12' - # Something changed somewhere that prevents the downloaded-at-build-time - # licenses from being included in built wheels, so pre-download them so - # that they exist before the build and are included. - - name: Pre-download bundled licenses - run: > - curl -Lo LICENSE/LICENSE_QHULL - https://github.com/qhull/qhull/raw/2020.2/COPYING.txt - - name: Install dependencies run: python -m pip install build twine @@ -73,7 +65,7 @@ jobs: run: twine check dist/* - name: Upload sdist result - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cibw-sdist path: dist/*.tar.gz @@ -110,12 +102,12 @@ jobs: cibw_archs: "ARM64" - os: macos-15-intel cibw_archs: "x86_64" - - os: macos-14 + - os: macos-15 cibw_archs: "arm64" steps: - name: Download sdist - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: cibw-sdist path: dist/ @@ -125,7 +117,7 @@ jobs: run: Remove-Item -Recurse C:\Strawberry - name: Build wheels for CPython 3.14 - uses: pypa/cibuildwheel@1828c10ab37f080699c7b81cea34097c684a7074 # v4.2.0 + uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 with: package-dir: dist/${{ needs.build_sdist.outputs.SDIST_NAME }} env: @@ -133,7 +125,7 @@ jobs: CIBW_ARCHS: ${{ matrix.cibw_archs }} - name: Build wheels for CPython 3.13 - uses: pypa/cibuildwheel@1828c10ab37f080699c7b81cea34097c684a7074 # v4.2.0 + uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 with: package-dir: dist/${{ needs.build_sdist.outputs.SDIST_NAME }} env: @@ -141,14 +133,14 @@ jobs: CIBW_ARCHS: ${{ matrix.cibw_archs }} - name: Build wheels for CPython 3.12 - uses: pypa/cibuildwheel@1828c10ab37f080699c7b81cea34097c684a7074 # v4.2.0 + uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 with: package-dir: dist/${{ needs.build_sdist.outputs.SDIST_NAME }} env: CIBW_BUILD: "cp312-*" CIBW_ARCHS: ${{ matrix.cibw_archs }} - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cibw-wheels-${{ runner.os }}-${{ matrix.cibw_archs }} path: ./wheelhouse/*.whl diff --git a/.github/workflows/circleci.yml b/.github/workflows/circleci.yml index 1796be0d03bf..02c221e11b06 100644 --- a/.github/workflows/circleci.yml +++ b/.github/workflows/circleci.yml @@ -14,7 +14,7 @@ jobs: steps: - name: GitHub Action step uses: - scientific-python/circleci-artifacts-redirector-action@5d358ff96e96429a5c64a969bb4a574555439f4f # v1.3.1 + scientific-python/circleci-artifacts-redirector-action@d35a82a1e5de3864f4cf9649eb7cedcedcfe8e09 # v1.3.2 with: repo-token: ${{ secrets.GITHUB_TOKEN }} api-token: ${{ secrets.CIRCLECI_TOKEN }} diff --git a/.github/workflows/clean_pr.yml b/.github/workflows/clean_pr.yml index 07fbecf0df5e..22f476f161c8 100644 --- a/.github/workflows/clean_pr.yml +++ b/.github/workflows/clean_pr.yml @@ -13,7 +13,8 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: '0' + fetch-depth: 0 + filter: tree:0 persist-credentials: false - name: Check for added-and-deleted files run: | diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 430d0aae75c5..8af33db964ae 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -34,7 +34,7 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9 + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: languages: ${{ matrix.language }} @@ -45,4 +45,4 @@ jobs: pip install --user -v . - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9 + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 diff --git a/.github/workflows/cygwin.yml b/.github/workflows/cygwin.yml index 1a4082636da9..b881da6274b2 100644 --- a/.github/workflows/cygwin.yml +++ b/.github/workflows/cygwin.yml @@ -85,7 +85,7 @@ jobs: fetch-depth: 0 persist-credentials: false - - uses: cygwin/cygwin-install-action@3f0a3f9f988f7e96b8c18098ae05eaec175f5b52 # v6 + - uses: cygwin/cygwin-install-action@5a1b0cd107181fa6bb6bf3f90d500f4fb3132f18 # v7.0.0 with: packages: >- ccache gcc-g++ gdb git graphviz libcairo-devel libffi-devel diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index f89bd925d356..eb07ef42e1be 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -14,12 +14,13 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + filter: blob:none persist-credentials: false - - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 + - uses: j178/prek-action@44924fe9ef4a6f88253c4b6b1bf11c689d3ce53d # v3.1.0 with: extra-args: --hook-stage manual --all-files --skip oxipng # Only run oxipng on the last diff, because we haven't updated all images. - - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 + - uses: j178/prek-action@44924fe9ef4a6f88253c4b6b1bf11c689d3ce53d # v3.1.0 with: extra-args: --hook-stage manual --from-ref origin/${{ github.base_ref }} oxipng @@ -35,7 +36,7 @@ jobs: persist-credentials: false - name: Set up Python 3 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.12' @@ -65,7 +66,7 @@ jobs: persist-credentials: false - name: Set up Python 3 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.12' @@ -96,7 +97,7 @@ jobs: persist-credentials: false - name: Set up Python 3 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.14' @@ -128,7 +129,7 @@ jobs: persist-credentials: false - name: eslint - uses: reviewdog/action-eslint@556a3fdaf8b4201d4d74d406013386aa4f7dab96 # v1.34.0 + uses: reviewdog/action-eslint@3ee2a450da17e060b9dfa4bffd53976906c6b2b0 # v1.36.1 with: filter_mode: nofilter github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/mypy-stubtest.yml b/.github/workflows/mypy-stubtest.yml index 8971bf82ad7e..6875510bfbc0 100644 --- a/.github/workflows/mypy-stubtest.yml +++ b/.github/workflows/mypy-stubtest.yml @@ -17,7 +17,7 @@ jobs: persist-credentials: false - name: Set up Python 3 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.12' diff --git a/.github/workflows/nightlies.yml b/.github/workflows/nightlies.yml index 8e8958a961ed..404f64806508 100644 --- a/.github/workflows/nightlies.yml +++ b/.github/workflows/nightlies.yml @@ -60,7 +60,7 @@ jobs: ls -l dist/ - name: Upload wheels to Anaconda Cloud as nightlies - uses: scientific-python/upload-nightly-action@16fa02eacee1655195143de09f03676e60ef2bf5 # 0.6.5 + uses: scientific-python/upload-nightly-action@5a74a2a4ec19d7ab8b5317c1cdd356c150d92cd0 # 0.6.6 with: artifacts_path: dist anaconda_nightly_upload_token: ${{ secrets.ANACONDA_ORG_UPLOAD_TOKEN }} diff --git a/.github/workflows/pr_welcome.yml b/.github/workflows/pr_welcome.yml index f8b004dc5468..b69f31d917eb 100644 --- a/.github/workflows/pr_welcome.yml +++ b/.github/workflows/pr_welcome.yml @@ -15,8 +15,10 @@ jobs: permissions: issues: write pull-requests: write + contents: read steps: - - uses: plbstl/first-contribution@2c36bdb58684587f60549a69aaa3ec00b9d5f4fe # v4.3.3 + - id: first-contribution + uses: plbstl/first-contribution@2c36bdb58684587f60549a69aaa3ec00b9d5f4fe # v4.3.3 with: labels: first-contribution skip-internal-contributors: false @@ -50,3 +52,16 @@ jobs: [Code of Conduct](https://github.com/matplotlib/matplotlib/blob/main/CODE_OF_CONDUCT.md). issue-opened-msg: "" + - name: Run agentscan if first-contribution left a comment + if: "${{ steps.first-contribution.outputs.comment-url != '' }}" + uses: MatteoGabriele/agentscan-action@8112fb79b33fafb8506159df20129a34209ac410 # v2.5.0 + with: + mode: labels + scan-pull-requests: true + scan-issues: true + allowed-users: "meeseeksmachine" + label-mixed: "AgentScan: mixed" + label-automation: "AgentScan: automated" + label-community-flagged: "AgentScan: flagged" + auto-close: false + honeypot: false diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 61603aeeb296..f10ac189951b 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -19,7 +19,7 @@ jobs: repo-token: ${{ secrets.GITHUB_TOKEN }} operations-per-run: 20 stale-pr-message: >- - Since this Pull Request has not been updated in 60 days, it has been marked "inactive." This does + Since this Pull Request has not been updated in over 60 days, it has been marked "inactive." This does not mean that it will be closed, though it may be moved to a "Draft" state. This helps maintainers prioritize their reviewing efforts. You can pick the PR back up anytime - please ping us if you need a review or guidance to move the PR forward! If you do not plan on continuing the work, please @@ -28,7 +28,7 @@ jobs: days-before-pr-stale: 60 days-before-pr-close: -1 stale-issue-message: >- - This issue has been marked "inactive" because it has been 365 days since the last comment. If this + This issue has been marked "inactive" because it has not been updated in over 365 days. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index bf75c80ddae0..3b3793adc3ef 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -75,29 +75,39 @@ jobs: pygobject-ver: '<3.52.0' - os: ubuntu-24.04 python-version: '3.14' + - name-suffix: "Free-threaded" + os: ubuntu-24.04 + python-version: '3.15t' + - os: ubuntu-24.04 + python-version: '3.15' - os: ubuntu-24.04-arm python-version: '3.12' - - os: macos-14 # This runner is on M1 (arm64) chips. + - os: macos-15 # This runner is on M1 (arm64) chips. python-version: '3.12' # https://github.com/matplotlib/matplotlib/issues/29732 pygobject-ver: '<3.52.0' - - os: macos-15 # This runner is on M1 (arm64) chips. + - os: macos-26 # This runner is on M1 (arm64) chips. python-version: '3.13' # https://github.com/matplotlib/matplotlib/issues/29732 pygobject-ver: '<3.52.0' - - os: macos-15 # This runner is on M1 (arm64) chips. + - os: macos-26 # This runner is on M1 (arm64) chips. python-version: '3.14' # https://github.com/matplotlib/matplotlib/issues/29732 pygobject-ver: '<3.52.0' + - os: macos-15 # This runner is on M1 (arm64) chips. + python-version: '3.15' + # https://github.com/matplotlib/matplotlib/issues/29732 + pygobject-ver: '<3.52.0' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + filter: blob:none persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} allow-prereleases: true @@ -172,6 +182,11 @@ jobs: brew unlink ${python_package} brew link --overwrite ${python_package} done + # Remove the stale openssl@1.1 symlink present in the macOS 15 runner image + openssl_link="$(brew --prefix)/bin/openssl" + case "$(readlink "$openssl_link" 2>/dev/null)" in + */openssl@1.1/*) rm -f "$openssl_link" ;; + esac # Workaround for https://github.com/actions/runner-images/issues/10984 brew uninstall --ignore-dependencies --force pkg-config@0.29.2 brew install ccache ffmpeg ghostscript gobject-introspection gtk4 imagemagick ninja @@ -238,7 +253,7 @@ jobs: # Sphinx is needed to run sphinxext tests python -m pip install --upgrade sphinx!=6.1.2 - if [[ "${{ matrix.python-version }}" != '3.14t' ]]; then + if [[ "${{ matrix.python-version }}" != 3.*t && "${{ matrix.python-version }}" != 3.15 ]]; then # GUI toolkits are pip-installable only for some versions of Python # so don't fail if we can't install them. Make it easier to check # whether the install was successful by trying to import the toolkit @@ -277,7 +292,7 @@ jobs: echo 'wxPython is available' || echo 'wxPython is not available' - fi # Skip backends on Python 3.14t. + fi # Skip backends on Python 3.*t. - name: Install the nightly dependencies # Only install the nightly dependencies during the scheduled event @@ -299,7 +314,7 @@ jobs: export CPPFLAGS='-fprofile-instr-generate=default.%m.profraw' export CPPFLAGS="$CPPFLAGS -fcoverage-mapping" else - export CPPFLAGS='--coverage -fprofile-abs-path' + export CPPFLAGS='--coverage -fprofile-abs-path -fprofile-update=prefer-atomic' fi python -m pip install --no-deps --no-build-isolation --verbose \ @@ -317,9 +332,12 @@ jobs: - name: Run pytest run: | - if [[ "${{ matrix.python-version }}" == '3.14t' ]]; then + if [[ "${{ matrix.python-version }}" == 3.*t ]]; then export PYTHON_GIL=0 fi + if [[ "${{ matrix.python-version }}" == 3.15* ]]; then + export PYTEST_ADDOPTS="-k 'not test_backends_interactive'" + fi pytest -rfEsXR -n auto \ --maxfail=50 --timeout=300 --durations=25 \ --cov-report=xml --cov=lib --log-level=DEBUG --color=yes @@ -378,14 +396,22 @@ jobs: xcrun llvm-cov export -format="lcov" build/*/src/*.so \ -instr-profile default.profdata > info.lcov fi + + - name: Upload macOS crash logs + if: failure() && runner.os == 'macOS' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: macos-crash-logs + path: ~/Library/Logs/DiagnosticReports/* + - name: Upload code coverage if: ${{ !cancelled() && github.event_name != 'schedule' }} - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: name: "${{ matrix.python-version }} ${{ matrix.os }} ${{ matrix.name-suffix }}" token: ${{ secrets.CODECOV_TOKEN }} - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: failure() with: name: "${{ matrix.python-version }} ${{ matrix.os }} ${{ matrix.name-suffix }} result images" diff --git a/.github/workflows/triage_board.yml b/.github/workflows/triage_board.yml index 3ef26369afeb..e59645deea2d 100644 --- a/.github/workflows/triage_board.yml +++ b/.github/workflows/triage_board.yml @@ -3,7 +3,7 @@ name: 'Update PR Triage Board' on: schedule: - - cron: '0 * * * *' # Run every hour + - cron: '0 */12 * * *' # Run every 12 hours workflow_dispatch: permissions: {} diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 4400d36f76ae..48142526dc70 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -45,13 +45,13 @@ jobs: persist-credentials: false - name: Build wheels for wasm - uses: pypa/cibuildwheel@1828c10ab37f080699c7b81cea34097c684a7074 # v4.2.0 + uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 env: CIBW_SKIP: "cp315-*" CIBW_PLATFORM: "pyodide" CIBW_TEST_COMMAND: "true" - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cibw-wheels-wasm path: ./wheelhouse/*.whl diff --git a/.github/workflows/windows-tests.yml b/.github/workflows/windows-tests.yml new file mode 100644 index 000000000000..bc60063d849b --- /dev/null +++ b/.github/workflows/windows-tests.yml @@ -0,0 +1,252 @@ +--- +name: Windows tests + +on: + push: + branches-ignore: + - auto-backport-of-pr-[0-9]+ + - v[0-9]+.[0-9]+.[0-9x]+-doc + - dependabot/** + pull_request: + branches-ignore: + - v[0-9]+.[0-9]+.[0-9x]+-doc + paths-ignore: + - 'doc/**' + - 'galleries/**' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }}-${{ github.event.ref }} + cancel-in-progress: true + +permissions: {} + +env: + PYTHONFAULTHANDLER: 1 + PYTHONIOENCODING: UTF-8 + +jobs: + pip-msvc: + if: >- + github.event_name == 'workflow_dispatch' || + ( + github.repository == 'matplotlib/matplotlib' && + !contains(github.event.head_commit.message, '[ci skip]') && + !contains(github.event.head_commit.message, '[skip ci]') && + !contains(github.event.head_commit.message, '[skip github]') && + !contains(github.event.head_commit.message, '[ci doc]') + ) + permissions: + contents: read + name: "pip/MSVC: Python ${{ matrix.python-version }} on ${{ matrix.os }}" + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - os: windows-2022 + python-version: '3.12' + - os: windows-latest + python-version: '3.13' + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Cache pip + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~\AppData\Local\pip\Cache + key: windows-${{ matrix.os }}-py${{ matrix.python-version }}-pip-${{ hashFiles('pyproject.toml') }} + restore-keys: | + windows-${{ matrix.os }}-py${{ matrix.python-version }}-pip- + + - name: Install OS dependencies + run: choco install ninja --yes --no-progress + + - name: Install Python dependencies + run: | + python -m pip install --upgrade pip + python -m pip install --upgrade --group build + python -m pip install --prefer-binary --group test --group test-extra + + - name: Build Matplotlib with MSVC coverage support + run: | + python -m pip install --no-build-isolation --verbose --editable '.[dev]' ` + --config-settings=setup-args=--vsenv ` + --config-settings=setup-args=-Dcpp_link_args=-PROFILE ` + --config-settings=setup-args=-Dbuildtype=debug + + - name: Show environment + run: | + Get-ChildItem Env: | Sort-Object Name + python -m pip list + git describe + + - name: Instrument extension modules and start native coverage collector + shell: bash + run: | + vswhere='/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe' + vs=$("$vswhere" -latest -products '*' -property installationPath | tr -d '\r') + tool_dir="$vs/Common7/IDE/Extensions/Microsoft/CodeCoverage.Console" + tool=$(cygpath -u "$tool_dir/Microsoft.CodeCoverage.Console.exe") + if [[ ! -x $tool ]]; then + echo "Microsoft.CodeCoverage.Console.exe was not found at $tool" + exit 1 + fi + + session_id=$(python -c "import uuid; print(uuid.uuid4(), end='')") + echo "VS_COVERAGE_TOOL=$tool" >> "$GITHUB_ENV" + echo "COVERAGE_SESSION_ID=$session_id" >> "$GITHUB_ENV" + echo "Coverage tool: $tool" + echo "Coverage session: $session_id" + + for module in build/cp*/src/*.pyd; do + echo "Instrumenting $module" + "$tool" instrument "$module" --session-id "$session_id" \ + --log-level Verbose --log-file instrument.log + cat instrument.log + done + + "$tool" collect --session-id "$session_id" --server-mode \ + --output-format cobertura --output extensions.xml \ + --log-level Verbose --log-file extensions.log & + + - name: Run pytest + run: | + python -m pytest -rfEsXR -n auto ` + --maxfail=50 --timeout=300 --durations=25 --log-level=DEBUG ` + --cov-report=xml:coverage.xml --cov=lib + + - name: Stop native coverage collector + if: always() + shell: bash + run: | + if [[ -n $VS_COVERAGE_TOOL && -n $COVERAGE_SESSION_ID ]]; then + "$VS_COVERAGE_TOOL" shutdown "$COVERAGE_SESSION_ID" + fi + if [[ -f extensions.log ]]; then + echo 'Native coverage collection log' + cat extensions.log + fi + + - name: Upload code coverage + if: ${{ !cancelled() }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + files: coverage.xml,extensions.xml + name: "${{ matrix.python-version }} ${{ matrix.os }}" + token: ${{ secrets.CODECOV_TOKEN }} + + - name: Upload failed image comparisons + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: pip-msvc-${{ matrix.os }}-py${{ matrix.python-version }}-result-images + path: result_images + + conda: + if: >- + github.event_name == 'workflow_dispatch' || + ( + github.repository == 'matplotlib/matplotlib' && + !contains(github.event.head_commit.message, '[ci skip]') && + !contains(github.event.head_commit.message, '[skip ci]') && + !contains(github.event.head_commit.message, '[skip github]') && + !contains(github.event.head_commit.message, '[ci doc]') + ) + permissions: + contents: read + name: "conda-forge: Python 3.12 on windows-2022" + runs-on: windows-2022 + timeout-minutes: 30 + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + + - name: Cache pip + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~\AppData\Local\pip\Cache + key: windows-conda-py312-pip-${{ hashFiles('environment.yml') }} + restore-keys: | + windows-conda-py312-pip- + + - name: Cache Matplotlib + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~\.cache\matplotlib + key: windows-conda-py312-mpl-${{ github.ref }}-${{ github.sha }} + restore-keys: | + windows-conda-py312-mpl-${{ github.ref }}- + windows-conda-py312-mpl- + + - name: Set up micromamba + uses: mamba-org/setup-micromamba@f457c30a868e4760d3a6fcea5f25dc655b8edf39 # v3 + with: + micromamba-version: 2.9.0-0 + micromamba-root-path: ${{ runner.temp }}\micromamba + init-shell: none + cache-downloads: true + cache-downloads-key: windows-conda-py312-${{ hashFiles('environment.yml') }} + + # Create the environment explicitly, rather than via setup-micromamba's + # environment-file option, so that we can add extra packages on top of + # environment.yml. + - name: Create conda environment + env: + MAMBA_ROOT_PREFIX: ${{ runner.temp }}\micromamba + run: | + micromamba create --yes --name mpl-dev --file environment.yml ` + python=3.12 pywin32 codecov ffmpeg inkscape + + - name: Build Matplotlib + env: + MAMBA_ROOT_PREFIX: ${{ runner.temp }}\micromamba + run: | + $env:LINK = "/LIBPATH:$pwd\lib" + micromamba run --name mpl-dev python -m pip install --verbose ` + --no-build-isolation --editable '.[dev]' + + - name: Verify TkAgg backend + env: + MAMBA_ROOT_PREFIX: ${{ runner.temp }}\micromamba + run: | + micromamba run --name mpl-dev python -c ` + "import matplotlib as m; m.use('tkagg'); import matplotlib.pyplot as plt; print(plt.get_backend())" + + - name: Run pytest + env: + MAMBA_ROOT_PREFIX: ${{ runner.temp }}\micromamba + run: | + micromamba run --name mpl-dev python -m pytest -rfEsXR -n auto ` + --timeout=300 --durations=25 --log-level=DEBUG ` + --cov-report=xml:coverage-conda.xml --cov=lib + + - name: Upload code coverage + if: ${{ !cancelled() }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + files: coverage-conda.xml + name: "3.12 windows-2022 conda-forge" + token: ${{ secrets.CODECOV_TOKEN }} + + - name: Upload failed image comparisons + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: conda-windows-2022-py312-result-images + path: result_images diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index 853bef83e04a..16a186237a35 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -27,4 +27,4 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@70fb788f84895a7701f5643d103d587e460b5c99 # v0.6.3 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5425b3fb99ee..0269064b7670 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,7 +29,7 @@ repos: - id: trailing-whitespace exclude_types: [diff, svg] - repo: https://github.com/pre-commit/mirrors-mypy - rev: d2823d321df3af8f878f7ee3414dc94d037145b9 # frozen: v2.1.0 + rev: 2834ec6639549dd6796205c8f011dedcd587288b # frozen: v2.4.0 hooks: - id: mypy additional_dependencies: @@ -44,13 +44,18 @@ repos: pass_filenames: false - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: c59bba8fb259db0fec2bbb77ad8ba51ea7341b56 # frozen: v0.15.20 + rev: f368fb366ff7f2f808dd324b83a6d32267799e19 # frozen: v0.17.2 hooks: # Run the linter. - id: ruff-check args: [--fix, --show-fixes] + # Sort imports in the galleries, mirroring the previous isort scope. + - id: ruff-check + name: ruff isort (galleries) + args: [--fix, --show-fixes, --select=I001] + files: ^galleries/tutorials/|^galleries/examples/|^galleries/plot_types/ - repo: https://github.com/codespell-project/codespell - rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.2 + rev: 57b21406f092110c18776e39b0bda50d37c945c8 # frozen: v2.4.3 hooks: - id: codespell files: ^.*\.(py|c|cpp|h|m|md|rst|yml)$ @@ -59,18 +64,12 @@ repos: - "ci/codespell-ignore-words.txt" - "--skip" - "doc/project/credits.rst" - - repo: https://github.com/pycqa/isort - rev: a333737ed43df02b18e6c95477ea1b285b3de15a # frozen: 8.0.1 - hooks: - - id: isort - name: isort (python) - files: ^galleries/tutorials/|^galleries/examples/|^galleries/plot_types/ - repo: https://github.com/rstcheck/rstcheck rev: d8774e96810795967ed9603f445b4e751e7b313f # frozen: v6.3.0 hooks: - id: rstcheck additional_dependencies: - - sphinx>=1.8.1 + - sphinx>=9.2.0 args: ["--sphinx-source-dir", "doc"] - repo: https://github.com/adrienverge/yamllint rev: cba56bcde1fdd01c1deb3f945e69764c291a6530 # frozen: v1.38.0 @@ -82,7 +81,7 @@ repos: hooks: - id: shellcheck - repo: https://github.com/zizmorcore/zizmor-pre-commit - rev: e3eebf65325ccc992422292cb7a4baee967cf815 # frozen: v1.26.1 + rev: c92afdf2c6ca336aaa8f39e2bd8d48f62dbd8e1f # frozen: v1.31.1 hooks: - id: zizmor - repo: https://github.com/simple-icons/svglint @@ -94,18 +93,12 @@ repos: # SVG examples are handled in .svglintrc.mjs. exclude: '^$' - repo: https://github.com/python-jsonschema/check-jsonschema - rev: 5030dca3047414c338091455ac41803200ec1f0f # frozen: 0.37.3 + rev: 0494aa7fa1314e98913a41227d8f0a515b2c1049 # frozen: 0.38.2 hooks: - # TODO: Re-enable this when https://github.com/microsoft/azure-pipelines-vscode/issues/567 is fixed. - # - id: check-azure-pipelines - id: check-dependabot - id: check-github-workflows # NOTE: If any of the below schema files need to be changed, be sure to # update the `ci/vendor_schemas.py` script. - - id: check-jsonschema - name: "Validate AppVeyor config" - files: ^\.appveyor\.yml$ - args: ["--verbose", "--schemafile", "ci/schemas/appveyor.json"] - id: check-jsonschema name: "Validate CircleCI config" files: ^\.circleci/config\.yml$ @@ -136,6 +129,6 @@ repos: files: ^environment\.yml$ args: ["--verbose", "--schemafile", "ci/schemas/conda-environment.json"] - repo: https://github.com/oxipng/oxipng - rev: 628e241e23f368097883807fa6e985ccf7c00357 # frozen: v10.1.1 + rev: 36f3ef8aac65ecf1761739ea2f2e530281f1312b # frozen: v10.2.1 hooks: - id: oxipng diff --git a/README.md b/README.md index bbbbec35331e..2567260ab962 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,6 @@ [![Contributing](https://img.shields.io/badge/PR-Welcome-%23FF8300.svg?)](https://matplotlib.org/stable/devel/index.html) [![GitHub actions status](https://github.com/matplotlib/matplotlib/workflows/Tests/badge.svg)](https://github.com/matplotlib/matplotlib/actions?query=workflow%3ATests) -[![Azure pipelines status](https://dev.azure.com/matplotlib/matplotlib/_apis/build/status/matplotlib.matplotlib?branchName=main)](https://dev.azure.com/matplotlib/matplotlib/_build/latest?definitionId=1&branchName=main) -[![AppVeyor status](https://ci.appveyor.com/api/projects/status/github/matplotlib/matplotlib?branch=main&svg=true)](https://ci.appveyor.com/project/matplotlib/matplotlib) [![Codecov status](https://codecov.io/github/matplotlib/matplotlib/badge.svg?branch=main&service=github)](https://app.codecov.io/gh/matplotlib/matplotlib) [![EffVer Versioning](https://img.shields.io/badge/version_scheme-EffVer-0097a7)](https://jacobtomlinson.dev/effver) diff --git a/azure-pipelines.yml b/azure-pipelines.yml deleted file mode 100644 index c8df751f2419..000000000000 --- a/azure-pipelines.yml +++ /dev/null @@ -1,159 +0,0 @@ -# Python package -# Create and test a Python package on multiple Python versions. -# Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and -# more: -# https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python?view=azure-devops - ---- -trigger: - branches: - exclude: - - v*-doc -pr: - branches: - exclude: - - v*-doc - paths: - exclude: - - doc/**/* - - galleries/**/* - -stages: - - - stage: Check - jobs: - - job: Skip - pool: - vmImage: 'ubuntu-latest' - variables: - DECODE_PERCENTS: 'false' - RET: 'true' - steps: - - bash: | - git_log=`git log --max-count=1 --skip=1 --pretty=format:"%B" | tr "\n" " "` - echo "##vso[task.setvariable variable=log]$git_log" - - bash: echo "##vso[task.setvariable variable=RET]false" - condition: >- - or(contains(variables.log, '[skip azp]'), - contains(variables.log, '[azp skip]'), - contains(variables.log, '[skip ci]'), - contains(variables.log, '[ci skip]'), - contains(variables.log, '[ci doc]')) - - bash: echo "##vso[task.setvariable variable=start_main;isOutput=true]$RET" - name: result - - - stage: Main - condition: and(succeeded(), eq(dependencies.Check.outputs['Skip.result.start_main'], 'true')) - dependsOn: Check - jobs: - - job: Pytest - strategy: - matrix: - Windows_py312: - vmImage: 'windows-2022' # Keep one job pinned to the oldest image - python.version: '3.12' - Windows_py313: - vmImage: 'windows-latest' - python.version: '3.13' - maxParallel: 4 - pool: - vmImage: '$(vmImage)' - steps: - - task: UsePythonVersion@0 - inputs: - versionSpec: '$(python.version)' - architecture: 'x64' - displayName: 'Use Python $(python.version)' - - - bash: | - choco install ninja - displayName: 'Install dependencies' - - - bash: | - python -m pip install --upgrade pip - python -m pip install --upgrade --group build - python -m pip install --prefer-binary --group test --group test-extra - displayName: 'Install dependencies with pip' - - - bash: | - CONFIG='--config-settings=setup-args=--vsenv' - CONFIG="$CONFIG --config-settings=setup-args=-Dcpp_link_args=-PROFILE" - CONFIG="$CONFIG --config-settings=setup-args=-Dbuildtype=debug" - - python -m pip install \ - --no-build-isolation $CONFIG \ - --verbose --editable .[dev] - displayName: "Install self" - - - script: env - displayName: 'print env' - - - script: pip list - displayName: 'print pip' - - - bash: | - set -e - SESSION_ID=$(python -c "import uuid; print(uuid.uuid4(), end='')") - echo "Coverage session ID: ${SESSION_ID}" - VS=$(ls -d /c/Program\ Files*/Microsoft\ Visual\ Studio/*/Enterprise) - echo "Visual Studio: ${VS}" - DIR="$VS/Common7/IDE/Extensions/Microsoft/CodeCoverage.Console" - # This is for MSVC 2022 (on windows-latest). - TOOL="$DIR/Microsoft.CodeCoverage.Console.exe" - for f in build/cp*/src/*.pyd; do - echo $f - echo "==============================" - "$TOOL" instrument $f --session-id $SESSION_ID \ - --log-level Verbose --log-file instrument.log - cat instrument.log - rm instrument.log - done - echo "Starting $TOOL in server mode" - "$TOOL" collect \ - --session-id $SESSION_ID --server-mode \ - --output-format cobertura --output extensions.xml \ - --log-level Verbose --log-file extensions.log & - VS_VER=2022 - - echo "##vso[task.setvariable variable=VS_COVERAGE_TOOL]$TOOL" - - PYTHONFAULTHANDLER=1 pytest -rfEsXR -n 2 \ - --maxfail=50 --timeout=300 --durations=25 \ - --junitxml=junit/test-results.xml --cov-report=xml --cov=lib - - if [[ $VS_VER == 2022 ]]; then - "$TOOL" shutdown $SESSION_ID - echo "Coverage collection log" - echo "=======================" - cat extensions.log - else - "$TOOL" shutdown -session:$SESSION_ID - fi - displayName: 'pytest' - - - bash: | - if [[ -f extensions.coverage ]]; then - # For MSVC 2019. - "$VS_COVERAGE_TOOL" analyze -output:extensions.xml \ - -include_skipped_functions -include_skipped_modules \ - extensions.coverage - rm extensions.coverage - fi - displayName: 'Filter C coverage' - condition: succeededOrFailed() - - bash: | - bash <(curl -s https://codecov.io/bash) \ - -n "$PYTHON_VERSION $AGENT_OS" \ - -f 'coverage.xml' -f 'extensions.xml' - displayName: 'Upload to codecov.io' - condition: succeededOrFailed() - - - task: PublishTestResults@2 - inputs: - testResultsFiles: '**/test-results.xml' - testRunTitle: 'Python $(python.version)' - condition: succeededOrFailed() - - - publish: $(System.DefaultWorkingDirectory)/result_images - artifact: $(Agent.JobName)-result_images - condition: failed() diff --git a/ci/check_wheel_licenses.py b/ci/check_wheel_licenses.py index 13470dc692bd..ae3f0a2b66a3 100644 --- a/ci/check_wheel_licenses.py +++ b/ci/check_wheel_licenses.py @@ -25,7 +25,7 @@ with zipfile.ZipFile(wheel) as f: wheel_license_file_names = {Path(path).name for path in sorted(f.namelist()) - if '.dist-info/LICENSE' in path} + if '.dist-info/licenses/LICENSE' in path} if not (len(wheel_license_file_names) and wheel_license_file_names.issuperset(license_file_names)): sys.exit(f'LICENSE file(s) missing:\n' diff --git a/ci/minver-requirements.txt b/ci/minver-requirements.txt index 91193d1c6511..328c17290486 100644 --- a/ci/minver-requirements.txt +++ b/ci/minver-requirements.txt @@ -5,10 +5,10 @@ cycler==0.12.0 fonttools==4.28.2 importlib-resources==3.2.0 kiwisolver==1.3.2 -meson-python==0.13.2 -meson==1.1.0 +meson-python==0.18.0 +meson==1.6.0 numpy==2.0.0 -packaging==20.0 +packaging==23.2 pillow==9.0.1 pyparsing==3.0.0 pytest==7.0.0 diff --git a/ci/schemas/appveyor.json b/ci/schemas/appveyor.json deleted file mode 100644 index d19a10f23b75..000000000000 --- a/ci/schemas/appveyor.json +++ /dev/null @@ -1,781 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "allOf": [ - { - "$ref": "#/definitions/job" - } - ], - "definitions": { - "possiblySecretString": { - "anyOf": [ - { - "type": "string", - "description": "This value will be used directly (regular string)" - }, - { - "type": "number", - "description": "This value will be treated as a string even though it is a number" - }, - { - "title": "secret string", - "type": "object", - "additionalProperties": false, - "properties": { - "secure": { - "type": "string", - "description": "This should have been encrypted by the same user account to which the project belongs" - } - } - } - ] - }, - "commitFilter": { - "title": "commit filter", - "type": "object", - "additionalProperties": false, - "properties": { - "message": { - "type": "string", - "format": "regex", - "description": "Regex for matching commit message" - }, - "author": { - "description": "Commit author's username, name, email or regexp matching one of these.", - "anyOf": [ - { - "type": "string", - "format": "regex" - }, - { - "type": "string" - } - ] - }, - "files": { - "type": "array", - "description": "Only specific files (glob patterns)", - "items": { - "type": "string" - } - } - } - }, - "command": { - "title": "command", - "oneOf": [ - { - "type": "string", - "description": "Run a batch command" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "ps": { - "type": "string", - "description": "Run a PowerShell command" - } - } - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "pwsh": { - "type": "string", - "description": "Run a PowerShell Core command" - } - } - }, - { - "type": "object", - "description": "Run a batch command", - "additionalProperties": false, - "properties": { - "cmd": { - "type": "string" - } - } - }, - { - "type": "object", - "description": "Run a Bash command", - "additionalProperties": false, - "properties": { - "sh": { - "type": "string" - } - } - } - ] - }, - "envVarHash": { - "title": "environment variable hash", - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/possiblySecretString" - } - }, - "platform": { - "enum": ["x86", "x64", "ARM", "ARM64", "Win32", "Any CPU"] - }, - "configuration": { - "type": "string" - }, - "imageName": { - "enum": [ - "macOS", - "macOS-Mojave", - "macos-bigsur", - "macos-monterey", - "Previous macOS", - "Previous macOS-Mojave", - "Ubuntu", - "Ubuntu1604", - "Ubuntu1804", - "Ubuntu2004", - "Ubuntu2204", - "Previous Ubuntu", - "Previous Ubuntu1604", - "Previous Ubuntu1804", - "Previous Ubuntu2004", - "Visual Studio 2013", - "Visual Studio 2015", - "Visual Studio 2017", - "Visual Studio 2019", - "Visual Studio 2022", - "Visual Studio 2017 Preview", - "Visual Studio 2019 Preview", - "Previous Visual Studio 2013", - "Previous Visual Studio 2015", - "Previous Visual Studio 2017", - "Previous Visual Studio 2019", - "Previous Visual Studio 2022", - "zhaw18", - "WMF 5" - ] - }, - "image": { - "description": "Build worker image (VM template) -DEV_VERSION", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "#/definitions/imageName" - } - }, - { - "$ref": "#/definitions/imageName" - } - ] - }, - "jobScalars": { - "title": "job scalars", - "type": "object", - "properties": { - "image": { - "$ref": "#/definitions/image" - }, - "platform": { - "description": "Build platform, i.e. x86, x64, Any CPU. This setting is optional", - "oneOf": [ - { - "$ref": "#/definitions/platform" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/platform" - } - } - ] - }, - "configuration": { - "description": "Build Configuration, i.e. Debug, Release, etc.", - "oneOf": [ - { - "$ref": "#/definitions/configuration" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/configuration" - } - } - ] - } - }, - "allOf": [ - { - "not": { - "required": ["skip_tags"] - } - }, - { - "not": { - "required": ["skip_commits"] - } - }, - { - "not": { - "required": ["skip_branch_with_pr"] - } - }, - { - "not": { - "required": ["skip_non_tags"] - } - } - ] - }, - "job": { - "title": "job", - "type": "object", - "properties": { - "version": { - "description": "Version format", - "type": "string" - }, - "branches": { - "title": "branch options", - "type": "object", - "description": "Branches to build", - "additionalProperties": false, - "properties": { - "only": { - "description": "Whitelist", - "type": "array", - "items": { - "type": "string" - } - }, - "except": { - "type": "array", - "description": "Blacklist", - "items": { - "type": "string" - } - } - } - }, - "skip_tags": { - "type": "boolean", - "description": "Do not build on tags (GitHub and BitBucket)" - }, - "skip_non_tags": { - "type": "boolean", - "description": "Start builds on tags only (GitHub and BitBucket)" - }, - "skip_commits": { - "$ref": "#/definitions/commitFilter", - "description": "Skipping commits with particular message or from specific user" - }, - "only_commits": { - "$ref": "#/definitions/commitFilter", - "description": "Including commits with particular message or from specific user" - }, - "skip_branch_with_pr": { - "type": "boolean", - "description": "Do not build feature branch with open Pull Requests" - }, - "max_jobs": { - "description": "Maximum number of concurrent jobs for the project", - "type": "integer" - }, - "notifications": { - "type": "array", - "items": { - "title": "notification", - "type": "object" - } - }, - "image": { - "$ref": "#/definitions/image" - }, - "init": { - "description": "Scripts that are called at very beginning, before repo cloning", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "clone_folder": { - "type": "string", - "description": "Clone directory" - }, - "shallow_clone": { - "type": "boolean", - "description": "Fetch repository as zip archive", - "default": false - }, - "clone_depth": { - "description": "Set git clone depth", - "type": "integer" - }, - "hosts": { - "title": "host options", - "type": "object", - "description": "Setting up etc\\hosts file", - "additionalProperties": { - "type": "string", - "anyOf": [ - { - "format": "ipv4" - }, - { - "format": "ipv6" - } - ] - } - }, - "environment": { - "description": "Environment variables", - "anyOf": [ - { - "title": "environment options", - "type": "object", - "properties": { - "global": { - "$ref": "#/definitions/envVarHash", - "description": "variables defined here are no different than those defined at top level of 'environment' node" - }, - "matrix": { - "type": "array", - "description": "an array of environment variables, each member of which is one dimension in the build matrix calculation", - "items": { - "$ref": "#/definitions/envVarHash" - } - } - } - }, - { - "$ref": "#/definitions/envVarHash" - } - ] - }, - "matrix": { - "title": "matrix options", - "type": "object", - "additionalProperties": false, - "properties": { - "fast_finish": { - "type": "boolean", - "description": "Set this flag to immediately finish build once one of the jobs fails" - }, - "allow_failures": { - "type": "array", - "description": "This is how to allow failing jobs in the matrix", - "items": { - "$ref": "#/definitions/jobScalars" - } - }, - "exclude": { - "type": "array", - "description": "Exclude configuration from the matrix. Works similarly to 'allow_failures' but build not even being started for excluded combination.", - "items": { - "$ref": "#/definitions/job" - } - } - } - }, - "cache": { - "type": "array", - "description": "Build cache to preserve files/folders between builds", - "items": { - "type": "string" - } - }, - "services": { - "type": "array", - "description": "Enable service required for build/tests", - "items": { - "enum": [ - "docker", - "iis", - "mongodb", - "msmq", - "mssql", - "mssql2008r2sp2", - "mssql2008r2sp2rs", - "mssql2012sp1", - "mssql2012sp1rs", - "mssql2014", - "mssql2014rs", - "mssql2016", - "mssql2017", - "mysql", - "postgresql", - "postgresql93", - "postgresql94", - "postgresql95", - "postgresql96", - "postgresql10", - "postgresql11", - "postgresql12", - "postgresql13" - ] - } - }, - "install": { - "description": "Scripts that run after cloning repository", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "assembly_info": { - "title": "assembly options", - "type": "object", - "description": "Enable patching of AssemblyInfo.* files", - "additionalProperties": false, - "properties": { - "patch": { - "type": "boolean" - }, - "file": { - "type": "string" - }, - "assembly_version": { - "type": "string" - }, - "assembly_file_version": { - "type": "string" - }, - "assembly_informational_version": { - "type": "string" - } - } - }, - "nuget": { - "title": "NuGet options", - "type": "object", - "description": "Automatically register private account and/or project AppVeyor NuGet feeds", - "properties": { - "account_feed": { - "type": "boolean" - }, - "project_feed": { - "type": "boolean" - }, - "disable_publish_on_pr": { - "type": "boolean", - "description": "Disable publishing of .nupkg artifacts to account/project feeds for pull request builds" - } - } - }, - "platform": { - "description": "Build platform, i.e. x86, x64, Any CPU. This setting is optional", - "oneOf": [ - { - "$ref": "#/definitions/platform" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/platform" - } - } - ] - }, - "configuration": { - "description": "Build Configuration, i.e. Debug, Release, etc.", - "oneOf": [ - { - "$ref": "#/definitions/configuration" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/configuration" - } - } - ] - }, - "build": { - "oneOf": [ - { - "type": "boolean", - "enum": [false] - }, - { - "title": "build options", - "type": "object", - "additionalProperties": false, - "properties": { - "parallel": { - "type": "boolean", - "description": "Enable MSBuild parallel builds" - }, - "project": { - "type": "string", - "description": "Path to Visual Studio solution or project" - }, - "publish_wap": { - "type": "boolean", - "description": "Package Web Application Projects (WAP) for Web Deploy" - }, - "publish_wap_xcopy": { - "type": "boolean", - "description": "Package Web Application Projects (WAP) for XCopy deployment" - }, - "publish_wap_beanstalk": { - "type": "boolean", - "description": "Package Web Applications for AWS Elastic Beanstalk deployment" - }, - "publish_wap_octopus": { - "type": "boolean", - "description": "Package Web Applications for Octopus deployment" - }, - "publish_azure_webjob": { - "type": "boolean", - "description": "Package Azure WebJobs for Zip Push deployment" - }, - "publish_azure": { - "type": "boolean", - "description": "Package Azure Cloud Service projects and push to artifacts" - }, - "publish_aspnet_core": { - "type": "boolean", - "description": "Package ASP.NET Core projects" - }, - "publish_core_console": { - "type": "boolean", - "description": "Package .NET Core console projects" - }, - "publish_nuget": { - "type": "boolean", - "description": "Package projects with .nuspec files and push to artifacts" - }, - "publish_nuget_symbols": { - "type": "boolean", - "description": "Generate and publish NuGet symbol packages" - }, - "include_nuget_references": { - "type": "boolean", - "description": "Add -IncludeReferencedProjects option while packaging NuGet artifacts" - }, - "verbosity": { - "enum": ["quiet", "minimal", "normal", "detailed"], - "description": "MSBuild verbosity level" - } - } - } - ] - }, - "before_build": { - "description": "Scripts to run before build", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "before_package": { - "description": "Scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services)", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "after_build": { - "description": "Scripts to run after build", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "build_script": { - "description": "To run your custom scripts instead of automatic MSBuild", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "before_test": { - "description": "Scripts to run before tests", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "test": { - "oneOf": [ - { - "type": "boolean", - "enum": [false], - "description": "To disable automatic tests" - }, - { - "title": "test options", - "description": "To run tests again only selected assemblies and/or categories", - "type": "object", - "additionalProperties": false, - "properties": { - "assemblies": { - "title": "assembly options", - "type": "object", - "additionalProperties": false, - "properties": { - "only": { - "type": "array", - "items": { - "type": "string" - } - }, - "except": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "categories": { - "oneOf": [ - { - "title": "category options", - "type": "object", - "additionalProperties": false, - "properties": { - "only": { - "type": "array", - "items": { - "type": "string" - } - }, - "except": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - { - "description": "To run tests from different categories as separate jobs in parallel", - "type": "array", - "items": { - "oneOf": [ - { - "type": "string", - "description": "A category common for all jobs" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - } - } - ] - } - } - } - ] - }, - "test_script": { - "description": "To run your custom scripts instead of automatic tests", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "after_test": { - "type": "array", - "description": "Scripts to run after tests", - "items": { - "$ref": "#/definitions/command" - } - }, - "artifacts": { - "type": "array", - "items": { - "title": "artifact options", - "type": "object", - "additionalProperties": false, - "properties": { - "path": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "Auto", - "WebDeployPackage", - "NuGetPackage", - "AzureCloudService", - "AzureCloudServiceConfig", - "SsdtPackage", - "Zip", - "File" - ] - } - }, - "required": ["path"] - } - }, - "before_deploy": { - "type": "array", - "description": "Scripts to run before deployment", - "items": { - "$ref": "#/definitions/command" - } - }, - "deploy": { - "oneOf": [ - { - "enum": ["off"] - }, - { - "type": "array", - "items": { - "title": "deployment options", - "type": "object" - } - } - ] - }, - "deploy_script": { - "description": "To run your custom scripts instead of provider deployments", - "type": "array", - "items": { - "$ref": "#/definitions/command" - } - }, - "after_deploy": { - "type": "array", - "description": "Scripts to run after deployment", - "items": { - "$ref": "#/definitions/command" - } - }, - "on_success": { - "type": "array", - "description": "On successful build", - "items": { - "$ref": "#/definitions/command" - } - }, - "on_failure": { - "type": "array", - "description": "On build failure", - "items": { - "$ref": "#/definitions/command" - } - }, - "on_finish": { - "type": "array", - "description": "After build failure or success", - "items": { - "$ref": "#/definitions/command" - } - } - } - } - }, - "id": "https://json.schemastore.org/appveyor.json", - "title": "JSON schema for AppVeyor CI configuration files" -} diff --git a/ci/schemas/vendor_schemas.py b/ci/schemas/vendor_schemas.py index a40e262e69f7..e4983a4a9bd6 100644 --- a/ci/schemas/vendor_schemas.py +++ b/ci/schemas/vendor_schemas.py @@ -13,7 +13,6 @@ HERE = pathlib.Path(__file__).parent SCHEMAS = [ - 'https://json.schemastore.org/appveyor.json', 'https://json.schemastore.org/circleciconfig.json', 'https://json.schemastore.org/github-funding.json', 'https://json.schemastore.org/github-issue-config.json', diff --git a/doc/Makefile b/doc/Makefile index baed196a3ee2..d33f7e36cd06 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -17,7 +17,7 @@ help: # workaround because sphinx does not completely clean up (#11139) clean: @$(SPHINXBUILD) -M clean "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - rm -rf "$(SOURCEDIR)/build" + rm -rf "$(SOURCEDIR)/$(BUILDDIR)" rm -rf "$(SOURCEDIR)/_tags" rm -rf "$(SOURCEDIR)/api/_as_gen" rm -rf "$(SOURCEDIR)/gallery" @@ -30,7 +30,7 @@ clean: rm -f $(SOURCEDIR)/sg_execution_times.rst show: - @python -c "import webbrowser; webbrowser.open_new_tab('file://$(shell pwd)/build/html/index.html')" + @python -c "import webbrowser; webbrowser.open_new_tab('file://$(shell pwd)/$(BUILDDIR)/html/index.html')" html-noplot: $(SPHINXBUILD) -D plot_gallery=0 -b html $(SOURCEDIR) $(BUILDDIR)/html $(SPHINXOPTS) $(O) diff --git a/doc/_static/mpl.css b/doc/_static/mpl.css index 881384478a09..4a4d1384b2a8 100644 --- a/doc/_static/mpl.css +++ b/doc/_static/mpl.css @@ -152,7 +152,6 @@ div.wide-table table th.stub { .checklist { list-style: none; padding: 0; - margin: 0; } .checklist li { margin-left: 24px; @@ -161,7 +160,7 @@ div.wide-table table th.stub { } .checklist li:before { content: "\2610\2001"; - margin-left: -24px; + margin-left: -30px; } .checklist li p { display: inline; @@ -202,13 +201,29 @@ div.wide-table table th.stub { * .. toctree:: * */ - .section-toc.toctree-wrapper .toctree-l1>a{ +.section-toc.toctree-wrapper .toctree-l1>a{ display: none; } .section-toc.toctree-wrapper .toctree-l1>ul{ padding-left: 0; } +/* no-caption-toc is a custom class that removes the caption from a + * toctree listing inside a grid-item-card. + */ +.no-caption-toc>p.caption{ + display: none; +} + +/* Align the button at the bottom of a grid-item-card, so that buttons line up + * across cards whose body text wraps to different heights. + * (used in devel/index) + */ +.sd-card-body.sd-d-flex-column > p:last-child { + margin-top: auto; + margin-bottom: 0; +} + .sidebar-cheatsheets { margin-bottom: 3em; } diff --git a/doc/api/axis_api.rst b/doc/api/axis_api.rst index 388779c0ebc5..2c9a94d5bf65 100644 --- a/doc/api/axis_api.rst +++ b/doc/api/axis_api.rst @@ -230,7 +230,7 @@ Discouraged These methods should be used together with care, calling ``set_ticks`` to specify the desired tick locations **before** calling ``set_ticklabels`` to specify a matching series of labels. Calling ``set_ticks`` makes a -`~matplotlib.ticker.FixedLocator`; it's list of locations is then used by +`~matplotlib.ticker.FixedLocator`; its list of locations is then used by ``set_ticklabels`` to make an appropriate `~matplotlib.ticker.FuncFormatter`. diff --git a/doc/api/backend_qt_api.rst b/doc/api/backend_qt_api.rst index 2f950adb672a..a7059207c4cf 100644 --- a/doc/api/backend_qt_api.rst +++ b/doc/api/backend_qt_api.rst @@ -28,7 +28,7 @@ Python binding for Qt5 and there are both `PyQt6 `_ and `PySide6 `_ for Qt6 [#]_. Matplotlib's qtagg and qtcairo backends (``matplotlib.backends.backend_qtagg`` and -``matplotlib.backend.backend_qtcairo``) support all these bindings, with common +``matplotlib.backends.backend_qtcairo``) support all these bindings, with common parts factored out in the ``matplotlib.backends.backend_qt`` module. At runtime, these backends select the actual binding used as follows: diff --git a/doc/api/next_api_changes/behavior/32281-CAZM.rst b/doc/api/next_api_changes/behavior/32281-CAZM.rst new file mode 100644 index 000000000000..69706daab85a --- /dev/null +++ b/doc/api/next_api_changes/behavior/32281-CAZM.rst @@ -0,0 +1,9 @@ +``EngFormatter.format_data`` honors ``axes.unicode_minus`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`.EngFormatter.format_data` and `.EngFormatter.format_eng` now honor +:rc:`axes.unicode_minus`, like `.ScalarFormatter.format_data`. With the default +rcParams, negative values are returned with a Unicode minus sign (U+2212) +instead of an ASCII hyphen (U+002D), as are negative exponents of values beyond +the range of SI prefixes. Tick labels and the offset text already used +the Unicode minus, so plots are unchanged. diff --git a/doc/api/next_api_changes/behavior/animation_stop_event_stop_not_null.rst b/doc/api/next_api_changes/behavior/animation_stop_event_stop_not_null.rst new file mode 100644 index 000000000000..728c93c49369 --- /dev/null +++ b/doc/api/next_api_changes/behavior/animation_stop_event_stop_not_null.rst @@ -0,0 +1,22 @@ +``TimedAnimation``/``Animation`` no longer set to None when an animation stops +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously upon animation completion or fig close ``.Animation.event_source`` +was set to ``None``. Now the event source is stopped and retained on +the animation. + +The following code snippet would before have returned None but would now return a +``matplotlib.backend_bases.TimerBase``. Code that used None to check for successful +stoppage should be updated. + +.. code-block:: python + + import matplotlib + matplotlib.use('agg') + import matplotlib.pyplot as plt + from matplotlib.animation import FuncAnimation + + fig, ax = plt.subplots() + anim = FuncAnimation(fig, lambda f: [], frames=3, repeat=False) + # Wait for the animation to finish. + print(anim.event_source) diff --git a/doc/api/next_api_changes/behavior/timezone_string_parsing.rst b/doc/api/next_api_changes/behavior/timezone_string_parsing.rst new file mode 100644 index 000000000000..531110f03ded --- /dev/null +++ b/doc/api/next_api_changes/behavior/timezone_string_parsing.rst @@ -0,0 +1,16 @@ +Timezone strings are now parsed using `~zoneinfo.ZoneInfo` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Timezone strings are now parsed using `~zoneinfo.ZoneInfo` rather than +`~dateutil.tz.gettz`. This change affects the following methods: + +- `matplotlib.axis.Axis.axis_date` +- `matplotlib.dates.num2date` +- `matplotlib.dates.DateFormatter` +- `matplotlib.dates.DateLocator` and subclasses + +Timezone identifiers must be valid IANA time zone keys (``"America/Los_Angeles"``). + +Other strings will raise a `~zoneinfo.ZoneInfoNotFoundError`. This includes +abbreviations (``"EST"``), POSIX-style names (``"EST5EDT"``), and invalid time zone +keys (``"Invalid/Zone"``). diff --git a/doc/api/toolkits/mplot3d/view_angles.rst b/doc/api/toolkits/mplot3d/view_angles.rst index e4200cd2d0e4..8ce018692828 100644 --- a/doc/api/toolkits/mplot3d/view_angles.rst +++ b/doc/api/toolkits/mplot3d/view_angles.rst @@ -71,7 +71,7 @@ A different variety of trackball rotates along the shortest arc on the virtual sphere (``mouserotationstyle: sphere``). Rotating around the viewing direction is straightforward with it: grab the ball near its edge instead of near the center. -Ken Shoemake's ARCBALL [Shoemake1992]_ is also available (``mouserotationstyle: Shoemake``); +Ken Shoemake's ARCBALL [Shoemake1992]_ is also available (``mouserotationstyle: arcball``); it resembles the ``sphere`` style, but is free of hysteresis, i.e., returning mouse to the original position returns the figure to its original orientation; the rotation is independent diff --git a/doc/conf.py b/doc/conf.py index d88b1ae88c89..8bc81d4cad78 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -305,7 +305,9 @@ def autodoc_process_bases(app, name, obj, options, bases): 'filename_pattern': '^((?!sgskip).)*$', 'gallery_dirs': gallery_dirs, 'image_scrapers': (matplotlib_reduced_latex_scraper, ), - 'image_srcset': ["2x"], + # Keep high-DPI images in deployed documentation, but avoid generating the + # additional renders for pull-request builds. + 'image_srcset': ["2x"] if is_release_build else [], 'junit': '../test-results/sphinx-gallery/junit.xml' if CIRCLECI else '', 'matplotlib_animations': sg_matplotlib_animations, 'min_reported_time': 1, @@ -841,6 +843,16 @@ def linkcode_resolve(domain, info): extensions.append('sphinx.ext.viewcode') +def disable_warning_banner_for_devel(app, pagename, templatename, context, doctree): + """Hide the version warning on pages that redirect to devdocs. + + The stable-version link on these pages leads back to the same development + page, so the warning is misleading. + """ + if pagename.startswith('devel/'): + context['theme_show_version_warning_banner'] = False + + # ----------------------------------------------------------------------------- # Sphinx setup # ----------------------------------------------------------------------------- @@ -854,4 +866,5 @@ def setup(app): app.connect('autodoc-process-bases', autodoc_process_bases) if sphinx.version_info[:2] < (7, 1): app.connect('html-page-context', add_html_cache_busting, priority=1000) + app.connect('html-page-context', disable_warning_banner_for_devel, priority=400) app.config.autodoc_use_legacy_class_based = True diff --git a/doc/devel/MEP/MEP26.rst b/doc/devel/MEP/MEP26.rst index 9d3af8f8c703..2ff1574ff166 100644 --- a/doc/devel/MEP/MEP26.rst +++ b/doc/devel/MEP/MEP26.rst @@ -67,7 +67,7 @@ Implementation It will be easiest to allow a '3rd party' to modify/set the style of an artist if the 'style' is created as a separate class and store against the artist as a -property. The `.GraphicsContextBase` class already provides a the basis of a +property. The `.GraphicsContextBase` class already provides the basis of a ``Style`` class and an artist's `~.Artist.draw` method can be refactored to use the ``Style`` class rather than setting up its own `.GraphicsContextBase` and transferring its style-related properties to it. A minimal example of how this @@ -137,7 +137,7 @@ initial development: Artist Type Selector -Select an `.Artist` by it's type. E.g `.Line2D` or `.Text`:: +Select an `.Artist` by its type. E.g `.Line2D` or `.Text`:: Line2D {attribute: value} diff --git a/doc/devel/MEP/MEP27.rst b/doc/devel/MEP/MEP27.rst index caf032c5c22d..8d58f875830a 100644 --- a/doc/devel/MEP/MEP27.rst +++ b/doc/devel/MEP/MEP27.rst @@ -148,7 +148,7 @@ The description of this MEP gives us most of the solution: Future compatibility ==================== -As eluded to above when discussing MEP 22, this refactor makes it easy +As alluded to above when discussing MEP 22, this refactor makes it easy to add in new generic features. At the moment, MEP 22 has to make ugly hacks to each class extending from ``FigureManagerBase``. With this code, this only needs to get made in the single ``FigureManager`` diff --git a/doc/devel/MEP/MEP28.rst b/doc/devel/MEP/MEP28.rst index 7ae9f8e610d4..001d93750ae1 100644 --- a/doc/devel/MEP/MEP28.rst +++ b/doc/devel/MEP/MEP28.rst @@ -47,7 +47,7 @@ Detailed description Currently, the ``Axes.boxplot`` method accepts parameters that allow the users to specify medians and confidence intervals for each box that will be drawn in the plot. These were provided so that advanced users -could provide statistics computed in a different fashion that the simple +could provide statistics computed in a different fashion than the simple method provided by matplotlib. However, handling this input requires complex logic to make sure that the forms of the data structure match what needs to be drawn. At the moment, that logic contains 9 separate if/else @@ -101,7 +101,7 @@ boxplots will allow users to opt-out of that assumption if the data are known to not fit a normal distribution. Below is an example of how ``Axes.boxplot`` classifies outliers of lognormal -data differently depending one these types of transforms. +data differently depending on these types of transforms. .. plot:: :include-source: true @@ -252,7 +252,7 @@ This MEP can be divided into a few loosely coupled components: #. Removing redundant statistical options in ``Axes.boxplot`` #. Shifting all styling parameter processing from ``Axes.boxplot`` to ``Axes.bxp``. -With this approach, #2 depends and #1, and #4 depends on #3. +With this approach, #2 depends on #1, and #4 depends on #3. There are two possible approaches to #2. The first and most direct would be to mirror the new ``transform_in`` and ``transform_out`` parameters of diff --git a/doc/devel/contribute.rst b/doc/devel/contribute.rst index b409d0b7bd72..9e1ca56b889a 100644 --- a/doc/devel/contribute.rst +++ b/doc/devel/contribute.rst @@ -104,7 +104,7 @@ you can: - Write or update an :ref:`example plot ` - Write or update a comprehensive :ref:`tutorial ` -Our code is documented inline in the source code files in :file:`matplotlib/lib`. +Our code is documented inline in the source code files in :file:`lib/matplotlib`. Our website structure mirrors our folder structure, meaning that a narrative document's URL roughly corresponds to its location in our folder structure: @@ -113,8 +113,8 @@ document's URL roughly corresponds to its location in our folder structure: .. grid-item:: using the library * :file:`galleries/plot_types/` - * :file:`users/getting_started/` - * :file:`galleries/user_explain/` + * :file:`doc/users/getting_started/` + * :file:`galleries/users_explain/` * :file:`galleries/tutorials/` * :file:`galleries/examples/` * :file:`doc/api/` @@ -248,7 +248,7 @@ veteran contributors, who are keen to support onboarding of new folks and share their experience. You can find our community calendar link at the `Scientific Python website `_, and you can browse previous meeting notes on `GitHub -`_. +`_. We recommend joining the meeting to clarify any doubts, or lingering questions you might have, and to get to know a few of the people behind the GitHub handles 😉. You can reach out to us on `incubator chat`_ for any diff --git a/doc/devel/development_setup.rst b/doc/devel/development_setup.rst index 2ee9193c9fa5..7997769034bc 100644 --- a/doc/devel/development_setup.rst +++ b/doc/devel/development_setup.rst @@ -186,7 +186,7 @@ setup. Create a new `conda`_ environment and install the Python dependencies with :: - conda env create -f environment.yml + conda create -f environment.yml You can use ``mamba`` instead of ``conda`` in the above command if you have `mamba`_ installed. @@ -321,20 +321,23 @@ you are aware of the existing issues beforehand. .. _pre-commit-hooks: -Install pre-commit hooks -======================== +Install git pre-commit hooks +============================ + `prek `_ hooks save time in the review process by identifying issues with the code before a pull request is formally opened. Most -hooks can also aide in fixing the errors, and the checks should have +hooks can also aid in fixing the errors, and the checks should have corresponding :ref:`development workflow ` and :ref:`pull request ` guidelines. Hooks are configured in `.pre-commit-config.yaml `_ -and include checks for spelling and formatting, flake 8 conformity, accidentally +and include checks for spelling and formatting, style conformity, accidentally committed files, import order, and incorrect branching. Install pre-commit hooks :: - python -m pip install prek + # e.g. + # pixi global install prek + # uv tool install prek prek install Hooks are run automatically after the ``git commit`` stage of the diff --git a/doc/devel/development_workflow.rst b/doc/devel/development_workflow.rst index 99c7e29234aa..398edf865683 100644 --- a/doc/devel/development_workflow.rst +++ b/doc/devel/development_workflow.rst @@ -113,7 +113,7 @@ The editing workflow .. code-block:: none - # On branch ny-new-feature + # On branch my-new-feature # Changed but not updated: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) @@ -517,9 +517,9 @@ will run on all supported platforms and versions of Python. * Codecov and CodeQL are currently for information only. Their failure is not necessarily a blocker. -Make sure the Linting, GitHub Actions, AppVeyor, CircleCI, and Azure pipelines are -passing before merging. All checks are listed at the bottom of the GitHub page of your -pull request. +Make sure the Linting, GitHub Actions, and CircleCI checks are passing before +merging. All checks are listed at the bottom of the GitHub page of your pull +request. .. list-table:: :header-rows: 1 @@ -539,17 +539,10 @@ pull request. * - CircleCI - :ref:`documentation build ` - Search the CircleCI log for ``WARNING``. - * - | GitHub Actions - | AppVeyor - | Azure pipelines + * - GitHub Actions - :ref:`tests ` - - | Search the log for ``FAILURES``. Subsequent section should contain information - on failed tests. - | - | On Azure, find the images as *artifacts* of the Azure job: - | 1. Click *Details* on the check on the GitHub PR page. - | 2. Click *View more details on Azure Pipelines* to go to Azure. - | 3. On the overview page *artifacts* are listed in the section *Related*. + - Search the log for ``FAILURES``. The subsequent section should contain + information on failed tests. Skip CI checks -------------- @@ -573,12 +566,6 @@ on individual commits by including the following strings in the commit message: * - ``[skip doc]`` - Skip documentation checks. - For when you didn't change documentation. - * - ``[skip appveyor]`` - - Skip AppVeyor run. - - Substring must be in first line of commit message. - * - ``[skip azp]`` - - Skip Azure Pipelines. - - * - ``[skip actions]`` - Skip GitHub Actions. - diff --git a/doc/devel/document.rst b/doc/devel/document.rst index 01a46386d52a..e19e009a3efd 100644 --- a/doc/devel/document.rst +++ b/doc/devel/document.rst @@ -2,9 +2,9 @@ .. _documenting-matplotlib: -=================== -Write documentation -=================== +============================= +Build and write documentation +============================= All documentation is built from the :file:`doc/` folder, but (as explained in this guide) some of these files are generated from inline docstrings or sphinx gallery files. @@ -13,14 +13,14 @@ some of these files are generated from inline docstrings or sphinx gallery files Don't directly edit the ``.rst`` files in :file:`doc/plot_types`, :file:`doc/gallery`, :file:`doc/tutorials`, :file:`doc/users/explain` and - :file:`doc/api` (except :file:`doc/api/api_changes/`). Sphinx_ regenerates + :file:`doc/api` (except :file:`doc/api/next_api_changes/`). Sphinx_ regenerates files in these directories when building documentation. Overview ======== Documentation is created in three ways. First, API documentation (:file:`doc/api`) is created by Sphinx_ from the docstrings of the classes in the Matplotlib library. Except -for :file:`doc/api/api_changes/`, ``.rst`` files in :file:`doc/api` are created +for :file:`doc/api/next_api_changes/`, ``.rst`` files in :file:`doc/api` are created when the documentation is built. See :ref:`writing-docstrings`. Second, our example pages, tutorials, and some of the user guide are created by @@ -31,7 +31,7 @@ See :ref:`writing-examples-and-tutorials`. Third, Matplotlib has informative documentation written in ReST in subdirectories of :file:`doc`. General and historical information about the project is in :file:`doc/project`, the installation guide is in :file:`doc/install`, and release notes are managed in -:file:`doc/release`. Maintenance documentation is in :file:`doc\devel` and the website +:file:`doc/release`. Maintenance documentation is in :file:`doc/devel` and the website always redirects to the latest version of these documents. We also maintain a list of external resources in :file:`doc/users/resources/index.rst`. To improve these documents or add resources, see :ref:`writing-rest-pages`. @@ -167,97 +167,7 @@ a good introduction into using ReST. More complete information is available in the `reStructuredText reference documentation `_. -This section contains additional information and conventions how ReST is used -in the Matplotlib documentation. - -Formatting and style conventions --------------------------------- - -It is useful to strive for consistency in the Matplotlib documentation. Here -are some formatting and style conventions that are used. - -Section formatting -^^^^^^^^^^^^^^^^^^ - -Use `sentence case `__ -``Upper lower`` for section titles, e.g., ``Possible hangups`` rather than -``Possible Hangups``. - -We aim to follow the recommendations from the -`Python documentation `_ -and the `Sphinx reStructuredText documentation `_ -for section markup characters, i.e.: - -- ``#`` with overline, for parts. This is reserved for the main title in - ``index.rst``. All other pages should start with "chapter" or lower. -- ``*`` with overline, for chapters -- ``=``, for sections -- ``-``, for subsections -- ``^``, for subsubsections -- ``"``, for paragraphs - -This may not yet be applied consistently in existing docs. - -Table formatting -^^^^^^^^^^^^^^^^ -Given the size of the table and length of each entry, use: - -+-------------+-------------------------------+--------------------+ -| | small table | large table | -+-------------+-------------------------------+--------------------+ -| short entry | `simple or grid table`_ | `grid table`_ | -+-------------+-------------------------------+--------------------+ -| long entry | `list table`_ | `csv table`_ | -+-------------+-------------------------------+--------------------+ - -For more information, see `rst tables `_. - -.. _`simple or grid table`: https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#tables -.. _`grid table`: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#grid-tables -.. _`list table`: https://docutils.sourceforge.io/docs/ref/rst/directives.html#list-table -.. _`csv table`: https://docutils.sourceforge.io/docs/ref/rst/directives.html#csv-table-1 - -Function arguments -^^^^^^^^^^^^^^^^^^ - -Function arguments and keywords within docstrings should be referred to using -the ``*emphasis*`` role. This will keep Matplotlib's documentation consistent -with Python's documentation: - -.. code-block:: rst - - Here is a description of *argument* - -Do not use the ```default role```: - -.. code-block:: rst - - Do not describe `argument` like this. As per the next section, - this syntax will (unsuccessfully) attempt to resolve the argument as a - link to a class or method in the library. - -nor the ````literal```` role: - -.. code-block:: rst - - Do not describe ``argument`` like this. - - -Mathematical expressions ------------------------- -Use sphinx's built in math support: - -- **Inline math:** Use the ``:math:`` - `role `__ -- **Math blocks:** Use the ``.. math::`` - `directive `__ - -In rare cases we want the rendering of the mathematical text in the -documentation html to exactly match with the rendering of the mathematical -expression in the Matplotlib figure. In these cases, you can use the -`matplotlib.sphinxext.mathmpl` Sphinx extension (See also the -:doc:`../users/explain/text/mathtext` tutorial.) - +See the :doc:`style guide ` for the ReST conventions used in the Matplotlib documentation. .. _internal-section-refs: @@ -318,7 +228,7 @@ before the section Summary for pull request authors ================================ -and then link to with ``:ref:`label-name``` +and then link to it with ``:ref:`label-name``` .. code-block:: rst @@ -396,8 +306,8 @@ commands:: Include figures and files ------------------------- -Image files can directly included in pages with the ``image::`` directive. -e.g., :file:`tutorials/intermediate/constrainedlayout_guide.py` displays +Image files can directly be included in pages with the ``image::`` directive. +e.g., :file:`galleries/users_explain/axes/constrainedlayout_guide.py` displays a couple of static images:: # .. image:: /_static/constrained_layout_1b.png @@ -566,7 +476,6 @@ Do not use the ```default role``` or the ````literal```` role: Neither `argument` nor ``argument`` should be used. - Quotes for strings ^^^^^^^^^^^^^^^^^^ @@ -979,7 +888,6 @@ these ``*.rst`` files from the source location to the build location (see In the Python files, to exclude an example from having a plot generated, insert "sgskip" somewhere in the filename. - The format of these files is relatively straightforward. Properly formatted comment blocks are treated as ReST_ text, the code is displayed, and figures are put into the built page. Matplotlib uses the diff --git a/doc/devel/index.rst b/doc/devel/index.rst index fdeb08d3b202..e5ff8ebb40c7 100644 --- a/doc/devel/index.rst +++ b/doc/devel/index.rst @@ -41,6 +41,7 @@ context that may be necessary for resolving the issue: .. grid-item-card:: :class-header: sd-fs-5 + :class-body: sd-d-flex-column :octicon:`bug;1em;sd-text-info` **Submit a bug report** ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -48,13 +49,14 @@ context that may be necessary for resolving the issue: Thank you for your help in keeping bug reports targeted and descriptive. .. button-link:: https://github.com/matplotlib/matplotlib/issues/new/choose - :expand: - :color: primary + :expand: + :color: primary - Report a bug + Report a bug .. grid-item-card:: :class-header: sd-fs-5 + :class-body: sd-d-flex-column :octicon:`light-bulb;1em;sd-text-info` **Request a new feature** ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -158,9 +160,9 @@ and managing a development environment and workflow: .. grid-item-card:: :shadow: none - **Install** + **Build and install from source** ^^^ - .. rst-class:: section-toc + .. rst-class:: section-toc no-caption-toc .. toctree:: :maxdepth: 4 @@ -170,7 +172,7 @@ and managing a development environment and workflow: .. grid-item-card:: :shadow: none - **Workflow** + **Development workflow** ^^^^ .. toctree:: @@ -209,8 +211,10 @@ manage, or release manage, these guidelines describe how our current process wor **Code** ^^^ + .. rst-class:: no-caption-toc .. toctree:: :maxdepth: 1 + :caption: Code coding_guide api_changes @@ -222,8 +226,10 @@ manage, or release manage, these guidelines describe how our current process wor **Documentation** ^^^ + .. rst-class:: no-caption-toc .. toctree:: :maxdepth: 1 + :caption: Documentation document style_guide @@ -235,8 +241,10 @@ manage, or release manage, these guidelines describe how our current process wor **Triage And Review** ^^^ + .. rst-class:: no-caption-toc .. toctree:: :maxdepth: 1 + :caption: Triage and Review triage pr_guide @@ -247,8 +255,10 @@ manage, or release manage, these guidelines describe how our current process wor **Maintenance** ^^^ + .. rst-class:: no-caption-toc .. toctree:: :maxdepth: 1 + :caption: Maintenance release_guide communication_guide diff --git a/doc/devel/min_dep_policy.rst b/doc/devel/min_dep_policy.rst index f0dc0438c8e4..d34c84131ddc 100644 --- a/doc/devel/min_dep_policy.rst +++ b/doc/devel/min_dep_policy.rst @@ -66,7 +66,7 @@ Test and documentation dependencies As these packages are only needed for testing or building the docs and not needed by end-users, we can be more aggressive about dropping support for old versions. However, we need to be careful to not -over-run what down-stream packagers support (as most of the run the +over-run what down-stream packagers support (as most of them run the tests and build the documentation as part of the packaging process). We will support at least minor versions of the development dependencies @@ -167,7 +167,7 @@ To update the minimum versions of Python we need to update: - ``environment.yml`` - ``doc/install/dependencies.rst`` - ``doc/devel/min_dep_policy.rst`` (this file) -- CI configuration files (circle, GHA, azure) +- CI configuration files (circle, GHA) - ``tox.ini`` To update the minimum NumPy we need to update: diff --git a/doc/devel/pr_guide.rst b/doc/devel/pr_guide.rst index b0f36f2e78b0..14aeefb9ef5b 100644 --- a/doc/devel/pr_guide.rst +++ b/doc/devel/pr_guide.rst @@ -249,7 +249,7 @@ Some explicit rules following from this: Ensure that all API changes are documented in a file in one of the subdirectories of :file:`doc/api/next_api_changes`, and significant new - features have an entry in :file:`doc/user/whats_new`. + features have an entry in :file:`doc/release/next_whats_new`. - If a PR already has a positive review, a core developer (e.g. the first reviewer, but not necessarily) may champion that PR for merging. In order @@ -360,7 +360,7 @@ Automated backports ------------------- We use MeeseeksDev bot to automatically backport merges to the correct -maintenance branch base on the milestone. To work properly the +maintenance branch based on the milestone. To work properly the milestone must be set before merging. If you have commit rights, the bot can also be manually triggered after a merge by leaving a message ``@meeseeksdev backport to BRANCH`` on the PR. If there are conflicts diff --git a/doc/devel/style_guide.rst b/doc/devel/style_guide.rst index b260872557c5..99d86f82b112 100644 --- a/doc/devel/style_guide.rst +++ b/doc/devel/style_guide.rst @@ -178,7 +178,23 @@ reliability and consistency in documentation. They are not interchangeable. Headings -------- -Use sentence case for headings. +We aim to follow the recommendations from the +`Python documentation `_ +and the `Sphinx reStructuredText documentation `_ +for section markup characters, i.e.: + +- ``#`` with overline, for parts. This is reserved for the main title in + ``index.rst``. All other pages should start with "chapter" or lower. +- ``*`` with overline, for chapters +- ``=``, for sections +- ``-``, for subsections +- ``^``, for subsubsections +- ``"``, for paragraphs + +This may not yet be applied consistently in existing docs. + +Use `sentence case `__ +``Upper lower`` for section titles. .. table:: :width: 100% @@ -316,17 +332,12 @@ subordinating conjunctive phrases. Formatting ========== -The following guidelines specify how to incorporate code and use appropriate +It is useful to strive for consistency in the Matplotlib documentation. The +following guidelines specify how to incorporate code and use appropriate formatting for Matplotlib documentation. -Code ----- - -Matplotlib is a Python library and follows the same standards for -documentation. - -Comments -^^^^^^^^ +Code examples +------------- Examples of Python code have comments before or on the same line. .. table:: @@ -347,7 +358,7 @@ Examples of Python code have comments before or on the same line. +---------------------------------------+---------------------------------+ Outputs -^^^^^^^ +------- When generating visuals with Matplotlib using ``.py`` files in examples, display the visual with `matplotlib.pyplot.show` to display the visual. Keep the documentation clear of Python output lines. @@ -371,6 +382,20 @@ Keep the documentation clear of Python output lines. | fig.show() | | +------------------------------------+------------------------------------+ +Mathematical expressions +------------------------ +Use Sphinx's built in math support: + +- **Inline math:** Use the ``:math:`` + `role `__ +- **Math blocks:** Use the ``.. math::`` + `directive `__ + +In rare cases we want the rendering of the mathematical text in the +documentation html to exactly match with the rendering of the mathematical +expression in the Matplotlib figure. In these cases, you can use the +`matplotlib.sphinxext.mathmpl` Sphinx extension. Usage is described in :doc:`../users/explain/text/mathtext`. + reStructuredText ---------------- @@ -412,41 +437,22 @@ exclusively for performing actions in a determined order. Tables ^^^^^^ -Use ASCII tables with reStructuredText standards in organizing content. -Markdown tables and the csv-table directive are not accepted. - -.. table:: - :width: 100% - :widths: 50, 50 - - +--------------------------------+----------------------------------------+ - | Correct | Incorrect | - +================================+========================================+ - | +----------+----------+ | :: | - | | Correct | Incorrect| | | - | +==========+==========+ | | Correct | Incorrect | | - | | OK | Not OK | | | ------- | --------- | | - | +----------+----------+ | | OK | Not OK | | - | | | - +--------------------------------+----------------------------------------+ - | :: | :: | - | | | - | +----------+----------+ | .. csv-table:: | - | | Correct | Incorrect| | :header: "correct", "incorrect" | - | +==========+==========+ | :widths: 10, 10 | - | | OK | Not OK | | | - | +----------+----------+ | "OK ", "Not OK" | - | | | - +--------------------------------+ | - | :: | | - | | | - | =========== =========== | | - | Correct Incorrect | | - | =========== =========== | | - | OK Not OK | | - | =========== =========== | | - | | | - +--------------------------------+----------------------------------------+ +Given the size of the table and length of each entry, use: + ++-------------+-------------------------------+--------------------+ +| | small table | large table | ++-------------+-------------------------------+--------------------+ +| short entry | `simple or grid table`_ | `grid table`_ | ++-------------+-------------------------------+--------------------+ +| long entry | `list table`_ | `csv table`_ | ++-------------+-------------------------------+--------------------+ + +For more information, see `rst tables `_. + +.. _`simple or grid table`: https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#tables +.. _`grid table`: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#grid-tables +.. _`list table`: https://docutils.sourceforge.io/docs/ref/rst/directives.html#list-table +.. _`csv table`: https://docutils.sourceforge.io/docs/ref/rst/directives.html#csv-table-1 Additional resources diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index 27594ffe7dd4..84969097fab9 100644 --- a/doc/devel/testing.rst +++ b/doc/devel/testing.rst @@ -213,7 +213,7 @@ tests it:: The first time this test is run, there will be no baseline image to compare against, so the test will fail. Copy the output images (in this case -:file:`result_images/test_lines/test_line_dashes.png`) to the correct +:file:`result_images/test_lines/line_dashes.png`) to the correct subdirectory of :file:`baseline_images` tree in the source directory (in this case :file:`lib/matplotlib/tests/baseline_images/test_lines`). Put this new file under source code revision control (with ``git add``). When rerunning @@ -289,7 +289,7 @@ CI with GitHub Actions "in the cloud". GitHub Actions is configured to receive notifications of new commits to GitHub -repos and to run builds or tests when it sees these new commits. It looks for a +repos and to run builds or tests when it sees these new commits. It looks for YAML files in ``.github/workflows`` to see how to test the project. GitHub Actions is already enabled for the `main Matplotlib GitHub repository @@ -384,7 +384,7 @@ To do so, either download the matching source distribution ``matplotlib-X.Y.Z.tar.gz`` from `PyPI `_ or alternatively, clone the git repository and ``git checkout vX.Y.Z``. Copy the folder :file:`lib/matplotlib/tests/baseline_images` to the folder -:file:`matplotlib/tests` of your the matplotlib installation to test. +:file:`matplotlib/tests` of the matplotlib installation to test. The correct target folder can be found using:: python -c "import matplotlib.tests; print(matplotlib.tests.__file__.rsplit('/', 1)[0])" diff --git a/doc/install/dependencies.rst b/doc/install/dependencies.rst index 68cd0e77d599..f59e7836e455 100644 --- a/doc/install/dependencies.rst +++ b/doc/install/dependencies.rst @@ -27,7 +27,7 @@ reference. * `fontTools `_ (>= 4.28.2) * `kiwisolver `_ (>= 1.3.1) * `NumPy `_ (>= 2.0) -* `packaging `_ (>= 20.0) +* `packaging `_ (>= 23.2) * `Pillow `_ (>= 9.0) * `pyparsing `_ (>= 3) @@ -91,7 +91,7 @@ Animations ^^^^^^^^^^ * ffmpeg_: for saving movies. -* `ImageMagick `_: for saving +* `ImageMagick `_: for saving animated gifs. Font handling and rendering @@ -110,7 +110,6 @@ C libraries Matplotlib brings its own copies of the following libraries: - ``Agg``: the Anti-Grain Geometry C++ rendering engine -- ``ttconv``: a TrueType font utility Additionally, Matplotlib depends on: @@ -237,13 +236,13 @@ when :ref:`installing Matplotlib for development `, which means that the dependencies must be explicitly installed, either by :ref:`creating a virtual environment ` (recommended) or by manually installing the following packages: -- `meson-python `_ (>= 0.13.1). -- `PyBind11 `_ (>= 2.13.2). Used to connect C/C++ code +- `meson-python `_ (>= 0.18.0). +- `PyBind11 `_ (>= 3.0.0). Used to connect C/C++ code with Python. - `setuptools_scm `_ (>= 7). Used to update the reported ``mpl.__version__`` based on the current git commit. Also a runtime dependency for editable installs. -- NumPy_ (>= 1.22). Also a runtime dependency. +- NumPy_ (>= 2.0). Also a runtime dependency. .. _compile-build-dependencies: diff --git a/doc/install/environment_variables_faq.rst b/doc/install/environment_variables_faq.rst index 033350f6e5e8..aedcabb1efd4 100644 --- a/doc/install/environment_variables_faq.rst +++ b/doc/install/environment_variables_faq.rst @@ -23,12 +23,17 @@ Environment variables This is the directory used to store user customizations to Matplotlib, as well as some caches to improve performance. If :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib` - and :file:`{HOME}/.cache/matplotlib` are used on Linux, and + and :file:`{HOME}/.cache/matplotlib` are used on Linux and FreeBSD, + :file:`%LOCALAPPDATA%\\matplotlib` on Windows, and :file:`{HOME}/.matplotlib` on other platforms, if they are writable. Otherwise, the Python standard library's `tempfile.gettempdir` is used to find a base directory in which the :file:`matplotlib` subdirectory is created. + Note: Prior to Matplotlib 3.11, the config directory on Windows was + :file:`%USERPROFILE%\\.matplotlib`. For backward compatibility, newer + versions will continue to use this directory if it exists. + .. envvar:: MPL_IGNORE_SYSTEM_FONTS When this variable is set, Matplotlib will update its font cache only with its own diff --git a/doc/install/index.rst b/doc/install/index.rst index 4e8792dd5d32..8678af8252a5 100644 --- a/doc/install/index.rst +++ b/doc/install/index.rst @@ -71,8 +71,6 @@ Python distributions Matplotlib is part of major Python distributions: - Anaconda_ -- `ActiveState ActivePython - `_ - `WinPython `_ Linux package manager @@ -248,7 +246,7 @@ the form of wheels. pip is installed by default with python.org and Homebrew Python, but needs to be manually installed on Macports with :: - sudo port install py38-pip + sudo port install py314-pip Once pip is installed, you can install Matplotlib and all its dependencies with from the Terminal.app command line:: diff --git a/doc/install/troubleshooting_faq.inc.rst b/doc/install/troubleshooting_faq.inc.rst index fce94cef6a66..e74a691ee023 100644 --- a/doc/install/troubleshooting_faq.inc.rst +++ b/doc/install/troubleshooting_faq.inc.rst @@ -43,10 +43,10 @@ locate your :file:`matplotlib/` configuration directory, use >>> mpl.get_configdir() '/home/darren/.config/matplotlib' -On Unix-like systems, this directory is generally located in your +On Linux and FreeBSD, this directory is generally located in your :envvar:`HOME` directory under the :file:`.config/` directory. -In addition, users have a cache directory. On Unix-like systems, this is +In addition, users have a cache directory. On Linux and FreeBSD, this is separate from the configuration directory by default. To locate your :file:`.cache/` directory, use :func:`matplotlib.get_cachedir`: @@ -54,15 +54,19 @@ separate from the configuration directory by default. To locate your >>> mpl.get_cachedir() '/home/darren/.cache/matplotlib' +On macOS, both the config directory and the cache directory are +:file:`{HOME}/.matplotlib` by default. + On Windows, both the config directory and the cache directory are -the same and are in your :file:`Documents and Settings` or :file:`Users` -directory by default: +:file:`%LOCALAPPDATA%\\matplotlib` by default. If +:file:`%USERPROFILE%\\.matplotlib` already exists (for example, from an +older Matplotlib version), that directory is used instead: >>> import matplotlib as mpl >>> mpl.get_configdir() -'C:\\Documents and Settings\\jdhunter\\.matplotlib' +'C:\\Users\\jdhunter\\AppData\\Local\\matplotlib' >>> mpl.get_cachedir() -'C:\\Documents and Settings\\jdhunter\\.matplotlib' +'C:\\Users\\jdhunter\\AppData\\Local\\matplotlib' If you would like to use a different configuration directory, you can do so by specifying the location in your :envvar:`MPLCONFIGDIR` diff --git a/doc/project/code_of_conduct.rst b/doc/project/code_of_conduct.rst index 56fee2f25f6f..c2b3149ca07a 100644 --- a/doc/project/code_of_conduct.rst +++ b/doc/project/code_of_conduct.rst @@ -1,148 +1,52 @@ .. _code_of_conduct: .. redirect-from:: /users/project/code_of_conduct -==================================== -Contributor Covenant Code of Conduct -==================================== +======================== +NUMFOCUS CODE OF CONDUCT +======================== -Our Pledge -========== +You can find the whole document here +https://numfocus.org/code-of-conduct. -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. +THE SHORT VERSION +================= -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +NumFOCUS is dedicated to providing a harassment-free community for +everyone, regardless of gender, sexual orientation, gender identity and +expression, disability, physical appearance, body size, race, or +religion. We do not tolerate harassment of community members in any +form. -Our Standards -============= - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -Enforcement Responsibilities -============================ - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -Scope -===== - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -Enforcement -=========== - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -`matplotlib-coc@numfocus.org `_ which is -monitored by the `CoC subcommittee `_ or a -report can be made using the `NumFOCUS Code of Conduct report form `_. -If community leaders cannot come to a resolution about enforcement, -reports will be escalated to the NumFocus Code of Conduct committee -(conduct@numfocus.org). All complaints will be reviewed and investigated -promptly and fairly. +Be kind to others. Do not insult or put down others. Behave +professionally. Remember that harassment and sexist, racist, or +exclusionary jokes are not appropriate for NumFOCUS. -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. +All communication should be appropriate for a professional audience +including people of many different backgrounds. Sexual language and +imagery is not appropriate. -Enforcement Guidelines -====================== +Thank you for helping make this a welcoming, friendly community for all. -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: +LONG VERSION +============ -1. Correction -------------- +You can find the long version of the Code of Conduct on the NumFOCUS +website https://numfocus.org/code-of-conduct -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -2. Warning ----------- - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -3. Temporary Ban ----------------- - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -4. Permanent Ban ----------------- - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -Attribution -=========== +HOW TO REPORT +============= -This Code of Conduct is adapted from the `Contributor Covenant `_, -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. +If you feel that the Code of Conduct has been violated, feel free to +submit a report, by using the form: `NumFOCUS Code of Conduct Reporting +Form `__ -Community Impact Guidelines were inspired by `Mozilla's code of conduct -enforcement ladder `_. +WHO WILL RECEIVE YOUR REPORT +============================ +Your report will be received and handled by NumFOCUS Code of Conduct +Working Group; trained, and experienced contributors with diverse +backgrounds. The group is making decisions independently from the +project, PyData, NumFOCUS or any other organization. -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. +You can learn more about the current group members, as well as the +reporting procedure `HERE `__ diff --git a/doc/release/next_whats_new/animation_default.rst b/doc/release/next_whats_new/animation_default.rst new file mode 100644 index 000000000000..4c0821675eb0 --- /dev/null +++ b/doc/release/next_whats_new/animation_default.rst @@ -0,0 +1,7 @@ +Animations now default to video rich display in Jupyter notebooks +----------------------------------------------------------------- + +When rich display of an Animation object is requested (i.e., by placing the variable as +the last line in a notebook cell), it will now default to the best available video +output. That is, if FFmpeg is available, a video file will be output, otherwise a +JavaScript animation will be output. diff --git a/doc/release/next_whats_new/contourset_set_data.rst b/doc/release/next_whats_new/contourset_set_data.rst new file mode 100644 index 000000000000..1e5773f1b664 --- /dev/null +++ b/doc/release/next_whats_new/contourset_set_data.rst @@ -0,0 +1,12 @@ +A ``ContourSet`` can be updated with new data +--------------------------------------------- +`.ContourSet.set_data` recontours new data using the existing artist, instead of +requiring the ``ContourSet`` to be removed and recreated:: + + cs = ax.contour(X, Y, Z) + cs.set_data(X, Y, Z2) + +It works for `~.Axes.contour`, `~.Axes.contourf`, `~.Axes.tricontour` and +`~.Axes.tricontourf`. The contour levels are kept, so the colors, the colorbar +and the legend entries of the ``ContourSet`` remain valid. This is useful for +animations and other interactive updates. diff --git a/doc/release/next_whats_new/engformatter_locale.rst b/doc/release/next_whats_new/engformatter_locale.rst new file mode 100644 index 000000000000..69252c74bb2f --- /dev/null +++ b/doc/release/next_whats_new/engformatter_locale.rst @@ -0,0 +1,17 @@ +``EngFormatter`` now respects ``axes.formatter.use_locale`` +----------------------------------------------------------- + +`~matplotlib.ticker.EngFormatter` now formats the decimal separator according to +the current locale, like `~matplotlib.ticker.ScalarFormatter` already did. This +is controlled by the :rc:`axes.formatter.use_locale` rcParam, or by the new +*useLocale* keyword argument: + +.. code-block:: python + + import locale + from matplotlib.ticker import EngFormatter + + locale.setlocale(locale.LC_ALL, "de_DE.UTF-8") + + ax.yaxis.set_major_formatter(EngFormatter(places=2, useLocale=True)) + # tick labels now read "555,10 m" instead of "555.10 m" diff --git a/doc/release/next_whats_new/fig_anchored_offsetbox.rst b/doc/release/next_whats_new/fig_anchored_offsetbox.rst new file mode 100644 index 000000000000..244b253517ca --- /dev/null +++ b/doc/release/next_whats_new/fig_anchored_offsetbox.rst @@ -0,0 +1,32 @@ +``AnchoredOffsetbox`` and ``AnchoredText`` for ``Figure`` and ``SubFigure`` +--------------------------------------------------------------------------- + +The `.AnchoredOffsetbox` and `.AnchoredText` artists may now be directly added to a +`.Figure` or `.SubFigure` and by default will be anchored relative to their parent +``(Sub)Figure``. + + +.. plot:: + :include-source: true + :alt: The left half of the figure contains two text boxes with black outlines. One in the top left of the figure reads "Anchored to Figure". One at the bottom and to the left the vertical center line reads "Anchored to SubFigure". A third box containing a blue circle is halfway up and to the right of the vertical center line. + + import matplotlib.pyplot as plt + import matplotlib.patches as mpatches + from matplotlib.offsetbox import AnchoredText, AnchoredOffsetbox, DrawingArea + + fig = plt.figure() + + sfig1, sfig2 = fig.subfigures(ncols=2) + sfig1.set_facecolor("lemonchiffon") + sfig2.set_facecolor("lightcyan") + + fig_text = AnchoredText("Anchored to Figure", loc="upper left") + fig.add_artist(fig_text) + + sfig_text = AnchoredText("Anchored to SubFigure", loc="lower right") + sfig1.add_artist(sfig_text) + + area = DrawingArea(width=30, height=30) + area.add_artist(mpatches.Circle((15, 15), 15, fc="tab:blue")) + box = AnchoredOffsetbox(child=area, loc="center left") + sfig2.add_artist(box) diff --git a/doc/release/next_whats_new/pcolormesh_gouraud.rst b/doc/release/next_whats_new/pcolormesh_gouraud.rst new file mode 100644 index 000000000000..089e4a8bc639 --- /dev/null +++ b/doc/release/next_whats_new/pcolormesh_gouraud.rst @@ -0,0 +1,52 @@ +``gouraud`` shading supports data at quadrilaterals centers +----------------------------------------------------------- + +`~.Axes.pcolormesh` previously required data at the corners of +quadrilaterals for ``gouraud`` shading. It now also supports data +defined at the centers of quadrilaterals. + +This now allows `~.Axes.pcolormesh` to provide both constant and +linearly interpolated shading for each data location. + +=============== ======== ===================== +.. constant linearly interpolated +=============== ======== ===================== +data at corners nearest gouraud +data at centers flat gouraud +=============== ======== ===================== + +Shading can be switched for the same data location, allowing +switches between ``nearest`` and ``gouraud``, and now also +between ``flat`` and ``gouraud``. + +For example: + +.. plot:: + :include-source: true + :alt: Switching between constant and linearly interpolated shading for data at corners and centers. + + import matplotlib.pyplot as plt + import numpy as np + + nrows, ncols = 3, 5 + Z = np.arange(nrows * ncols).reshape(nrows, ncols) + x = np.arange(ncols + 1) + y = np.arange(nrows + 1) + + fig, axs = plt.subplots(2, 2, layout='constrained') + + # Data at corners, requires X and Y the same shape as Z. + axs[0, 0].pcolormesh(x[:-1], y[:-1], Z, shading='nearest') + axs[0, 0].set_title('nearest: X, Y, Z same shape') + + axs[0, 1].pcolormesh(x[:-1], y[:-1], Z, shading='gouraud') + axs[0, 1].set_title('gouraud: X, Y, Z same shape') + + # Data at centers, requires X and Y one larger than Z. + axs[1, 0].pcolormesh(x, y, Z, shading='flat') + axs[1, 0].set_title('flat: X, Y one larger than Z') + + axs[1, 1].pcolormesh(x, y, Z, shading='gouraud') + axs[1, 1].set_title('gouraud: X, Y one larger than Z') + + plt.show() diff --git a/doc/sphinxext/rcparams.py b/doc/sphinxext/rcparams.py index f2f56de3b39a..17535b801675 100644 --- a/doc/sphinxext/rcparams.py +++ b/doc/sphinxext/rcparams.py @@ -1,3 +1,4 @@ +import textwrap import typing from docutils.parsers.rst import Directive @@ -52,7 +53,8 @@ def run(self): f'.. _rcparam_{elem.name.replace(".", "_")}:', '', f'{elem.name} : {typestr} = ``{elem.default!r}``', - f' {elem.description if elem.description else "*no description*"}' + *textwrap.indent( + elem.description or '*no description*', ' ').splitlines(), '', ] self.state_machine.insert_input(lines, 'rcParams table') diff --git a/environment.yml b/environment.yml index 4f53b19072ee..208c38d5d42f 100644 --- a/environment.yml +++ b/environment.yml @@ -1,6 +1,6 @@ # To set up a development environment using conda run: # -# conda env create -f environment.yml +# conda create -f environment.yml # conda activate mpl-dev # pip install --verbose --no-build-isolation --group dev --editable . # @@ -19,7 +19,7 @@ dependencies: - importlib-resources>=3.2.0 - kiwisolver>=1.3.1 - pybind11>=2.13.2 - - meson-python>=0.13.1 + - meson-python>=0.18.0 - numpy>=2.0 - pillow>=9 - pkg-config @@ -47,11 +47,9 @@ dependencies: - sphinx-tags>=0.4.0 - pystemmer - pikepdf - - pip - - pip: - - mpl-sphinx-theme~=3.11.0 - - sphinxcontrib-svg2pdfconverter>=1.1.0 - - sphinxcontrib-video>=0.2.1 + - sphinxcontrib-svg2pdfconverter>=1.1.0 + - sphinxcontrib-video>=0.2.1 + - mpl-sphinx-theme~=3.11.0 # testing - black<26 - coverage @@ -72,3 +70,4 @@ dependencies: - pytz - ruff - tox + - pip diff --git a/extern/agg24-svn/include/agg_color_rgba.h b/extern/agg24-svn/include/agg_color_rgba.h index 9905a8f69429..f944990d5390 100644 --- a/extern/agg24-svn/include/agg_color_rgba.h +++ b/extern/agg24-svn/include/agg_color_rgba.h @@ -24,6 +24,11 @@ #ifndef AGG_COLOR_RGBA_INCLUDED #define AGG_COLOR_RGBA_INCLUDED +#ifdef MPL_ADD_AGG_HSL_BLEND_MODES +#include +#include +#endif + #include #include "agg_basics.h" #include "agg_gamma_lut.h" diff --git a/galleries/examples/animation/simple_anim.py b/galleries/examples/animation/simple_anim.py index 2b65b5935b40..d253bf8e1c58 100644 --- a/galleries/examples/animation/simple_anim.py +++ b/galleries/examples/animation/simple_anim.py @@ -37,6 +37,35 @@ def animate(i): plt.show() +# %% +# Contours are updated the same way, with `.ContourSet.set_data`. Recontouring +# the existing artist is faster than removing the ``ContourSet`` and making a +# new one, and it keeps the contours in the same place in the draw order, which +# matters when blitting. The levels are not recomputed, so the colors mean +# the same thing in every frame. + +fig, ax = plt.subplots() + +X, Y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100)) + + +def f(t): + return np.sin(X + t) * np.cos(Y - t) + + +cs = ax.contour(X, Y, f(0), levels=np.linspace(-0.9, 0.9, 7)) + + +def animate_contour(i): + cs.set_data(X, Y, f(i / 25)) # update the data. + return cs, + + +ani_contour = animation.FuncAnimation( + fig, animate_contour, interval=20, blit=True, save_count=50) + +plt.show() + # %% # # .. tags:: diff --git a/galleries/examples/images_contours_and_fields/colormap_normalizations.py b/galleries/examples/images_contours_and_fields/colormap_normalizations.py deleted file mode 100644 index 1d81336b4964..000000000000 --- a/galleries/examples/images_contours_and_fields/colormap_normalizations.py +++ /dev/null @@ -1,153 +0,0 @@ -""" -======================= -Colormap normalizations -======================= - -Demonstration of using norm to map colormaps onto data in non-linear ways. - -.. redirect-from:: /gallery/userdemo/colormap_normalizations -""" - -import matplotlib.pyplot as plt -import numpy as np - -import matplotlib.colors as colors - -N = 100 - -# %% -# LogNorm -# ------- -# This example data has a low hump with a spike coming out of its center. If plotted -# using a linear colour scale, then only the spike will be visible. To see both hump and -# spike, this requires the z/colour axis on a log scale. -# -# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be -# made logarithmic using a `.LogNorm`. - -X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = np.exp(-X**2 - Y**2) -Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) -Z = Z1 + 50 * Z2 - -fig, ax = plt.subplots(2, 1) - -pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest') -fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling') - -pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest', - norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max())) -fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm') - -# %% -# PowerNorm -# --------- -# This example data mixes a power-law trend in X with a rectified sine wave in Y. If -# plotted using a linear colour scale, then the power-law trend in X partially obscures -# the sine wave in Y. -# -# The power law can be removed using a `.PowerNorm`. - -X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] -Z = (1 + np.sin(Y * 10)) * X**2 - -fig, ax = plt.subplots(2, 1) - -pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest') -fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling') - -pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest', - norm=colors.PowerNorm(gamma=0.5)) -fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm') - -# %% -# SymLogNorm -# ---------- -# This example data has two humps, one negative and one positive, The positive hump has -# 5 times the amplitude of the negative. If plotted with a linear colour scale, then -# the detail in the negative hump is obscured. -# -# Here we logarithmically scale the positive and negative data separately with -# `.SymLogNorm`. -# -# Note that colorbar labels do not come out looking very good. - -X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = np.exp(-X**2 - Y**2) -Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) -Z = (5 * Z1 - Z2) * 2 - -fig, ax = plt.subplots(2, 1) - -pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - vmin=-np.max(Z)) -fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling') - -pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - norm=colors.SymLogNorm(linthresh=0.015, - vmin=-10.0, vmax=10.0, base=10)) -fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm') - -# %% -# Custom Norm -# ----------- -# Alternatively, the above example data can be scaled with a customized normalization. -# This one normalizes the negative data differently from the positive. - - -# Example of making your own norm. Also see matplotlib.colors. -# From Joe Kington: This one gives two different linear ramps: -class MidpointNormalize(colors.Normalize): - def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): - self.midpoint = midpoint - super().__init__(vmin, vmax, clip) - - def __call__(self, value, clip=None): - # I'm ignoring masked values and all kinds of edge cases to make a - # simple example... - x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] - return np.ma.masked_array(np.interp(value, x, y)) - - -# %% -fig, ax = plt.subplots(2, 1) - -pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - vmin=-np.max(Z)) -fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling') - -pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - norm=MidpointNormalize(midpoint=0)) -fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm') - -# %% -# BoundaryNorm -# ------------ -# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by -# providing the boundaries for colors, this norm puts the first color in between the -# first pair, the second color between the second pair, etc. - -fig, ax = plt.subplots(3, 1, layout='constrained') - -pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - vmin=-np.max(Z)) -fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical', - label='linear scaling') - -# Evenly-spaced bounds gives a contour-like effect. -bounds = np.linspace(-2, 2, 11) -norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - norm=norm) -fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical', - label='BoundaryNorm\nlinspace(-2, 2, 11)') - -# Unevenly-spaced bounds changes the colormapping. -bounds = np.array([-1, -0.5, 0, 2.5, 5]) -norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest', - norm=norm) -fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical', - label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]') - -plt.show() diff --git a/galleries/examples/images_contours_and_fields/gallery_order.txt b/galleries/examples/images_contours_and_fields/gallery_order.txt index 371e8c1624bf..5e222444a8bf 100644 --- a/galleries/examples/images_contours_and_fields/gallery_order.txt +++ b/galleries/examples/images_contours_and_fields/gallery_order.txt @@ -54,7 +54,6 @@ plot_streamplot # colormapping colormap_interactive_adjustment -colormap_normalizations colormap_normalizations_symlognorm image_annotated_heatmap diff --git a/galleries/examples/images_contours_and_fields/image_transparency_blend.py b/galleries/examples/images_contours_and_fields/image_transparency_blend.py index 31d1d50f757c..b658080e2f13 100644 --- a/galleries/examples/images_contours_and_fields/image_transparency_blend.py +++ b/galleries/examples/images_contours_and_fields/image_transparency_blend.py @@ -16,6 +16,7 @@ """ import matplotlib.pyplot as plt + # sphinx_gallery_thumbnail_number = 3 import numpy as np diff --git a/galleries/examples/images_contours_and_fields/pcolormesh_grids.py b/galleries/examples/images_contours_and_fields/pcolormesh_grids.py index 212b807dbf90..ce35eba61f02 100644 --- a/galleries/examples/images_contours_and_fields/pcolormesh_grids.py +++ b/galleries/examples/images_contours_and_fields/pcolormesh_grids.py @@ -108,7 +108,8 @@ def _annotate(ax, x, y, title): # # `Gouraud shading `_ can also # be specified, where the color in the quadrilaterals is linearly interpolated -# between the grid points. The shapes of *X*, *Y*, *Z* must be the same. +# between the grid points. The data is specified at the corners of the +# quadrilaterals, in which case *X*, *Y* and *Z* are all the same shape. fig, ax = plt.subplots(layout='constrained') x = np.arange(ncols) @@ -116,6 +117,21 @@ def _annotate(ax, x, y, title): ax.pcolormesh(x, y, Z, shading='gouraud', vmin=Z.min(), vmax=Z.max()) _annotate(ax, x, y, "shading='gouraud'; X, Y same shape as Z") +# %% +# Gouraud Shading, one larger grid +# -------------------------------- +# +# In some cases, the user has data defined at the centers of the quadrilaterals +# with *X* and *Y* one larger than *Z*. ``shading='gouraud'`` also supports +# this by using the grid quadrilateral centers as the corners of each colored +# quadrilateral. This contracts the pseudocolor plot by half a grid cell. + +fig, ax = plt.subplots(layout='constrained') +x = np.arange(ncols + 1) +y = np.arange(nrows + 1) +ax.pcolormesh(x, y, Z, shading='gouraud', vmin=Z.min(), vmax=Z.max()) +_annotate(ax, x, y, "shading='gouraud'; X, Y one larger than Z") + plt.show() # %% # diff --git a/galleries/examples/lines_bars_and_markers/gallery_order.txt b/galleries/examples/lines_bars_and_markers/gallery_order.txt index b2f1e1a0c214..c9a710b8d7b0 100644 --- a/galleries/examples/lines_bars_and_markers/gallery_order.txt +++ b/galleries/examples/lines_bars_and_markers/gallery_order.txt @@ -22,6 +22,7 @@ gradient_bar barh horizontal_barchart_distribution broken_barh +pareto_chart # scatter scatter_demo2 diff --git a/galleries/examples/lines_bars_and_markers/pareto_chart.py b/galleries/examples/lines_bars_and_markers/pareto_chart.py new file mode 100644 index 000000000000..b02aa516f784 --- /dev/null +++ b/galleries/examples/lines_bars_and_markers/pareto_chart.py @@ -0,0 +1,87 @@ +""" +============ +Pareto chart +============ + +A Pareto chart combines a bar chart of counts, sorted in descending order, +with a line showing the cumulative percentage. It is used to identify the +few categories that account for most of the total (the "vital few"). + +The cumulative line is drawn against the same y-axis as the bars, so the left +axis runs from 0 to the total count. A secondary y-axis created with +`.Axes.secondary_yaxis` relabels the same scale as a percentage, keeping both +axes aligned, and a dashed reference line at 80% marks the usual Pareto +threshold. +""" + +import matplotlib.pyplot as plt +import numpy as np + +from matplotlib.ticker import PercentFormatter + +# Mock data: number of defects found per category. +categories = ["Scratches", "Dents", "Misalignment", "Wrong color", + "Missing parts", "Cracks", "Other"] +counts = np.array([58, 42, 17, 9, 6, 4, 3]) + + +def pareto_chart(categories, counts): + """ + Parameters + ---------- + categories : list of str + The category labels. + counts : array-like + The number of occurrences of each category. + + Returns + ------- + fig, ax : `.Figure`, `~matplotlib.axes.Axes` + """ + # Sort in descending order. + order = np.argsort(counts)[::-1] + categories = [categories[i] for i in order] + counts = np.asarray(counts)[order] + total = counts.sum() + + fig, ax = plt.subplots(layout='constrained') + + ax.bar(categories, counts) + ax.tick_params(axis='x', rotation=30, labelrotation_mode='xtick') + ax.set_ylabel('Number of defects') + ax.set_title('Pareto chart of defects') + + ax.plot(categories, np.cumsum(counts), color='tab:red', marker='o') + ax.axhline(0.8 * total, color='tab:gray', linestyle='--', linewidth=1) + ax.set_ylim(0, total * 1.05) # headroom so the 100% marker is not clipped + + # Secondary axis that maps counts to a percentage of the total (and back). + secax = ax.secondary_yaxis('right', functions=(lambda c: c / total * 100, + lambda p: p / 100 * total)) + secax.yaxis.set_major_formatter(PercentFormatter()) + secax.set_ylabel('Cumulative percentage') + + return fig, ax + + +pareto_chart(categories, counts) +plt.show() + +# %% +# +# .. admonition:: References +# +# The use of the following functions, methods, classes and modules is shown +# in this example: +# +# - `matplotlib.axes.Axes.bar` / `matplotlib.pyplot.bar` +# - `matplotlib.axes.Axes.secondary_yaxis` +# - `matplotlib.axes.Axes.tick_params` / `matplotlib.pyplot.tick_params` +# - `matplotlib.ticker.PercentFormatter` +# +# .. tags:: +# +# component: axes +# plot-type: bar +# plot-type: line +# level: beginner diff --git a/galleries/examples/misc/anchored_artists.py b/galleries/examples/misc/anchored_artists.py index be600449bba6..bb3197fe37da 100644 --- a/galleries/examples/misc/anchored_artists.py +++ b/galleries/examples/misc/anchored_artists.py @@ -17,17 +17,22 @@ from matplotlib import pyplot as plt from matplotlib.lines import Line2D -from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox, DrawingArea, - TextArea, VPacker) +from matplotlib.offsetbox import ( + AnchoredOffsetbox, + AuxTransformBox, + DrawingArea, + TextArea, + VPacker, +) from matplotlib.patches import Circle, Ellipse -def draw_text(ax): +def draw_text(fig): """Draw a text-box anchored to the upper-left corner of the figure.""" box = AnchoredOffsetbox(child=TextArea("Figure 1a"), loc="upper left", frameon=True) box.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") - ax.add_artist(box) + fig.add_artist(box) def draw_circles(ax): @@ -68,7 +73,7 @@ def draw_sizebar(ax): fig, ax = plt.subplots() ax.set_aspect(1) -draw_text(ax) +draw_text(fig) draw_circles(ax) draw_ellipse(ax) draw_sizebar(ax) diff --git a/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py b/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py index 93c7662576e1..48d49b26bb64 100644 --- a/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py +++ b/galleries/examples/subplots_axes_and_figures/axes_zoom_effect.py @@ -8,8 +8,11 @@ import matplotlib.pyplot as plt from matplotlib.transforms import Bbox, TransformedBbox, blended_transform_factory -from mpl_toolkits.axes_grid1.inset_locator import (BboxConnector, BboxConnectorPatch, - BboxPatch) +from mpl_toolkits.axes_grid1.inset_locator import ( + BboxConnector, + BboxConnectorPatch, + BboxPatch, +) def connect_bbox(bbox1, bbox2, diff --git a/galleries/examples/ticks/date_formatters_locators.py b/galleries/examples/ticks/date_formatters_locators.py index bc5f1994cd74..eb485f73e670 100644 --- a/galleries/examples/ticks/date_formatters_locators.py +++ b/galleries/examples/ticks/date_formatters_locators.py @@ -13,11 +13,30 @@ import numpy as np # While these appear unused directly, they are used from eval'd strings. -from matplotlib.dates import (FR, MO, MONTHLY, SA, SU, TH, TU, WE, AutoDateFormatter, - AutoDateLocator, ConciseDateFormatter, DateFormatter, - DayLocator, HourLocator, MicrosecondLocator, - MinuteLocator, MonthLocator, RRuleLocator, SecondLocator, - WeekdayLocator, YearLocator, rrulewrapper) +from matplotlib.dates import ( + FR, + MO, + MONTHLY, + SA, + SU, + TH, + TU, + WE, + AutoDateFormatter, + AutoDateLocator, + ConciseDateFormatter, + DateFormatter, + DayLocator, + HourLocator, + MicrosecondLocator, + MinuteLocator, + MonthLocator, + RRuleLocator, + SecondLocator, + WeekdayLocator, + YearLocator, + rrulewrapper, +) import matplotlib.ticker as ticker diff --git a/galleries/examples/user_interfaces/GALLERY_HEADER.rst b/galleries/examples/user_interfaces/GALLERY_HEADER.rst index 75b469da7cf6..defbcc8a6fea 100644 --- a/galleries/examples/user_interfaces/GALLERY_HEADER.rst +++ b/galleries/examples/user_interfaces/GALLERY_HEADER.rst @@ -7,7 +7,9 @@ You can embed Matplotlib directly into a user interface application by following the embedding_in_SOMEGUI.py examples here. Currently Matplotlib supports PyQt/PySide, PyGObject, Tkinter, and wxPython. -When embedding Matplotlib in a GUI, you must use the Matplotlib API -directly rather than the pylab/pyplot procedural interface, so take a -look at the examples/api directory for some example code working with -the API. +When embedding Matplotlib in a GUI, use standalone `.Figure` objects only. +Do not use pyplot, because you do not want to depend on its globally managed +state and its event loop control. In particular, use ``fig = Figure()`` rather +than ``plt.figure()``, and ``fig = Figure(); axs = fig.subplots()`` rather than +``fig, axs = plt.subplots()``. The examples below show how to connect these +figures to the supported GUI toolkits. diff --git a/galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py b/galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py index 634d8c511aa7..584a2c712517 100644 --- a/galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py +++ b/galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py @@ -13,8 +13,9 @@ import numpy as np from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas -from matplotlib.backends.backend_wxagg import \ - NavigationToolbar2WxAgg as NavigationToolbar +from matplotlib.backends.backend_wxagg import ( + NavigationToolbar2WxAgg as NavigationToolbar, +) from matplotlib.figure import Figure diff --git a/galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py b/galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py index 4917180582fe..2a61743fa70e 100644 --- a/galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py +++ b/galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py @@ -27,8 +27,9 @@ import numpy as np from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas -from matplotlib.backends.backend_wxagg import \ - NavigationToolbar2WxAgg as NavigationToolbar +from matplotlib.backends.backend_wxagg import ( + NavigationToolbar2WxAgg as NavigationToolbar, +) import matplotlib.cbook as cbook from matplotlib.figure import Figure diff --git a/galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py b/galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py index 062f1219adb5..fbcb9c59fd63 100644 --- a/galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py +++ b/galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py @@ -11,8 +11,9 @@ import numpy as np from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas -from matplotlib.backends.backend_wxagg import \ - NavigationToolbar2WxAgg as NavigationToolbar +from matplotlib.backends.backend_wxagg import ( + NavigationToolbar2WxAgg as NavigationToolbar, +) from matplotlib.figure import Figure diff --git a/galleries/examples/user_interfaces/embedding_in_wx5_sgskip.py b/galleries/examples/user_interfaces/embedding_in_wx5_sgskip.py index f5442ec1f700..cff9aac6fe00 100644 --- a/galleries/examples/user_interfaces/embedding_in_wx5_sgskip.py +++ b/galleries/examples/user_interfaces/embedding_in_wx5_sgskip.py @@ -16,8 +16,9 @@ import wx.lib.agw.aui as aui from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas -from matplotlib.backends.backend_wxagg import \ - NavigationToolbar2WxAgg as NavigationToolbar +from matplotlib.backends.backend_wxagg import ( + NavigationToolbar2WxAgg as NavigationToolbar, +) from matplotlib.figure import Figure diff --git a/galleries/examples/user_interfaces/embedding_webagg_sgskip.py b/galleries/examples/user_interfaces/embedding_webagg_sgskip.py index 50e245f3db46..d55fc97f11c3 100644 --- a/galleries/examples/user_interfaces/embedding_webagg_sgskip.py +++ b/galleries/examples/user_interfaces/embedding_webagg_sgskip.py @@ -32,8 +32,10 @@ import numpy as np import matplotlib as mpl -from matplotlib.backends.backend_webagg import (FigureManagerWebAgg, - new_figure_manager_given_figure) +from matplotlib.backends.backend_webagg import ( + FigureManagerWebAgg, + new_figure_manager_given_figure, +) from matplotlib.figure import Figure diff --git a/galleries/examples/user_interfaces/mplcvd.py b/galleries/examples/user_interfaces/mplcvd.py index 99c115b8d251..8a9f4d02f234 100644 --- a/galleries/examples/user_interfaces/mplcvd.py +++ b/galleries/examples/user_interfaces/mplcvd.py @@ -10,8 +10,8 @@ import functools from pathlib import Path -from PIL import Image import colour +from PIL import Image import numpy as np diff --git a/galleries/tutorials/lifecycle.py b/galleries/tutorials/lifecycle.py index d932021726da..892073abd906 100644 --- a/galleries/tutorials/lifecycle.py +++ b/galleries/tutorials/lifecycle.py @@ -28,6 +28,7 @@ """ import matplotlib.pyplot as plt + # sphinx_gallery_thumbnail_number = 10 import numpy as np diff --git a/galleries/users_explain/animations/animations.py b/galleries/users_explain/animations/animations.py index 45c42f538fa6..444018676093 100644 --- a/galleries/users_explain/animations/animations.py +++ b/galleries/users_explain/animations/animations.py @@ -64,6 +64,9 @@ # - `.Animation.to_jshtml` to create HTML code with interactive JavaScript animation # controls # - `.Animation.save` to save the animation to a file +# - Place the animation as the last statement in a Jupyter Notebook cell; this will +# automatically render the animation as video and display it as the cell output, +# unless :rc:`animation.html` is set to ``'none'``. # # The following table shows a few plotting methods, the artists they return and some # commonly used ``set_*`` methods that update the underlying data. While updating data diff --git a/galleries/users_explain/axes/autoscale.py b/galleries/users_explain/axes/autoscale.py index 22cdd1f8dc96..f108480d5a09 100644 --- a/galleries/users_explain/axes/autoscale.py +++ b/galleries/users_explain/axes/autoscale.py @@ -299,6 +299,8 @@ # are not affected. Setting ``Axes.use_sticky_edges = False`` disables sticky # edge clamping on that Axes. # +# .. _autoscaling-limit-rounding: +# # Limit rounding # ~~~~~~~~~~~~~~ # diff --git a/galleries/users_explain/colors/colormapnorms.py b/galleries/users_explain/colors/colormapnorms.py index 66bff534b3b0..a1b8ff56eb6b 100644 --- a/galleries/users_explain/colors/colormapnorms.py +++ b/galleries/users_explain/colors/colormapnorms.py @@ -1,6 +1,8 @@ """ .. redirect-from:: /tutorials/colors/colormapnorms +.. redirect-from:: /gallery/images_contours_and_fields/colormap_normalizations +.. redirect-from:: /gallery/userdemo/colormap_normalizations .. _colormapnorms: @@ -19,7 +21,7 @@ Matplotlib does this mapping in two steps, with a normalization from the input data to [0, 1] occurring first, and then mapping onto the indices in the colormap. Normalizations are classes defined in the -:func:`matplotlib.colors` module. The default, linear normalization +:mod:`matplotlib.colors` module. The default, linear normalization is :func:`matplotlib.colors.Normalize`. Artists that map data to color pass the arguments *vmin* and *vmax* to @@ -339,9 +341,9 @@ def _inverse(x): # Custom normalization: Manually implement two linear ranges # ---------------------------------------------------------- # -# The `.TwoSlopeNorm` described above makes a useful example for -# defining your own norm. Note for the colorbar to work, you must -# define an inverse for your norm: +# `.TwoSlopeNorm` is already built into Matplotlib. The class below does the same +# thing by hand, to show how you can create your own norm. For the colorbar to +# work, you must also define an inverse for your norm: class MidpointNormalize(colors.Normalize): diff --git a/galleries/users_explain/toolkits/axisartist.rst b/galleries/users_explain/toolkits/axisartist.rst index 1b770c828ff6..35ed4a2eb3f4 100644 --- a/galleries/users_explain/toolkits/axisartist.rst +++ b/galleries/users_explain/toolkits/axisartist.rst @@ -566,16 +566,19 @@ way is to add it as an item of Axes's axis attribute.:: See the first example of this page. -Current limitations and TODO's +Current limitations and TODOs ============================== -The code need more refinement. Here is an incomplete list of issues and TODO's +The toolkit still requires further refinement. The following is an incomplete +list of known limitations and areas for future improvement. -* No easy way to support a user customized tick location (for - curvilinear grid). A new Locator class needs to be created. +* There is currently no straightforward way to support user-defined tick + locations for curvilinear grids. A new ``Locator`` class would be required. -* FloatingAxis may have coordinate limits, e.g., a floating axis of x = 0, - but y only spans from 0 to 1. +* ``FloatingAxis`` cannot currently define coordinate limits. For example, a + floating axis at ``x = 0`` cannot easily be restricted to span only + ``y = 0`` to ``1``. -* The location of axislabel of FloatingAxis needs to be optionally - given as a coordinate value. ex, a floating axis of x=0 with label at y=1 +* The location of a ``FloatingAxis`` axis label should optionally be + specifiable using a coordinate value, for example placing the label of + ``x = 0`` at ``y = 1``. diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index b7704e1f54c3..3975eec54699 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -253,8 +253,8 @@ def _check_versions(): ("cycler", "0.12.0"), ("dateutil", "2.7"), ("kiwisolver", "1.3.1"), - ("numpy", "1.25"), - ("pyparsing", "2.3.1"), + ("numpy", "2.0"), + ("pyparsing", "3.0"), ]: module = importlib.import_module(modname) if parse_version(module.__version__) < parse_version(minver): @@ -696,6 +696,12 @@ class RcParams(MutableMapping, dict): validate = rcsetup._validators + # Class-level backend state: shared across all RcParams instances because + # there can only be one active backend at a time. + # rcParams["backend"] remains valid API for now, but stores the values here + # and not as regular key in the underlying dict. + _backend = rcsetup._auto_backend_sentinel + # validate values on the way in def __init__(self, *args, **kwargs): self.update(*args, **kwargs) @@ -718,6 +724,9 @@ def _set(self, key, val): :meta public: """ + if key == "backend": + RcParams._backend = val + return dict.__setitem__(self, key, val) def _get(self, key): @@ -739,6 +748,8 @@ def _get(self, key): :meta public: """ + if key == "backend": + return RcParams._backend return dict.__getitem__(self, key) def _update_raw(self, other_params): @@ -756,24 +767,24 @@ def _update_raw(self, other_params): """ if isinstance(other_params, RcParams): other_params = dict.items(other_params) + else: + if "backend" in other_params: + # should not happen because we aim to not use "backend" as a regular + # key anymore, but keep to ensure we have not overlooked a code path. + raise RuntimeError("'backend' must not be passed to _update_raw()") dict.update(self, other_params) - def _ensure_has_backend(self): - """ - Ensure that a "backend" entry exists. - - Normally, the default matplotlibrc file contains *no* entry for "backend" (the - corresponding line starts with ##, not #; we fill in _auto_backend_sentinel - in that case. However, packagers can set a different default backend - (resulting in a normal `#backend: foo` line) in which case we should *not* - fill in _auto_backend_sentinel. - """ - dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel) - def __setitem__(self, key, val): - if (key == "backend" - and val is rcsetup._auto_backend_sentinel - and "backend" in self): + if (key == "backend" and val is rcsetup._auto_backend_sentinel): + # Don't let caller silently overwrite a real backend with the auto-sentinel + # (only internal code via _set() may do that). + # + # The primary reason for existence was covering internal rcParams logic + # since end-users do not have direct access to + # rcsetup._auto_backend_sentinel. It is likely that this is not needed + # anymore due to removing "backend" from the dict and making it + # a class attribute RcParams._backend`. But to be on the safe side, we + # keep this as long as "backend" is a valid key for rcParams. return valid_key = _api.getitem_checked( self.validate, rcParam=key, _error_cls=KeyError @@ -787,18 +798,19 @@ def __setitem__(self, key, val): self._set(key, cval) def __getitem__(self, key): - # In theory, this should only ever be used after the global rcParams - # has been set up, but better be safe e.g. in presence of breakpoints. - if key == "backend" and self is globals().get("rcParams"): - val = self._get(key) - if val is rcsetup._auto_backend_sentinel: + if key == "backend": + # In theory, this should only ever be used after the global rcParams + # has been set up, but better be safe e.g. in presence of breakpoints. + if (self is globals().get("rcParams") + and RcParams._backend is rcsetup._auto_backend_sentinel): from matplotlib import pyplot as plt plt.switch_backend(rcsetup._auto_backend_sentinel) + return RcParams._backend return self._get(key) def _get_backend_or_none(self): """Get the requested backend, if any, without triggering resolution.""" - backend = self._get("backend") + backend = RcParams._backend return None if backend is rcsetup._auto_backend_sentinel else backend def __repr__(self): @@ -995,7 +1007,6 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): transform=lambda line: line[1:] if line.startswith("#") else line, fail_on_error=True) rcParamsDefault._update_raw(rcsetup._hardcoded_defaults) -rcParamsDefault._ensure_has_backend() rcParams = RcParams() # The global instance. rcParams._update_raw(rcParamsDefault) @@ -1204,8 +1215,7 @@ def rc_context(rc=None, fname=None): plt.plot(x, y) """ - orig = dict(rcParams.copy()) - del orig['backend'] + orig = rcParams.copy() try: if fname: rc_file(fname) diff --git a/lib/matplotlib/__init__.pyi b/lib/matplotlib/__init__.pyi index 47c9784068fb..fdf70b5aed4b 100644 --- a/lib/matplotlib/__init__.pyi +++ b/lib/matplotlib/__init__.pyi @@ -77,7 +77,6 @@ class RcParams(dict[RcKeyType, Any]): def _update_raw(self, other_params: dict[RcKeyType, Any] | RcParams) -> None: ... - def _ensure_has_backend(self) -> None: ... def __setitem__(self, key: RcKeyType, val: Any) -> None: ... def __getitem__(self, key: RcKeyType) -> Any: ... def __iter__(self) -> Generator[RcKeyType, None, None]: ... diff --git a/lib/matplotlib/_mathtext.py b/lib/matplotlib/_mathtext.py index 319d6f065389..62473c1d1f00 100644 --- a/lib/matplotlib/_mathtext.py +++ b/lib/matplotlib/_mathtext.py @@ -364,6 +364,12 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag self._fonts['default'] = default_font self._fonts['regular'] = default_font + def _normalize_font_pattern(self, pattern: str) -> str: + for option in ['stretch', 'style', 'variant', 'weight']: + if f':{option}=' not in pattern: + pattern = f'{pattern}:{option}=normal' + return pattern + def _get_font(self, font: str) -> FT2Font: basename = self.fontmap.get(font, font) cached_font = self._fonts.get(basename) @@ -492,7 +498,7 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag super().__init__(default_font_prop, load_glyph_flags) for key, val in self._fontmap.items(): - fullpath = findfont(val) + fullpath = findfont(self._normalize_font_pattern(val)) self.fontmap[key] = fullpath self.fontmap[val] = fullpath @@ -617,7 +623,7 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag } for size, name in stixsizedaltfonts.items(): - fullpath = findfont(name) + fullpath = findfont(self._normalize_font_pattern(name)) self.fontmap[size] = fullpath self.fontmap[name] = fullpath @@ -719,7 +725,7 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag '5': 'STIXSizeFiveSym', }) for key, name in self._fontmap.items(): - fullpath = findfont(name) + fullpath = findfont(self._normalize_font_pattern(name)) self.fontmap[key] = fullpath self.fontmap[name] = fullpath @@ -748,9 +754,9 @@ class DejaVuSerifFonts(DejaVuFonts): """ _fontmap = { 'rm': 'DejaVu Serif', - 'it': 'DejaVu Serif:italic', + 'it': 'DejaVu Serif:style=italic', 'bf': 'DejaVu Serif:weight=bold', - 'bfit': 'DejaVu Serif:italic:bold', + 'bfit': 'DejaVu Serif:style=italic:weight=bold', 'sf': 'DejaVu Sans', 'tt': 'DejaVu Sans Mono', 'ex': 'DejaVu Serif Display', @@ -769,9 +775,9 @@ class DejaVuSansFonts(DejaVuFonts): """ _fontmap = { 'rm': 'DejaVu Sans', - 'it': 'DejaVu Sans:italic', + 'it': 'DejaVu Sans:style=italic', 'bf': 'DejaVu Sans:weight=bold', - 'bfit': 'DejaVu Sans:italic:bold', + 'bfit': 'DejaVu Sans:style=italic:weight=bold', 'sf': 'DejaVu Sans', 'tt': 'DejaVu Sans Mono', 'ex': 'DejaVu Sans Display', @@ -796,11 +802,11 @@ class StixFonts(UnicodeFonts): """ _fontmap = { 'rm': 'STIXGeneral', - 'it': 'STIXGeneral:italic', + 'it': 'STIXGeneral:style=italic', 'bf': 'STIXGeneral:weight=bold', - 'bfit': 'STIXGeneral:italic:bold', + 'bfit': 'STIXGeneral:style=italic:weight=bold', 'nonunirm': 'STIXNonUnicode', - 'nonuniit': 'STIXNonUnicode:italic', + 'nonuniit': 'STIXNonUnicode:style=italic', 'nonunibf': 'STIXNonUnicode:weight=bold', '0': 'STIXGeneral', '1': 'STIXSizeOneSym', @@ -815,7 +821,7 @@ class StixFonts(UnicodeFonts): def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) for key, name in self._fontmap.items(): - fullpath = findfont(name) + fullpath = findfont(self._normalize_font_pattern(name)) self.fontmap[key] = fullpath self.fontmap[name] = fullpath diff --git a/lib/matplotlib/_text_helpers.py b/lib/matplotlib/_text_helpers.py index 0ebbf3ac139d..4d36f92ac316 100644 --- a/lib/matplotlib/_text_helpers.py +++ b/lib/matplotlib/_text_helpers.py @@ -24,8 +24,8 @@ def layout(string: str, font: FT2Font, *, """ Render *string* with *font*. - For each character in *string*, yield a LayoutItem instance. When such an instance - is yielded, the font's glyph is set to the corresponding character. + For each character in *string*, yield a LayoutItem instance. Callers that + need the outline must load the glyph themselves. Parameters ---------- @@ -43,8 +43,5 @@ def layout(string: str, font: FT2Font, *, ------ LayoutItem """ - for raqm_item in font._layout(string, LoadFlags.NO_HINTING, - features=features, language=language): - raqm_item.ft_object.load_glyph(raqm_item.glyph_index, - flags=LoadFlags.NO_HINTING) - yield raqm_item + yield from font._layout(string, LoadFlags.NO_HINTING, + features=features, language=language) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index ad303cbb92e9..66f1083a59c7 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -360,7 +360,7 @@ def grab_frame(self, **savefig_kwargs): def _args(self): """Assemble list of encoder-specific command-line arguments.""" - return NotImplementedError("args needs to be implemented by subclass.") + raise NotImplementedError("args needs to be implemented by subclass.") @classmethod def bin_path(cls): @@ -946,7 +946,7 @@ def _stop(self, *args): self._fig.canvas.mpl_disconnect(self._resize_id) self._fig.canvas.mpl_disconnect(self._close_id) self.event_source.remove_callback(self._step) - self.event_source = None + self.event_source.stop() def save(self, filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, @@ -1276,7 +1276,7 @@ def _end_redraw(self, event): self._resize_id = self._fig.canvas.mpl_connect('resize_event', self._on_resize) - def to_html5_video(self, embed_limit=None): + def to_html5_video(self, embed_limit=None, *, _writer_cls=None): """ Convert the animation to an HTML5 ``