Commit ·
c5edd41
1
Parent(s): 6c80b41
Upload folder using huggingface_hub (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +21 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_axes.cpython-311.pyc +3 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_base.cpython-311.pyc +3 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_axes.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_axes.pyi +780 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_base.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_base.pyi +459 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.py +322 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.pyi +45 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axis.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axis.pyi +280 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_bases.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_bases.pyi +482 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_managers.py +387 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_managers.pyi +64 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_tools.py +998 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_tools.pyi +121 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__init__.py +5 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__pycache__/registry.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so +3 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.pyi +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_gtk.py +331 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_pdf_ps.py +189 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_tk.py +1105 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_macosx.pyi +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so +3 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_tkagg.pyi +15 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py +528 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_cairo.py +529 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3.py +596 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3agg.py +74 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3cairo.py +35 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4.py +642 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4agg.py +41 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4cairo.py +32 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_macosx.py +196 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_mixed.py +119 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_nbagg.py +243 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_pdf.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py +1010 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_ps.py +1481 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt.py +1089 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5.py +28 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5agg.py +14 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5cairo.py +11 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qtagg.py +86 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qtcairo.py +46 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_svg.py +1380 -0
.gitattributes
CHANGED
|
@@ -959,3 +959,24 @@ pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_image.cpytho
|
|
| 959 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 960 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 961 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 960 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 961 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 962 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_axes.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 963 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_base.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 964 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 965 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 966 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/ft2font.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 967 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf filter=lfs diff=lfs merge=lfs -text
|
| 968 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
|
| 969 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
|
| 970 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
|
| 971 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf filter=lfs diff=lfs merge=lfs -text
|
| 972 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
|
| 973 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
|
| 974 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
|
| 975 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf filter=lfs diff=lfs merge=lfs -text
|
| 976 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf filter=lfs diff=lfs merge=lfs -text
|
| 977 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf filter=lfs diff=lfs merge=lfs -text
|
| 978 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf filter=lfs diff=lfs merge=lfs -text
|
| 979 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf filter=lfs diff=lfs merge=lfs -text
|
| 980 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text
|
| 981 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text
|
| 982 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_axes.cpython-311.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6c741aca585c4d79d92632955e299b7b621489ff33a528fdbe54ffbbb081bc5d
|
| 3 |
+
size 372185
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_base.cpython-311.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:da208458cfa2fa34ebbde8a445247b6e04411fa6c99cae8b1eb63eb1d452345d
|
| 3 |
+
size 226949
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-311.pyc
ADDED
|
Binary file (15 kB). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_axes.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_axes.pyi
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib.axes._base import _AxesBase
|
| 2 |
+
from matplotlib.axes._secondary_axes import SecondaryAxis
|
| 3 |
+
|
| 4 |
+
from matplotlib.artist import Artist
|
| 5 |
+
from matplotlib.backend_bases import RendererBase
|
| 6 |
+
from matplotlib.collections import (
|
| 7 |
+
Collection,
|
| 8 |
+
FillBetweenPolyCollection,
|
| 9 |
+
LineCollection,
|
| 10 |
+
PathCollection,
|
| 11 |
+
PolyCollection,
|
| 12 |
+
EventCollection,
|
| 13 |
+
QuadMesh,
|
| 14 |
+
)
|
| 15 |
+
from matplotlib.colorizer import Colorizer
|
| 16 |
+
from matplotlib.colors import Colormap, Normalize
|
| 17 |
+
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
|
| 18 |
+
from matplotlib.contour import ContourSet, QuadContourSet
|
| 19 |
+
from matplotlib.image import AxesImage, PcolorImage
|
| 20 |
+
from matplotlib.inset import InsetIndicator
|
| 21 |
+
from matplotlib.legend import Legend
|
| 22 |
+
from matplotlib.legend_handler import HandlerBase
|
| 23 |
+
from matplotlib.lines import Line2D, AxLine
|
| 24 |
+
from matplotlib.mlab import GaussianKDE
|
| 25 |
+
from matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge
|
| 26 |
+
from matplotlib.quiver import Quiver, QuiverKey, Barbs
|
| 27 |
+
from matplotlib.text import Annotation, Text
|
| 28 |
+
from matplotlib.transforms import Transform
|
| 29 |
+
from matplotlib.typing import CoordsType
|
| 30 |
+
import matplotlib.tri as mtri
|
| 31 |
+
import matplotlib.table as mtable
|
| 32 |
+
import matplotlib.stackplot as mstack
|
| 33 |
+
import matplotlib.streamplot as mstream
|
| 34 |
+
|
| 35 |
+
import datetime
|
| 36 |
+
import PIL.Image
|
| 37 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 38 |
+
from typing import Any, Literal, overload
|
| 39 |
+
import numpy as np
|
| 40 |
+
from numpy.typing import ArrayLike
|
| 41 |
+
from matplotlib.typing import ColorType, MarkerType, LineStyleType
|
| 42 |
+
|
| 43 |
+
class Axes(_AxesBase):
|
| 44 |
+
def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ...
|
| 45 |
+
def set_title(
|
| 46 |
+
self,
|
| 47 |
+
label: str,
|
| 48 |
+
fontdict: dict[str, Any] | None = ...,
|
| 49 |
+
loc: Literal["left", "center", "right"] | None = ...,
|
| 50 |
+
pad: float | None = ...,
|
| 51 |
+
*,
|
| 52 |
+
y: float | None = ...,
|
| 53 |
+
**kwargs
|
| 54 |
+
) -> Text: ...
|
| 55 |
+
def get_legend_handles_labels(
|
| 56 |
+
self, legend_handler_map: dict[type, HandlerBase] | None = ...
|
| 57 |
+
) -> tuple[list[Artist], list[Any]]: ...
|
| 58 |
+
legend_: Legend | None
|
| 59 |
+
|
| 60 |
+
@overload
|
| 61 |
+
def legend(self) -> Legend: ...
|
| 62 |
+
@overload
|
| 63 |
+
def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ...
|
| 64 |
+
@overload
|
| 65 |
+
def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ...
|
| 66 |
+
@overload
|
| 67 |
+
def legend(self, labels: Iterable[str], **kwargs) -> Legend: ...
|
| 68 |
+
@overload
|
| 69 |
+
def legend(self, **kwargs) -> Legend: ...
|
| 70 |
+
|
| 71 |
+
def inset_axes(
|
| 72 |
+
self,
|
| 73 |
+
bounds: tuple[float, float, float, float],
|
| 74 |
+
*,
|
| 75 |
+
transform: Transform | None = ...,
|
| 76 |
+
zorder: float = ...,
|
| 77 |
+
**kwargs
|
| 78 |
+
) -> Axes: ...
|
| 79 |
+
def indicate_inset(
|
| 80 |
+
self,
|
| 81 |
+
bounds: tuple[float, float, float, float] | None = ...,
|
| 82 |
+
inset_ax: Axes | None = ...,
|
| 83 |
+
*,
|
| 84 |
+
transform: Transform | None = ...,
|
| 85 |
+
facecolor: ColorType = ...,
|
| 86 |
+
edgecolor: ColorType = ...,
|
| 87 |
+
alpha: float = ...,
|
| 88 |
+
zorder: float | None = ...,
|
| 89 |
+
**kwargs
|
| 90 |
+
) -> InsetIndicator: ...
|
| 91 |
+
def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> InsetIndicator: ...
|
| 92 |
+
def secondary_xaxis(
|
| 93 |
+
self,
|
| 94 |
+
location: Literal["top", "bottom"] | float,
|
| 95 |
+
functions: tuple[
|
| 96 |
+
Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
|
| 97 |
+
]
|
| 98 |
+
| Transform
|
| 99 |
+
| None = ...,
|
| 100 |
+
*,
|
| 101 |
+
transform: Transform | None = ...,
|
| 102 |
+
**kwargs
|
| 103 |
+
) -> SecondaryAxis: ...
|
| 104 |
+
def secondary_yaxis(
|
| 105 |
+
self,
|
| 106 |
+
location: Literal["left", "right"] | float,
|
| 107 |
+
functions: tuple[
|
| 108 |
+
Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
|
| 109 |
+
]
|
| 110 |
+
| Transform
|
| 111 |
+
| None = ...,
|
| 112 |
+
*,
|
| 113 |
+
transform: Transform | None = ...,
|
| 114 |
+
**kwargs
|
| 115 |
+
) -> SecondaryAxis: ...
|
| 116 |
+
def text(
|
| 117 |
+
self,
|
| 118 |
+
x: float,
|
| 119 |
+
y: float,
|
| 120 |
+
s: str,
|
| 121 |
+
fontdict: dict[str, Any] | None = ...,
|
| 122 |
+
**kwargs
|
| 123 |
+
) -> Text: ...
|
| 124 |
+
def annotate(
|
| 125 |
+
self,
|
| 126 |
+
text: str,
|
| 127 |
+
xy: tuple[float, float],
|
| 128 |
+
xytext: tuple[float, float] | None = ...,
|
| 129 |
+
xycoords: CoordsType = ...,
|
| 130 |
+
textcoords: CoordsType | None = ...,
|
| 131 |
+
arrowprops: dict[str, Any] | None = ...,
|
| 132 |
+
annotation_clip: bool | None = ...,
|
| 133 |
+
**kwargs
|
| 134 |
+
) -> Annotation: ...
|
| 135 |
+
def axhline(
|
| 136 |
+
self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs
|
| 137 |
+
) -> Line2D: ...
|
| 138 |
+
def axvline(
|
| 139 |
+
self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs
|
| 140 |
+
) -> Line2D: ...
|
| 141 |
+
|
| 142 |
+
# TODO: Could separate the xy2 and slope signatures
|
| 143 |
+
def axline(
|
| 144 |
+
self,
|
| 145 |
+
xy1: tuple[float, float],
|
| 146 |
+
xy2: tuple[float, float] | None = ...,
|
| 147 |
+
*,
|
| 148 |
+
slope: float | None = ...,
|
| 149 |
+
**kwargs
|
| 150 |
+
) -> AxLine: ...
|
| 151 |
+
def axhspan(
|
| 152 |
+
self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs
|
| 153 |
+
) -> Rectangle: ...
|
| 154 |
+
def axvspan(
|
| 155 |
+
self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs
|
| 156 |
+
) -> Rectangle: ...
|
| 157 |
+
def hlines(
|
| 158 |
+
self,
|
| 159 |
+
y: float | ArrayLike,
|
| 160 |
+
xmin: float | ArrayLike,
|
| 161 |
+
xmax: float | ArrayLike,
|
| 162 |
+
colors: ColorType | Sequence[ColorType] | None = ...,
|
| 163 |
+
linestyles: LineStyleType = ...,
|
| 164 |
+
*,
|
| 165 |
+
label: str = ...,
|
| 166 |
+
data=...,
|
| 167 |
+
**kwargs
|
| 168 |
+
) -> LineCollection: ...
|
| 169 |
+
def vlines(
|
| 170 |
+
self,
|
| 171 |
+
x: float | ArrayLike,
|
| 172 |
+
ymin: float | ArrayLike,
|
| 173 |
+
ymax: float | ArrayLike,
|
| 174 |
+
colors: ColorType | Sequence[ColorType] | None = ...,
|
| 175 |
+
linestyles: LineStyleType = ...,
|
| 176 |
+
*,
|
| 177 |
+
label: str = ...,
|
| 178 |
+
data=...,
|
| 179 |
+
**kwargs
|
| 180 |
+
) -> LineCollection: ...
|
| 181 |
+
def eventplot(
|
| 182 |
+
self,
|
| 183 |
+
positions: ArrayLike | Sequence[ArrayLike],
|
| 184 |
+
*,
|
| 185 |
+
orientation: Literal["horizontal", "vertical"] = ...,
|
| 186 |
+
lineoffsets: float | Sequence[float] = ...,
|
| 187 |
+
linelengths: float | Sequence[float] = ...,
|
| 188 |
+
linewidths: float | Sequence[float] | None = ...,
|
| 189 |
+
colors: ColorType | Sequence[ColorType] | None = ...,
|
| 190 |
+
alpha: float | Sequence[float] | None = ...,
|
| 191 |
+
linestyles: LineStyleType | Sequence[LineStyleType] = ...,
|
| 192 |
+
data=...,
|
| 193 |
+
**kwargs
|
| 194 |
+
) -> EventCollection: ...
|
| 195 |
+
def plot(
|
| 196 |
+
self,
|
| 197 |
+
*args: float | ArrayLike | str,
|
| 198 |
+
scalex: bool = ...,
|
| 199 |
+
scaley: bool = ...,
|
| 200 |
+
data=...,
|
| 201 |
+
**kwargs
|
| 202 |
+
) -> list[Line2D]: ...
|
| 203 |
+
def plot_date(
|
| 204 |
+
self,
|
| 205 |
+
x: ArrayLike,
|
| 206 |
+
y: ArrayLike,
|
| 207 |
+
fmt: str = ...,
|
| 208 |
+
tz: str | datetime.tzinfo | None = ...,
|
| 209 |
+
xdate: bool = ...,
|
| 210 |
+
ydate: bool = ...,
|
| 211 |
+
*,
|
| 212 |
+
data=...,
|
| 213 |
+
**kwargs
|
| 214 |
+
) -> list[Line2D]: ...
|
| 215 |
+
def loglog(self, *args, **kwargs) -> list[Line2D]: ...
|
| 216 |
+
def semilogx(self, *args, **kwargs) -> list[Line2D]: ...
|
| 217 |
+
def semilogy(self, *args, **kwargs) -> list[Line2D]: ...
|
| 218 |
+
def acorr(
|
| 219 |
+
self, x: ArrayLike, *, data=..., **kwargs
|
| 220 |
+
) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
|
| 221 |
+
def xcorr(
|
| 222 |
+
self,
|
| 223 |
+
x: ArrayLike,
|
| 224 |
+
y: ArrayLike,
|
| 225 |
+
*,
|
| 226 |
+
normed: bool = ...,
|
| 227 |
+
detrend: Callable[[ArrayLike], ArrayLike] = ...,
|
| 228 |
+
usevlines: bool = ...,
|
| 229 |
+
maxlags: int = ...,
|
| 230 |
+
data=...,
|
| 231 |
+
**kwargs
|
| 232 |
+
) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
|
| 233 |
+
def step(
|
| 234 |
+
self,
|
| 235 |
+
x: ArrayLike,
|
| 236 |
+
y: ArrayLike,
|
| 237 |
+
*args,
|
| 238 |
+
where: Literal["pre", "post", "mid"] = ...,
|
| 239 |
+
data=...,
|
| 240 |
+
**kwargs
|
| 241 |
+
) -> list[Line2D]: ...
|
| 242 |
+
def bar(
|
| 243 |
+
self,
|
| 244 |
+
x: float | ArrayLike,
|
| 245 |
+
height: float | ArrayLike,
|
| 246 |
+
width: float | ArrayLike = ...,
|
| 247 |
+
bottom: float | ArrayLike | None = ...,
|
| 248 |
+
*,
|
| 249 |
+
align: Literal["center", "edge"] = ...,
|
| 250 |
+
data=...,
|
| 251 |
+
**kwargs
|
| 252 |
+
) -> BarContainer: ...
|
| 253 |
+
def barh(
|
| 254 |
+
self,
|
| 255 |
+
y: float | ArrayLike,
|
| 256 |
+
width: float | ArrayLike,
|
| 257 |
+
height: float | ArrayLike = ...,
|
| 258 |
+
left: float | ArrayLike | None = ...,
|
| 259 |
+
*,
|
| 260 |
+
align: Literal["center", "edge"] = ...,
|
| 261 |
+
data=...,
|
| 262 |
+
**kwargs
|
| 263 |
+
) -> BarContainer: ...
|
| 264 |
+
def bar_label(
|
| 265 |
+
self,
|
| 266 |
+
container: BarContainer,
|
| 267 |
+
labels: ArrayLike | None = ...,
|
| 268 |
+
*,
|
| 269 |
+
fmt: str | Callable[[float], str] = ...,
|
| 270 |
+
label_type: Literal["center", "edge"] = ...,
|
| 271 |
+
padding: float = ...,
|
| 272 |
+
**kwargs
|
| 273 |
+
) -> list[Annotation]: ...
|
| 274 |
+
def broken_barh(
|
| 275 |
+
self,
|
| 276 |
+
xranges: Sequence[tuple[float, float]],
|
| 277 |
+
yrange: tuple[float, float],
|
| 278 |
+
*,
|
| 279 |
+
data=...,
|
| 280 |
+
**kwargs
|
| 281 |
+
) -> PolyCollection: ...
|
| 282 |
+
def stem(
|
| 283 |
+
self,
|
| 284 |
+
*args: ArrayLike | str,
|
| 285 |
+
linefmt: str | None = ...,
|
| 286 |
+
markerfmt: str | None = ...,
|
| 287 |
+
basefmt: str | None = ...,
|
| 288 |
+
bottom: float = ...,
|
| 289 |
+
label: str | None = ...,
|
| 290 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 291 |
+
data=...,
|
| 292 |
+
) -> StemContainer: ...
|
| 293 |
+
|
| 294 |
+
# TODO: data kwarg preprocessor?
|
| 295 |
+
def pie(
|
| 296 |
+
self,
|
| 297 |
+
x: ArrayLike,
|
| 298 |
+
*,
|
| 299 |
+
explode: ArrayLike | None = ...,
|
| 300 |
+
labels: Sequence[str] | None = ...,
|
| 301 |
+
colors: ColorType | Sequence[ColorType] | None = ...,
|
| 302 |
+
autopct: str | Callable[[float], str] | None = ...,
|
| 303 |
+
pctdistance: float = ...,
|
| 304 |
+
shadow: bool = ...,
|
| 305 |
+
labeldistance: float | None = ...,
|
| 306 |
+
startangle: float = ...,
|
| 307 |
+
radius: float = ...,
|
| 308 |
+
counterclock: bool = ...,
|
| 309 |
+
wedgeprops: dict[str, Any] | None = ...,
|
| 310 |
+
textprops: dict[str, Any] | None = ...,
|
| 311 |
+
center: tuple[float, float] = ...,
|
| 312 |
+
frame: bool = ...,
|
| 313 |
+
rotatelabels: bool = ...,
|
| 314 |
+
normalize: bool = ...,
|
| 315 |
+
hatch: str | Sequence[str] | None = ...,
|
| 316 |
+
data=...,
|
| 317 |
+
) -> tuple[list[Wedge], list[Text]] | tuple[
|
| 318 |
+
list[Wedge], list[Text], list[Text]
|
| 319 |
+
]: ...
|
| 320 |
+
def errorbar(
|
| 321 |
+
self,
|
| 322 |
+
x: float | ArrayLike,
|
| 323 |
+
y: float | ArrayLike,
|
| 324 |
+
yerr: float | ArrayLike | None = ...,
|
| 325 |
+
xerr: float | ArrayLike | None = ...,
|
| 326 |
+
fmt: str = ...,
|
| 327 |
+
*,
|
| 328 |
+
ecolor: ColorType | None = ...,
|
| 329 |
+
elinewidth: float | None = ...,
|
| 330 |
+
capsize: float | None = ...,
|
| 331 |
+
barsabove: bool = ...,
|
| 332 |
+
lolims: bool | ArrayLike = ...,
|
| 333 |
+
uplims: bool | ArrayLike = ...,
|
| 334 |
+
xlolims: bool | ArrayLike = ...,
|
| 335 |
+
xuplims: bool | ArrayLike = ...,
|
| 336 |
+
errorevery: int | tuple[int, int] = ...,
|
| 337 |
+
capthick: float | None = ...,
|
| 338 |
+
data=...,
|
| 339 |
+
**kwargs
|
| 340 |
+
) -> ErrorbarContainer: ...
|
| 341 |
+
def boxplot(
|
| 342 |
+
self,
|
| 343 |
+
x: ArrayLike | Sequence[ArrayLike],
|
| 344 |
+
*,
|
| 345 |
+
notch: bool | None = ...,
|
| 346 |
+
sym: str | None = ...,
|
| 347 |
+
vert: bool | None = ...,
|
| 348 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 349 |
+
whis: float | tuple[float, float] | None = ...,
|
| 350 |
+
positions: ArrayLike | None = ...,
|
| 351 |
+
widths: float | ArrayLike | None = ...,
|
| 352 |
+
patch_artist: bool | None = ...,
|
| 353 |
+
bootstrap: int | None = ...,
|
| 354 |
+
usermedians: ArrayLike | None = ...,
|
| 355 |
+
conf_intervals: ArrayLike | None = ...,
|
| 356 |
+
meanline: bool | None = ...,
|
| 357 |
+
showmeans: bool | None = ...,
|
| 358 |
+
showcaps: bool | None = ...,
|
| 359 |
+
showbox: bool | None = ...,
|
| 360 |
+
showfliers: bool | None = ...,
|
| 361 |
+
boxprops: dict[str, Any] | None = ...,
|
| 362 |
+
tick_labels: Sequence[str] | None = ...,
|
| 363 |
+
flierprops: dict[str, Any] | None = ...,
|
| 364 |
+
medianprops: dict[str, Any] | None = ...,
|
| 365 |
+
meanprops: dict[str, Any] | None = ...,
|
| 366 |
+
capprops: dict[str, Any] | None = ...,
|
| 367 |
+
whiskerprops: dict[str, Any] | None = ...,
|
| 368 |
+
manage_ticks: bool = ...,
|
| 369 |
+
autorange: bool = ...,
|
| 370 |
+
zorder: float | None = ...,
|
| 371 |
+
capwidths: float | ArrayLike | None = ...,
|
| 372 |
+
label: Sequence[str] | None = ...,
|
| 373 |
+
data=...,
|
| 374 |
+
) -> dict[str, Any]: ...
|
| 375 |
+
def bxp(
|
| 376 |
+
self,
|
| 377 |
+
bxpstats: Sequence[dict[str, Any]],
|
| 378 |
+
positions: ArrayLike | None = ...,
|
| 379 |
+
*,
|
| 380 |
+
widths: float | ArrayLike | None = ...,
|
| 381 |
+
vert: bool | None = ...,
|
| 382 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 383 |
+
patch_artist: bool = ...,
|
| 384 |
+
shownotches: bool = ...,
|
| 385 |
+
showmeans: bool = ...,
|
| 386 |
+
showcaps: bool = ...,
|
| 387 |
+
showbox: bool = ...,
|
| 388 |
+
showfliers: bool = ...,
|
| 389 |
+
boxprops: dict[str, Any] | None = ...,
|
| 390 |
+
whiskerprops: dict[str, Any] | None = ...,
|
| 391 |
+
flierprops: dict[str, Any] | None = ...,
|
| 392 |
+
medianprops: dict[str, Any] | None = ...,
|
| 393 |
+
capprops: dict[str, Any] | None = ...,
|
| 394 |
+
meanprops: dict[str, Any] | None = ...,
|
| 395 |
+
meanline: bool = ...,
|
| 396 |
+
manage_ticks: bool = ...,
|
| 397 |
+
zorder: float | None = ...,
|
| 398 |
+
capwidths: float | ArrayLike | None = ...,
|
| 399 |
+
label: Sequence[str] | None = ...,
|
| 400 |
+
) -> dict[str, Any]: ...
|
| 401 |
+
def scatter(
|
| 402 |
+
self,
|
| 403 |
+
x: float | ArrayLike,
|
| 404 |
+
y: float | ArrayLike,
|
| 405 |
+
s: float | ArrayLike | None = ...,
|
| 406 |
+
c: ArrayLike | Sequence[ColorType] | ColorType | None = ...,
|
| 407 |
+
*,
|
| 408 |
+
marker: MarkerType | None = ...,
|
| 409 |
+
cmap: str | Colormap | None = ...,
|
| 410 |
+
norm: str | Normalize | None = ...,
|
| 411 |
+
vmin: float | None = ...,
|
| 412 |
+
vmax: float | None = ...,
|
| 413 |
+
alpha: float | None = ...,
|
| 414 |
+
linewidths: float | Sequence[float] | None = ...,
|
| 415 |
+
edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ...,
|
| 416 |
+
colorizer: Colorizer | None = ...,
|
| 417 |
+
plotnonfinite: bool = ...,
|
| 418 |
+
data=...,
|
| 419 |
+
**kwargs
|
| 420 |
+
) -> PathCollection: ...
|
| 421 |
+
def hexbin(
|
| 422 |
+
self,
|
| 423 |
+
x: ArrayLike,
|
| 424 |
+
y: ArrayLike,
|
| 425 |
+
C: ArrayLike | None = ...,
|
| 426 |
+
*,
|
| 427 |
+
gridsize: int | tuple[int, int] = ...,
|
| 428 |
+
bins: Literal["log"] | int | Sequence[float] | None = ...,
|
| 429 |
+
xscale: Literal["linear", "log"] = ...,
|
| 430 |
+
yscale: Literal["linear", "log"] = ...,
|
| 431 |
+
extent: tuple[float, float, float, float] | None = ...,
|
| 432 |
+
cmap: str | Colormap | None = ...,
|
| 433 |
+
norm: str | Normalize | None = ...,
|
| 434 |
+
vmin: float | None = ...,
|
| 435 |
+
vmax: float | None = ...,
|
| 436 |
+
alpha: float | None = ...,
|
| 437 |
+
linewidths: float | None = ...,
|
| 438 |
+
edgecolors: Literal["face", "none"] | ColorType = ...,
|
| 439 |
+
reduce_C_function: Callable[[np.ndarray | list[float]], float] = ...,
|
| 440 |
+
mincnt: int | None = ...,
|
| 441 |
+
marginals: bool = ...,
|
| 442 |
+
colorizer: Colorizer | None = ...,
|
| 443 |
+
data=...,
|
| 444 |
+
**kwargs
|
| 445 |
+
) -> PolyCollection: ...
|
| 446 |
+
def arrow(
|
| 447 |
+
self, x: float, y: float, dx: float, dy: float, **kwargs
|
| 448 |
+
) -> FancyArrow: ...
|
| 449 |
+
def quiverkey(
|
| 450 |
+
self, Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs
|
| 451 |
+
) -> QuiverKey: ...
|
| 452 |
+
def quiver(self, *args, data=..., **kwargs) -> Quiver: ...
|
| 453 |
+
def barbs(self, *args, data=..., **kwargs) -> Barbs: ...
|
| 454 |
+
def fill(self, *args, data=..., **kwargs) -> list[Polygon]: ...
|
| 455 |
+
def fill_between(
|
| 456 |
+
self,
|
| 457 |
+
x: ArrayLike,
|
| 458 |
+
y1: ArrayLike | float,
|
| 459 |
+
y2: ArrayLike | float = ...,
|
| 460 |
+
where: Sequence[bool] | None = ...,
|
| 461 |
+
interpolate: bool = ...,
|
| 462 |
+
step: Literal["pre", "post", "mid"] | None = ...,
|
| 463 |
+
*,
|
| 464 |
+
data=...,
|
| 465 |
+
**kwargs
|
| 466 |
+
) -> FillBetweenPolyCollection: ...
|
| 467 |
+
def fill_betweenx(
|
| 468 |
+
self,
|
| 469 |
+
y: ArrayLike,
|
| 470 |
+
x1: ArrayLike | float,
|
| 471 |
+
x2: ArrayLike | float = ...,
|
| 472 |
+
where: Sequence[bool] | None = ...,
|
| 473 |
+
step: Literal["pre", "post", "mid"] | None = ...,
|
| 474 |
+
interpolate: bool = ...,
|
| 475 |
+
*,
|
| 476 |
+
data=...,
|
| 477 |
+
**kwargs
|
| 478 |
+
) -> FillBetweenPolyCollection: ...
|
| 479 |
+
def imshow(
|
| 480 |
+
self,
|
| 481 |
+
X: ArrayLike | PIL.Image.Image,
|
| 482 |
+
cmap: str | Colormap | None = ...,
|
| 483 |
+
norm: str | Normalize | None = ...,
|
| 484 |
+
*,
|
| 485 |
+
aspect: Literal["equal", "auto"] | float | None = ...,
|
| 486 |
+
interpolation: str | None = ...,
|
| 487 |
+
alpha: float | ArrayLike | None = ...,
|
| 488 |
+
vmin: float | None = ...,
|
| 489 |
+
vmax: float | None = ...,
|
| 490 |
+
colorizer: Colorizer | None = ...,
|
| 491 |
+
origin: Literal["upper", "lower"] | None = ...,
|
| 492 |
+
extent: tuple[float, float, float, float] | None = ...,
|
| 493 |
+
interpolation_stage: Literal["data", "rgba", "auto"] | None = ...,
|
| 494 |
+
filternorm: bool = ...,
|
| 495 |
+
filterrad: float = ...,
|
| 496 |
+
resample: bool | None = ...,
|
| 497 |
+
url: str | None = ...,
|
| 498 |
+
data=...,
|
| 499 |
+
**kwargs
|
| 500 |
+
) -> AxesImage: ...
|
| 501 |
+
def pcolor(
|
| 502 |
+
self,
|
| 503 |
+
*args: ArrayLike,
|
| 504 |
+
shading: Literal["flat", "nearest", "auto"] | None = ...,
|
| 505 |
+
alpha: float | None = ...,
|
| 506 |
+
norm: str | Normalize | None = ...,
|
| 507 |
+
cmap: str | Colormap | None = ...,
|
| 508 |
+
vmin: float | None = ...,
|
| 509 |
+
vmax: float | None = ...,
|
| 510 |
+
colorizer: Colorizer | None = ...,
|
| 511 |
+
data=...,
|
| 512 |
+
**kwargs
|
| 513 |
+
) -> Collection: ...
|
| 514 |
+
def pcolormesh(
|
| 515 |
+
self,
|
| 516 |
+
*args: ArrayLike,
|
| 517 |
+
alpha: float | None = ...,
|
| 518 |
+
norm: str | Normalize | None = ...,
|
| 519 |
+
cmap: str | Colormap | None = ...,
|
| 520 |
+
vmin: float | None = ...,
|
| 521 |
+
vmax: float | None = ...,
|
| 522 |
+
colorizer: Colorizer | None = ...,
|
| 523 |
+
shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ...,
|
| 524 |
+
antialiased: bool = ...,
|
| 525 |
+
data=...,
|
| 526 |
+
**kwargs
|
| 527 |
+
) -> QuadMesh: ...
|
| 528 |
+
def pcolorfast(
|
| 529 |
+
self,
|
| 530 |
+
*args: ArrayLike | tuple[float, float],
|
| 531 |
+
alpha: float | None = ...,
|
| 532 |
+
norm: str | Normalize | None = ...,
|
| 533 |
+
cmap: str | Colormap | None = ...,
|
| 534 |
+
vmin: float | None = ...,
|
| 535 |
+
vmax: float | None = ...,
|
| 536 |
+
colorizer: Colorizer | None = ...,
|
| 537 |
+
data=...,
|
| 538 |
+
**kwargs
|
| 539 |
+
) -> AxesImage | PcolorImage | QuadMesh: ...
|
| 540 |
+
def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ...
|
| 541 |
+
def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ...
|
| 542 |
+
def clabel(
|
| 543 |
+
self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs
|
| 544 |
+
) -> list[Text]: ...
|
| 545 |
+
def hist(
|
| 546 |
+
self,
|
| 547 |
+
x: ArrayLike | Sequence[ArrayLike],
|
| 548 |
+
bins: int | Sequence[float] | str | None = ...,
|
| 549 |
+
*,
|
| 550 |
+
range: tuple[float, float] | None = ...,
|
| 551 |
+
density: bool = ...,
|
| 552 |
+
weights: ArrayLike | None = ...,
|
| 553 |
+
cumulative: bool | float = ...,
|
| 554 |
+
bottom: ArrayLike | float | None = ...,
|
| 555 |
+
histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ...,
|
| 556 |
+
align: Literal["left", "mid", "right"] = ...,
|
| 557 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 558 |
+
rwidth: float | None = ...,
|
| 559 |
+
log: bool = ...,
|
| 560 |
+
color: ColorType | Sequence[ColorType] | None = ...,
|
| 561 |
+
label: str | Sequence[str] | None = ...,
|
| 562 |
+
stacked: bool = ...,
|
| 563 |
+
data=...,
|
| 564 |
+
**kwargs
|
| 565 |
+
) -> tuple[
|
| 566 |
+
np.ndarray | list[np.ndarray],
|
| 567 |
+
np.ndarray,
|
| 568 |
+
BarContainer | Polygon | list[BarContainer | Polygon],
|
| 569 |
+
]: ...
|
| 570 |
+
def stairs(
|
| 571 |
+
self,
|
| 572 |
+
values: ArrayLike,
|
| 573 |
+
edges: ArrayLike | None = ...,
|
| 574 |
+
*,
|
| 575 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 576 |
+
baseline: float | ArrayLike | None = ...,
|
| 577 |
+
fill: bool = ...,
|
| 578 |
+
data=...,
|
| 579 |
+
**kwargs
|
| 580 |
+
) -> StepPatch: ...
|
| 581 |
+
def hist2d(
|
| 582 |
+
self,
|
| 583 |
+
x: ArrayLike,
|
| 584 |
+
y: ArrayLike,
|
| 585 |
+
bins: None
|
| 586 |
+
| int
|
| 587 |
+
| tuple[int, int]
|
| 588 |
+
| ArrayLike
|
| 589 |
+
| tuple[ArrayLike, ArrayLike] = ...,
|
| 590 |
+
*,
|
| 591 |
+
range: ArrayLike | None = ...,
|
| 592 |
+
density: bool = ...,
|
| 593 |
+
weights: ArrayLike | None = ...,
|
| 594 |
+
cmin: float | None = ...,
|
| 595 |
+
cmax: float | None = ...,
|
| 596 |
+
data=...,
|
| 597 |
+
**kwargs
|
| 598 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ...
|
| 599 |
+
def ecdf(
|
| 600 |
+
self,
|
| 601 |
+
x: ArrayLike,
|
| 602 |
+
weights: ArrayLike | None = ...,
|
| 603 |
+
*,
|
| 604 |
+
complementary: bool=...,
|
| 605 |
+
orientation: Literal["vertical", "horizontal"]=...,
|
| 606 |
+
compress: bool=...,
|
| 607 |
+
data=...,
|
| 608 |
+
**kwargs
|
| 609 |
+
) -> Line2D: ...
|
| 610 |
+
def psd(
|
| 611 |
+
self,
|
| 612 |
+
x: ArrayLike,
|
| 613 |
+
*,
|
| 614 |
+
NFFT: int | None = ...,
|
| 615 |
+
Fs: float | None = ...,
|
| 616 |
+
Fc: int | None = ...,
|
| 617 |
+
detrend: Literal["none", "mean", "linear"]
|
| 618 |
+
| Callable[[ArrayLike], ArrayLike]
|
| 619 |
+
| None = ...,
|
| 620 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 621 |
+
noverlap: int | None = ...,
|
| 622 |
+
pad_to: int | None = ...,
|
| 623 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 624 |
+
scale_by_freq: bool | None = ...,
|
| 625 |
+
return_line: bool | None = ...,
|
| 626 |
+
data=...,
|
| 627 |
+
**kwargs
|
| 628 |
+
) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
|
| 629 |
+
def csd(
|
| 630 |
+
self,
|
| 631 |
+
x: ArrayLike,
|
| 632 |
+
y: ArrayLike,
|
| 633 |
+
*,
|
| 634 |
+
NFFT: int | None = ...,
|
| 635 |
+
Fs: float | None = ...,
|
| 636 |
+
Fc: int | None = ...,
|
| 637 |
+
detrend: Literal["none", "mean", "linear"]
|
| 638 |
+
| Callable[[ArrayLike], ArrayLike]
|
| 639 |
+
| None = ...,
|
| 640 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 641 |
+
noverlap: int | None = ...,
|
| 642 |
+
pad_to: int | None = ...,
|
| 643 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 644 |
+
scale_by_freq: bool | None = ...,
|
| 645 |
+
return_line: bool | None = ...,
|
| 646 |
+
data=...,
|
| 647 |
+
**kwargs
|
| 648 |
+
) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
|
| 649 |
+
def magnitude_spectrum(
|
| 650 |
+
self,
|
| 651 |
+
x: ArrayLike,
|
| 652 |
+
*,
|
| 653 |
+
Fs: float | None = ...,
|
| 654 |
+
Fc: int | None = ...,
|
| 655 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 656 |
+
pad_to: int | None = ...,
|
| 657 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 658 |
+
scale: Literal["default", "linear", "dB"] | None = ...,
|
| 659 |
+
data=...,
|
| 660 |
+
**kwargs
|
| 661 |
+
) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
|
| 662 |
+
def angle_spectrum(
|
| 663 |
+
self,
|
| 664 |
+
x: ArrayLike,
|
| 665 |
+
*,
|
| 666 |
+
Fs: float | None = ...,
|
| 667 |
+
Fc: int | None = ...,
|
| 668 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 669 |
+
pad_to: int | None = ...,
|
| 670 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 671 |
+
data=...,
|
| 672 |
+
**kwargs
|
| 673 |
+
) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
|
| 674 |
+
def phase_spectrum(
|
| 675 |
+
self,
|
| 676 |
+
x: ArrayLike,
|
| 677 |
+
*,
|
| 678 |
+
Fs: float | None = ...,
|
| 679 |
+
Fc: int | None = ...,
|
| 680 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 681 |
+
pad_to: int | None = ...,
|
| 682 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 683 |
+
data=...,
|
| 684 |
+
**kwargs
|
| 685 |
+
) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
|
| 686 |
+
def cohere(
|
| 687 |
+
self,
|
| 688 |
+
x: ArrayLike,
|
| 689 |
+
y: ArrayLike,
|
| 690 |
+
*,
|
| 691 |
+
NFFT: int = ...,
|
| 692 |
+
Fs: float = ...,
|
| 693 |
+
Fc: int = ...,
|
| 694 |
+
detrend: Literal["none", "mean", "linear"]
|
| 695 |
+
| Callable[[ArrayLike], ArrayLike] = ...,
|
| 696 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ...,
|
| 697 |
+
noverlap: int = ...,
|
| 698 |
+
pad_to: int | None = ...,
|
| 699 |
+
sides: Literal["default", "onesided", "twosided"] = ...,
|
| 700 |
+
scale_by_freq: bool | None = ...,
|
| 701 |
+
data=...,
|
| 702 |
+
**kwargs
|
| 703 |
+
) -> tuple[np.ndarray, np.ndarray]: ...
|
| 704 |
+
def specgram(
|
| 705 |
+
self,
|
| 706 |
+
x: ArrayLike,
|
| 707 |
+
*,
|
| 708 |
+
NFFT: int | None = ...,
|
| 709 |
+
Fs: float | None = ...,
|
| 710 |
+
Fc: int | None = ...,
|
| 711 |
+
detrend: Literal["none", "mean", "linear"]
|
| 712 |
+
| Callable[[ArrayLike], ArrayLike]
|
| 713 |
+
| None = ...,
|
| 714 |
+
window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
|
| 715 |
+
noverlap: int | None = ...,
|
| 716 |
+
cmap: str | Colormap | None = ...,
|
| 717 |
+
xextent: tuple[float, float] | None = ...,
|
| 718 |
+
pad_to: int | None = ...,
|
| 719 |
+
sides: Literal["default", "onesided", "twosided"] | None = ...,
|
| 720 |
+
scale_by_freq: bool | None = ...,
|
| 721 |
+
mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ...,
|
| 722 |
+
scale: Literal["default", "linear", "dB"] | None = ...,
|
| 723 |
+
vmin: float | None = ...,
|
| 724 |
+
vmax: float | None = ...,
|
| 725 |
+
data=...,
|
| 726 |
+
**kwargs
|
| 727 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ...
|
| 728 |
+
def spy(
|
| 729 |
+
self,
|
| 730 |
+
Z: ArrayLike,
|
| 731 |
+
*,
|
| 732 |
+
precision: float | Literal["present"] = ...,
|
| 733 |
+
marker: str | None = ...,
|
| 734 |
+
markersize: float | None = ...,
|
| 735 |
+
aspect: Literal["equal", "auto"] | float | None = ...,
|
| 736 |
+
origin: Literal["upper", "lower"] = ...,
|
| 737 |
+
**kwargs
|
| 738 |
+
) -> AxesImage: ...
|
| 739 |
+
def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ...
|
| 740 |
+
def violinplot(
|
| 741 |
+
self,
|
| 742 |
+
dataset: ArrayLike | Sequence[ArrayLike],
|
| 743 |
+
positions: ArrayLike | None = ...,
|
| 744 |
+
*,
|
| 745 |
+
vert: bool | None = ...,
|
| 746 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 747 |
+
widths: float | ArrayLike = ...,
|
| 748 |
+
showmeans: bool = ...,
|
| 749 |
+
showextrema: bool = ...,
|
| 750 |
+
showmedians: bool = ...,
|
| 751 |
+
quantiles: Sequence[float | Sequence[float]] | None = ...,
|
| 752 |
+
points: int = ...,
|
| 753 |
+
bw_method: Literal["scott", "silverman"]
|
| 754 |
+
| float
|
| 755 |
+
| Callable[[GaussianKDE], float]
|
| 756 |
+
| None = ...,
|
| 757 |
+
side: Literal["both", "low", "high"] = ...,
|
| 758 |
+
data=...,
|
| 759 |
+
) -> dict[str, Collection]: ...
|
| 760 |
+
def violin(
|
| 761 |
+
self,
|
| 762 |
+
vpstats: Sequence[dict[str, Any]],
|
| 763 |
+
positions: ArrayLike | None = ...,
|
| 764 |
+
*,
|
| 765 |
+
vert: bool | None = ...,
|
| 766 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 767 |
+
widths: float | ArrayLike = ...,
|
| 768 |
+
showmeans: bool = ...,
|
| 769 |
+
showextrema: bool = ...,
|
| 770 |
+
showmedians: bool = ...,
|
| 771 |
+
side: Literal["both", "low", "high"] = ...,
|
| 772 |
+
) -> dict[str, Collection]: ...
|
| 773 |
+
|
| 774 |
+
table = mtable.table
|
| 775 |
+
stackplot = mstack.stackplot
|
| 776 |
+
streamplot = mstream.streamplot
|
| 777 |
+
tricontour = mtri.tricontour
|
| 778 |
+
tricontourf = mtri.tricontourf
|
| 779 |
+
tripcolor = mtri.tripcolor
|
| 780 |
+
triplot = mtri.triplot
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_base.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_base.pyi
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
| 1 |
+
import matplotlib.artist as martist
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
from collections.abc import Callable, Iterable, Iterator, Sequence
|
| 5 |
+
from matplotlib import cbook
|
| 6 |
+
from matplotlib.artist import Artist
|
| 7 |
+
from matplotlib.axes import Axes
|
| 8 |
+
from matplotlib.axis import XAxis, YAxis, Tick
|
| 9 |
+
from matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent
|
| 10 |
+
from matplotlib.cbook import CallbackRegistry
|
| 11 |
+
from matplotlib.container import Container
|
| 12 |
+
from matplotlib.collections import Collection
|
| 13 |
+
from matplotlib.colorizer import ColorizingArtist
|
| 14 |
+
from matplotlib.legend import Legend
|
| 15 |
+
from matplotlib.lines import Line2D
|
| 16 |
+
from matplotlib.gridspec import SubplotSpec, GridSpec
|
| 17 |
+
from matplotlib.figure import Figure, SubFigure
|
| 18 |
+
from matplotlib.image import AxesImage
|
| 19 |
+
from matplotlib.patches import Patch
|
| 20 |
+
from matplotlib.scale import ScaleBase
|
| 21 |
+
from matplotlib.spines import Spines
|
| 22 |
+
from matplotlib.table import Table
|
| 23 |
+
from matplotlib.text import Text
|
| 24 |
+
from matplotlib.transforms import Transform, Bbox
|
| 25 |
+
|
| 26 |
+
from cycler import Cycler
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
from numpy.typing import ArrayLike
|
| 30 |
+
from typing import Any, Literal, TypeVar, overload
|
| 31 |
+
from matplotlib.typing import ColorType
|
| 32 |
+
|
| 33 |
+
_T = TypeVar("_T", bound=Artist)
|
| 34 |
+
|
| 35 |
+
class _axis_method_wrapper:
|
| 36 |
+
attr_name: str
|
| 37 |
+
method_name: str
|
| 38 |
+
__doc__: str
|
| 39 |
+
def __init__(
|
| 40 |
+
self, attr_name: str, method_name: str, *, doc_sub: dict[str, str] | None = ...
|
| 41 |
+
) -> None: ...
|
| 42 |
+
def __set_name__(self, owner: Any, name: str) -> None: ...
|
| 43 |
+
|
| 44 |
+
class _AxesBase(martist.Artist):
|
| 45 |
+
name: str
|
| 46 |
+
patch: Patch
|
| 47 |
+
spines: Spines
|
| 48 |
+
fmt_xdata: Callable[[float], str] | None
|
| 49 |
+
fmt_ydata: Callable[[float], str] | None
|
| 50 |
+
xaxis: XAxis
|
| 51 |
+
yaxis: YAxis
|
| 52 |
+
bbox: Bbox
|
| 53 |
+
dataLim: Bbox
|
| 54 |
+
transAxes: Transform
|
| 55 |
+
transScale: Transform
|
| 56 |
+
transLimits: Transform
|
| 57 |
+
transData: Transform
|
| 58 |
+
ignore_existing_data_limits: bool
|
| 59 |
+
axison: bool
|
| 60 |
+
containers: list[Container]
|
| 61 |
+
callbacks: CallbackRegistry
|
| 62 |
+
child_axes: list[_AxesBase]
|
| 63 |
+
legend_: Legend | None
|
| 64 |
+
title: Text
|
| 65 |
+
_projection_init: Any
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
fig: Figure,
|
| 70 |
+
*args: tuple[float, float, float, float] | Bbox | int,
|
| 71 |
+
facecolor: ColorType | None = ...,
|
| 72 |
+
frameon: bool = ...,
|
| 73 |
+
sharex: _AxesBase | None = ...,
|
| 74 |
+
sharey: _AxesBase | None = ...,
|
| 75 |
+
label: Any = ...,
|
| 76 |
+
xscale: str | ScaleBase | None = ...,
|
| 77 |
+
yscale: str | ScaleBase | None = ...,
|
| 78 |
+
box_aspect: float | None = ...,
|
| 79 |
+
forward_navigation_events: bool | Literal["auto"] = ...,
|
| 80 |
+
**kwargs
|
| 81 |
+
) -> None: ...
|
| 82 |
+
def get_subplotspec(self) -> SubplotSpec | None: ...
|
| 83 |
+
def set_subplotspec(self, subplotspec: SubplotSpec) -> None: ...
|
| 84 |
+
def get_gridspec(self) -> GridSpec | None: ...
|
| 85 |
+
def set_figure(self, fig: Figure | SubFigure) -> None: ...
|
| 86 |
+
@property
|
| 87 |
+
def viewLim(self) -> Bbox: ...
|
| 88 |
+
def get_xaxis_transform(
|
| 89 |
+
self, which: Literal["grid", "tick1", "tick2"] = ...
|
| 90 |
+
) -> Transform: ...
|
| 91 |
+
def get_xaxis_text1_transform(
|
| 92 |
+
self, pad_points: float
|
| 93 |
+
) -> tuple[
|
| 94 |
+
Transform,
|
| 95 |
+
Literal["center", "top", "bottom", "baseline", "center_baseline"],
|
| 96 |
+
Literal["center", "left", "right"],
|
| 97 |
+
]: ...
|
| 98 |
+
def get_xaxis_text2_transform(
|
| 99 |
+
self, pad_points
|
| 100 |
+
) -> tuple[
|
| 101 |
+
Transform,
|
| 102 |
+
Literal["center", "top", "bottom", "baseline", "center_baseline"],
|
| 103 |
+
Literal["center", "left", "right"],
|
| 104 |
+
]: ...
|
| 105 |
+
def get_yaxis_transform(
|
| 106 |
+
self, which: Literal["grid", "tick1", "tick2"] = ...
|
| 107 |
+
) -> Transform: ...
|
| 108 |
+
def get_yaxis_text1_transform(
|
| 109 |
+
self, pad_points
|
| 110 |
+
) -> tuple[
|
| 111 |
+
Transform,
|
| 112 |
+
Literal["center", "top", "bottom", "baseline", "center_baseline"],
|
| 113 |
+
Literal["center", "left", "right"],
|
| 114 |
+
]: ...
|
| 115 |
+
def get_yaxis_text2_transform(
|
| 116 |
+
self, pad_points
|
| 117 |
+
) -> tuple[
|
| 118 |
+
Transform,
|
| 119 |
+
Literal["center", "top", "bottom", "baseline", "center_baseline"],
|
| 120 |
+
Literal["center", "left", "right"],
|
| 121 |
+
]: ...
|
| 122 |
+
def get_position(self, original: bool = ...) -> Bbox: ...
|
| 123 |
+
def set_position(
|
| 124 |
+
self,
|
| 125 |
+
pos: Bbox | tuple[float, float, float, float],
|
| 126 |
+
which: Literal["both", "active", "original"] = ...,
|
| 127 |
+
) -> None: ...
|
| 128 |
+
def reset_position(self) -> None: ...
|
| 129 |
+
def set_axes_locator(
|
| 130 |
+
self, locator: Callable[[_AxesBase, RendererBase], Bbox]
|
| 131 |
+
) -> None: ...
|
| 132 |
+
def get_axes_locator(self) -> Callable[[_AxesBase, RendererBase], Bbox]: ...
|
| 133 |
+
def sharex(self, other: _AxesBase) -> None: ...
|
| 134 |
+
def sharey(self, other: _AxesBase) -> None: ...
|
| 135 |
+
def clear(self) -> None: ...
|
| 136 |
+
def cla(self) -> None: ...
|
| 137 |
+
|
| 138 |
+
class ArtistList(Sequence[_T]):
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
axes: _AxesBase,
|
| 142 |
+
prop_name: str,
|
| 143 |
+
valid_types: type | Iterable[type] | None = ...,
|
| 144 |
+
invalid_types: type | Iterable[type] | None = ...,
|
| 145 |
+
) -> None: ...
|
| 146 |
+
def __len__(self) -> int: ...
|
| 147 |
+
def __iter__(self) -> Iterator[_T]: ...
|
| 148 |
+
@overload
|
| 149 |
+
def __getitem__(self, key: int) -> _T: ...
|
| 150 |
+
@overload
|
| 151 |
+
def __getitem__(self, key: slice) -> list[_T]: ...
|
| 152 |
+
|
| 153 |
+
@overload
|
| 154 |
+
def __add__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...
|
| 155 |
+
@overload
|
| 156 |
+
def __add__(self, other: list[Any]) -> list[Any]: ...
|
| 157 |
+
@overload
|
| 158 |
+
def __add__(self, other: tuple[Any]) -> tuple[Any]: ...
|
| 159 |
+
|
| 160 |
+
@overload
|
| 161 |
+
def __radd__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...
|
| 162 |
+
@overload
|
| 163 |
+
def __radd__(self, other: list[Any]) -> list[Any]: ...
|
| 164 |
+
@overload
|
| 165 |
+
def __radd__(self, other: tuple[Any]) -> tuple[Any]: ...
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def artists(self) -> _AxesBase.ArtistList[Artist]: ...
|
| 169 |
+
@property
|
| 170 |
+
def collections(self) -> _AxesBase.ArtistList[Collection]: ...
|
| 171 |
+
@property
|
| 172 |
+
def images(self) -> _AxesBase.ArtistList[AxesImage]: ...
|
| 173 |
+
@property
|
| 174 |
+
def lines(self) -> _AxesBase.ArtistList[Line2D]: ...
|
| 175 |
+
@property
|
| 176 |
+
def patches(self) -> _AxesBase.ArtistList[Patch]: ...
|
| 177 |
+
@property
|
| 178 |
+
def tables(self) -> _AxesBase.ArtistList[Table]: ...
|
| 179 |
+
@property
|
| 180 |
+
def texts(self) -> _AxesBase.ArtistList[Text]: ...
|
| 181 |
+
def get_facecolor(self) -> ColorType: ...
|
| 182 |
+
def set_facecolor(self, color: ColorType | None) -> None: ...
|
| 183 |
+
@overload
|
| 184 |
+
def set_prop_cycle(self, cycler: Cycler | None) -> None: ...
|
| 185 |
+
@overload
|
| 186 |
+
def set_prop_cycle(self, label: str, values: Iterable[Any]) -> None: ...
|
| 187 |
+
@overload
|
| 188 |
+
def set_prop_cycle(self, **kwargs: Iterable[Any]) -> None: ...
|
| 189 |
+
def get_aspect(self) -> float | Literal["auto"]: ...
|
| 190 |
+
def set_aspect(
|
| 191 |
+
self,
|
| 192 |
+
aspect: float | Literal["auto", "equal"],
|
| 193 |
+
adjustable: Literal["box", "datalim"] | None = ...,
|
| 194 |
+
anchor: str | tuple[float, float] | None = ...,
|
| 195 |
+
share: bool = ...,
|
| 196 |
+
) -> None: ...
|
| 197 |
+
def get_adjustable(self) -> Literal["box", "datalim"]: ...
|
| 198 |
+
def set_adjustable(
|
| 199 |
+
self, adjustable: Literal["box", "datalim"], share: bool = ...
|
| 200 |
+
) -> None: ...
|
| 201 |
+
def get_box_aspect(self) -> float | None: ...
|
| 202 |
+
def set_box_aspect(self, aspect: float | None = ...) -> None: ...
|
| 203 |
+
def get_anchor(self) -> str | tuple[float, float]: ...
|
| 204 |
+
def set_anchor(
|
| 205 |
+
self, anchor: str | tuple[float, float], share: bool = ...
|
| 206 |
+
) -> None: ...
|
| 207 |
+
def get_data_ratio(self) -> float: ...
|
| 208 |
+
def apply_aspect(self, position: Bbox | None = ...) -> None: ...
|
| 209 |
+
@overload
|
| 210 |
+
def axis(
|
| 211 |
+
self,
|
| 212 |
+
arg: tuple[float, float, float, float] | bool | str | None = ...,
|
| 213 |
+
/,
|
| 214 |
+
*,
|
| 215 |
+
emit: bool = ...
|
| 216 |
+
) -> tuple[float, float, float, float]: ...
|
| 217 |
+
@overload
|
| 218 |
+
def axis(
|
| 219 |
+
self,
|
| 220 |
+
*,
|
| 221 |
+
emit: bool = ...,
|
| 222 |
+
xmin: float | None = ...,
|
| 223 |
+
xmax: float | None = ...,
|
| 224 |
+
ymin: float | None = ...,
|
| 225 |
+
ymax: float | None = ...
|
| 226 |
+
) -> tuple[float, float, float, float]: ...
|
| 227 |
+
def get_legend(self) -> Legend | None: ...
|
| 228 |
+
def get_images(self) -> list[AxesImage]: ...
|
| 229 |
+
def get_lines(self) -> list[Line2D]: ...
|
| 230 |
+
def get_xaxis(self) -> XAxis: ...
|
| 231 |
+
def get_yaxis(self) -> YAxis: ...
|
| 232 |
+
def has_data(self) -> bool: ...
|
| 233 |
+
def add_artist(self, a: Artist) -> Artist: ...
|
| 234 |
+
def add_child_axes(self, ax: _AxesBase) -> _AxesBase: ...
|
| 235 |
+
def add_collection(
|
| 236 |
+
self, collection: Collection, autolim: bool = ...
|
| 237 |
+
) -> Collection: ...
|
| 238 |
+
def add_image(self, image: AxesImage) -> AxesImage: ...
|
| 239 |
+
def add_line(self, line: Line2D) -> Line2D: ...
|
| 240 |
+
def add_patch(self, p: Patch) -> Patch: ...
|
| 241 |
+
def add_table(self, tab: Table) -> Table: ...
|
| 242 |
+
def add_container(self, container: Container) -> Container: ...
|
| 243 |
+
def relim(self, visible_only: bool = ...) -> None: ...
|
| 244 |
+
def update_datalim(
|
| 245 |
+
self, xys: ArrayLike, updatex: bool = ..., updatey: bool = ...
|
| 246 |
+
) -> None: ...
|
| 247 |
+
def in_axes(self, mouseevent: MouseEvent) -> bool: ...
|
| 248 |
+
def get_autoscale_on(self) -> bool: ...
|
| 249 |
+
def set_autoscale_on(self, b: bool) -> None: ...
|
| 250 |
+
@property
|
| 251 |
+
def use_sticky_edges(self) -> bool: ...
|
| 252 |
+
@use_sticky_edges.setter
|
| 253 |
+
def use_sticky_edges(self, b: bool) -> None: ...
|
| 254 |
+
def get_xmargin(self) -> float: ...
|
| 255 |
+
def get_ymargin(self) -> float: ...
|
| 256 |
+
def set_xmargin(self, m: float) -> None: ...
|
| 257 |
+
def set_ymargin(self, m: float) -> None: ...
|
| 258 |
+
|
| 259 |
+
# Probably could be made better with overloads
|
| 260 |
+
def margins(
|
| 261 |
+
self,
|
| 262 |
+
*margins: float,
|
| 263 |
+
x: float | None = ...,
|
| 264 |
+
y: float | None = ...,
|
| 265 |
+
tight: bool | None = ...
|
| 266 |
+
) -> tuple[float, float] | None: ...
|
| 267 |
+
def set_rasterization_zorder(self, z: float | None) -> None: ...
|
| 268 |
+
def get_rasterization_zorder(self) -> float | None: ...
|
| 269 |
+
def autoscale(
|
| 270 |
+
self,
|
| 271 |
+
enable: bool = ...,
|
| 272 |
+
axis: Literal["both", "x", "y"] = ...,
|
| 273 |
+
tight: bool | None = ...,
|
| 274 |
+
) -> None: ...
|
| 275 |
+
def autoscale_view(
|
| 276 |
+
self, tight: bool | None = ..., scalex: bool = ..., scaley: bool = ...
|
| 277 |
+
) -> None: ...
|
| 278 |
+
def draw_artist(self, a: Artist) -> None: ...
|
| 279 |
+
def redraw_in_frame(self) -> None: ...
|
| 280 |
+
def get_frame_on(self) -> bool: ...
|
| 281 |
+
def set_frame_on(self, b: bool) -> None: ...
|
| 282 |
+
def get_axisbelow(self) -> bool | Literal["line"]: ...
|
| 283 |
+
def set_axisbelow(self, b: bool | Literal["line"]) -> None: ...
|
| 284 |
+
def grid(
|
| 285 |
+
self,
|
| 286 |
+
visible: bool | None = ...,
|
| 287 |
+
which: Literal["major", "minor", "both"] = ...,
|
| 288 |
+
axis: Literal["both", "x", "y"] = ...,
|
| 289 |
+
**kwargs
|
| 290 |
+
) -> None: ...
|
| 291 |
+
def ticklabel_format(
|
| 292 |
+
self,
|
| 293 |
+
*,
|
| 294 |
+
axis: Literal["both", "x", "y"] = ...,
|
| 295 |
+
style: Literal["", "sci", "scientific", "plain"] | None = ...,
|
| 296 |
+
scilimits: tuple[int, int] | None = ...,
|
| 297 |
+
useOffset: bool | float | None = ...,
|
| 298 |
+
useLocale: bool | None = ...,
|
| 299 |
+
useMathText: bool | None = ...
|
| 300 |
+
) -> None: ...
|
| 301 |
+
def locator_params(
|
| 302 |
+
self, axis: Literal["both", "x", "y"] = ..., tight: bool | None = ..., **kwargs
|
| 303 |
+
) -> None: ...
|
| 304 |
+
def tick_params(self, axis: Literal["both", "x", "y"] = ..., **kwargs) -> None: ...
|
| 305 |
+
def set_axis_off(self) -> None: ...
|
| 306 |
+
def set_axis_on(self) -> None: ...
|
| 307 |
+
def get_xlabel(self) -> str: ...
|
| 308 |
+
def set_xlabel(
|
| 309 |
+
self,
|
| 310 |
+
xlabel: str,
|
| 311 |
+
fontdict: dict[str, Any] | None = ...,
|
| 312 |
+
labelpad: float | None = ...,
|
| 313 |
+
*,
|
| 314 |
+
loc: Literal["left", "center", "right"] | None = ...,
|
| 315 |
+
**kwargs
|
| 316 |
+
) -> Text: ...
|
| 317 |
+
def invert_xaxis(self) -> None: ...
|
| 318 |
+
def get_xbound(self) -> tuple[float, float]: ...
|
| 319 |
+
def set_xbound(
|
| 320 |
+
self, lower: float | None = ..., upper: float | None = ...
|
| 321 |
+
) -> None: ...
|
| 322 |
+
def get_xlim(self) -> tuple[float, float]: ...
|
| 323 |
+
def set_xlim(
|
| 324 |
+
self,
|
| 325 |
+
left: float | tuple[float, float] | None = ...,
|
| 326 |
+
right: float | None = ...,
|
| 327 |
+
*,
|
| 328 |
+
emit: bool = ...,
|
| 329 |
+
auto: bool | None = ...,
|
| 330 |
+
xmin: float | None = ...,
|
| 331 |
+
xmax: float | None = ...
|
| 332 |
+
) -> tuple[float, float]: ...
|
| 333 |
+
def get_ylabel(self) -> str: ...
|
| 334 |
+
def set_ylabel(
|
| 335 |
+
self,
|
| 336 |
+
ylabel: str,
|
| 337 |
+
fontdict: dict[str, Any] | None = ...,
|
| 338 |
+
labelpad: float | None = ...,
|
| 339 |
+
*,
|
| 340 |
+
loc: Literal["bottom", "center", "top"] | None = ...,
|
| 341 |
+
**kwargs
|
| 342 |
+
) -> Text: ...
|
| 343 |
+
def invert_yaxis(self) -> None: ...
|
| 344 |
+
def get_ybound(self) -> tuple[float, float]: ...
|
| 345 |
+
def set_ybound(
|
| 346 |
+
self, lower: float | None = ..., upper: float | None = ...
|
| 347 |
+
) -> None: ...
|
| 348 |
+
def get_ylim(self) -> tuple[float, float]: ...
|
| 349 |
+
def set_ylim(
|
| 350 |
+
self,
|
| 351 |
+
bottom: float | tuple[float, float] | None = ...,
|
| 352 |
+
top: float | None = ...,
|
| 353 |
+
*,
|
| 354 |
+
emit: bool = ...,
|
| 355 |
+
auto: bool | None = ...,
|
| 356 |
+
ymin: float | None = ...,
|
| 357 |
+
ymax: float | None = ...
|
| 358 |
+
) -> tuple[float, float]: ...
|
| 359 |
+
def format_xdata(self, x: float) -> str: ...
|
| 360 |
+
def format_ydata(self, y: float) -> str: ...
|
| 361 |
+
def format_coord(self, x: float, y: float) -> str: ...
|
| 362 |
+
def minorticks_on(self) -> None: ...
|
| 363 |
+
def minorticks_off(self) -> None: ...
|
| 364 |
+
def can_zoom(self) -> bool: ...
|
| 365 |
+
def can_pan(self) -> bool: ...
|
| 366 |
+
def get_navigate(self) -> bool: ...
|
| 367 |
+
def set_navigate(self, b: bool) -> None: ...
|
| 368 |
+
def get_forward_navigation_events(self) -> bool | Literal["auto"]: ...
|
| 369 |
+
def set_forward_navigation_events(self, forward: bool | Literal["auto"]) -> None: ...
|
| 370 |
+
def get_navigate_mode(self) -> Literal["PAN", "ZOOM"] | None: ...
|
| 371 |
+
def set_navigate_mode(self, b: Literal["PAN", "ZOOM"] | None) -> None: ...
|
| 372 |
+
def start_pan(self, x: float, y: float, button: MouseButton) -> None: ...
|
| 373 |
+
def end_pan(self) -> None: ...
|
| 374 |
+
def drag_pan(
|
| 375 |
+
self, button: MouseButton, key: str | None, x: float, y: float
|
| 376 |
+
) -> None: ...
|
| 377 |
+
def get_children(self) -> list[Artist]: ...
|
| 378 |
+
def contains_point(self, point: tuple[int, int]) -> bool: ...
|
| 379 |
+
def get_default_bbox_extra_artists(self) -> list[Artist]: ...
|
| 380 |
+
def get_tightbbox(
|
| 381 |
+
self,
|
| 382 |
+
renderer: RendererBase | None = ...,
|
| 383 |
+
*,
|
| 384 |
+
call_axes_locator: bool = ...,
|
| 385 |
+
bbox_extra_artists: Sequence[Artist] | None = ...,
|
| 386 |
+
for_layout_only: bool = ...
|
| 387 |
+
) -> Bbox | None: ...
|
| 388 |
+
def twinx(self) -> Axes: ...
|
| 389 |
+
def twiny(self) -> Axes: ...
|
| 390 |
+
def get_shared_x_axes(self) -> cbook.GrouperView: ...
|
| 391 |
+
def get_shared_y_axes(self) -> cbook.GrouperView: ...
|
| 392 |
+
def label_outer(self, remove_inner_ticks: bool = ...) -> None: ...
|
| 393 |
+
|
| 394 |
+
# The methods underneath this line are added via the `_axis_method_wrapper` class
|
| 395 |
+
# Initially they are set to an object, but that object uses `__set_name__` to override
|
| 396 |
+
# itself with a method modified from the Axis methods for the x or y Axis.
|
| 397 |
+
# As such, they are typed according to the resultant method rather than as that object.
|
| 398 |
+
|
| 399 |
+
def get_xgridlines(self) -> list[Line2D]: ...
|
| 400 |
+
def get_xticklines(self, minor: bool = ...) -> list[Line2D]: ...
|
| 401 |
+
def get_ygridlines(self) -> list[Line2D]: ...
|
| 402 |
+
def get_yticklines(self, minor: bool = ...) -> list[Line2D]: ...
|
| 403 |
+
def _sci(self, im: ColorizingArtist) -> None: ...
|
| 404 |
+
def get_autoscalex_on(self) -> bool: ...
|
| 405 |
+
def get_autoscaley_on(self) -> bool: ...
|
| 406 |
+
def set_autoscalex_on(self, b: bool) -> None: ...
|
| 407 |
+
def set_autoscaley_on(self, b: bool) -> None: ...
|
| 408 |
+
def xaxis_inverted(self) -> bool: ...
|
| 409 |
+
def get_xscale(self) -> str: ...
|
| 410 |
+
def set_xscale(self, value: str | ScaleBase, **kwargs) -> None: ...
|
| 411 |
+
def get_xticks(self, *, minor: bool = ...) -> np.ndarray: ...
|
| 412 |
+
def set_xticks(
|
| 413 |
+
self,
|
| 414 |
+
ticks: ArrayLike,
|
| 415 |
+
labels: Iterable[str] | None = ...,
|
| 416 |
+
*,
|
| 417 |
+
minor: bool = ...,
|
| 418 |
+
**kwargs
|
| 419 |
+
) -> list[Tick]: ...
|
| 420 |
+
def get_xmajorticklabels(self) -> list[Text]: ...
|
| 421 |
+
def get_xminorticklabels(self) -> list[Text]: ...
|
| 422 |
+
def get_xticklabels(
|
| 423 |
+
self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
|
| 424 |
+
) -> list[Text]: ...
|
| 425 |
+
def set_xticklabels(
|
| 426 |
+
self,
|
| 427 |
+
labels: Iterable[str | Text],
|
| 428 |
+
*,
|
| 429 |
+
minor: bool = ...,
|
| 430 |
+
fontdict: dict[str, Any] | None = ...,
|
| 431 |
+
**kwargs
|
| 432 |
+
) -> list[Text]: ...
|
| 433 |
+
def yaxis_inverted(self) -> bool: ...
|
| 434 |
+
def get_yscale(self) -> str: ...
|
| 435 |
+
def set_yscale(self, value: str | ScaleBase, **kwargs) -> None: ...
|
| 436 |
+
def get_yticks(self, *, minor: bool = ...) -> np.ndarray: ...
|
| 437 |
+
def set_yticks(
|
| 438 |
+
self,
|
| 439 |
+
ticks: ArrayLike,
|
| 440 |
+
labels: Iterable[str] | None = ...,
|
| 441 |
+
*,
|
| 442 |
+
minor: bool = ...,
|
| 443 |
+
**kwargs
|
| 444 |
+
) -> list[Tick]: ...
|
| 445 |
+
def get_ymajorticklabels(self) -> list[Text]: ...
|
| 446 |
+
def get_yminorticklabels(self) -> list[Text]: ...
|
| 447 |
+
def get_yticklabels(
|
| 448 |
+
self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
|
| 449 |
+
) -> list[Text]: ...
|
| 450 |
+
def set_yticklabels(
|
| 451 |
+
self,
|
| 452 |
+
labels: Iterable[str | Text],
|
| 453 |
+
*,
|
| 454 |
+
minor: bool = ...,
|
| 455 |
+
fontdict: dict[str, Any] | None = ...,
|
| 456 |
+
**kwargs
|
| 457 |
+
) -> list[Text]: ...
|
| 458 |
+
def xaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
|
| 459 |
+
def yaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numbers
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from matplotlib import _api, _docstring, transforms
|
| 6 |
+
import matplotlib.ticker as mticker
|
| 7 |
+
from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator
|
| 8 |
+
from matplotlib.axis import Axis
|
| 9 |
+
from matplotlib.transforms import Transform
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SecondaryAxis(_AxesBase):
|
| 13 |
+
"""
|
| 14 |
+
General class to hold a Secondary_X/Yaxis.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, parent, orientation, location, functions, transform=None,
|
| 18 |
+
**kwargs):
|
| 19 |
+
"""
|
| 20 |
+
See `.secondary_xaxis` and `.secondary_yaxis` for the doc string.
|
| 21 |
+
While there is no need for this to be private, it should really be
|
| 22 |
+
called by those higher level functions.
|
| 23 |
+
"""
|
| 24 |
+
_api.check_in_list(["x", "y"], orientation=orientation)
|
| 25 |
+
self._functions = functions
|
| 26 |
+
self._parent = parent
|
| 27 |
+
self._orientation = orientation
|
| 28 |
+
self._ticks_set = False
|
| 29 |
+
|
| 30 |
+
fig = self._parent.get_figure(root=False)
|
| 31 |
+
if self._orientation == 'x':
|
| 32 |
+
super().__init__(fig, [0, 1., 1, 0.0001], **kwargs)
|
| 33 |
+
self._axis = self.xaxis
|
| 34 |
+
self._locstrings = ['top', 'bottom']
|
| 35 |
+
self._otherstrings = ['left', 'right']
|
| 36 |
+
else: # 'y'
|
| 37 |
+
super().__init__(fig, [0, 1., 0.0001, 1], **kwargs)
|
| 38 |
+
self._axis = self.yaxis
|
| 39 |
+
self._locstrings = ['right', 'left']
|
| 40 |
+
self._otherstrings = ['top', 'bottom']
|
| 41 |
+
self._parentscale = None
|
| 42 |
+
# this gets positioned w/o constrained_layout so exclude:
|
| 43 |
+
|
| 44 |
+
self.set_location(location, transform)
|
| 45 |
+
self.set_functions(functions)
|
| 46 |
+
|
| 47 |
+
# styling:
|
| 48 |
+
otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis
|
| 49 |
+
otheraxis.set_major_locator(mticker.NullLocator())
|
| 50 |
+
otheraxis.set_ticks_position('none')
|
| 51 |
+
|
| 52 |
+
self.spines[self._otherstrings].set_visible(False)
|
| 53 |
+
self.spines[self._locstrings].set_visible(True)
|
| 54 |
+
|
| 55 |
+
if self._pos < 0.5:
|
| 56 |
+
# flip the location strings...
|
| 57 |
+
self._locstrings = self._locstrings[::-1]
|
| 58 |
+
self.set_alignment(self._locstrings[0])
|
| 59 |
+
|
| 60 |
+
def set_alignment(self, align):
|
| 61 |
+
"""
|
| 62 |
+
Set if axes spine and labels are drawn at top or bottom (or left/right)
|
| 63 |
+
of the Axes.
|
| 64 |
+
|
| 65 |
+
Parameters
|
| 66 |
+
----------
|
| 67 |
+
align : {'top', 'bottom', 'left', 'right'}
|
| 68 |
+
Either 'top' or 'bottom' for orientation='x' or
|
| 69 |
+
'left' or 'right' for orientation='y' axis.
|
| 70 |
+
"""
|
| 71 |
+
_api.check_in_list(self._locstrings, align=align)
|
| 72 |
+
if align == self._locstrings[1]: # Need to change the orientation.
|
| 73 |
+
self._locstrings = self._locstrings[::-1]
|
| 74 |
+
self.spines[self._locstrings[0]].set_visible(True)
|
| 75 |
+
self.spines[self._locstrings[1]].set_visible(False)
|
| 76 |
+
self._axis.set_ticks_position(align)
|
| 77 |
+
self._axis.set_label_position(align)
|
| 78 |
+
|
| 79 |
+
def set_location(self, location, transform=None):
|
| 80 |
+
"""
|
| 81 |
+
Set the vertical or horizontal location of the axes in
|
| 82 |
+
parent-normalized coordinates.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
location : {'top', 'bottom', 'left', 'right'} or float
|
| 87 |
+
The position to put the secondary axis. Strings can be 'top' or
|
| 88 |
+
'bottom' for orientation='x' and 'right' or 'left' for
|
| 89 |
+
orientation='y'. A float indicates the relative position on the
|
| 90 |
+
parent Axes to put the new Axes, 0.0 being the bottom (or left)
|
| 91 |
+
and 1.0 being the top (or right).
|
| 92 |
+
|
| 93 |
+
transform : `.Transform`, optional
|
| 94 |
+
Transform for the location to use. Defaults to
|
| 95 |
+
the parent's ``transAxes``, so locations are normally relative to
|
| 96 |
+
the parent axes.
|
| 97 |
+
|
| 98 |
+
.. versionadded:: 3.9
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
_api.check_isinstance((transforms.Transform, None), transform=transform)
|
| 102 |
+
|
| 103 |
+
# This puts the rectangle into figure-relative coordinates.
|
| 104 |
+
if isinstance(location, str):
|
| 105 |
+
_api.check_in_list(self._locstrings, location=location)
|
| 106 |
+
self._pos = 1. if location in ('top', 'right') else 0.
|
| 107 |
+
elif isinstance(location, numbers.Real):
|
| 108 |
+
self._pos = location
|
| 109 |
+
else:
|
| 110 |
+
raise ValueError(
|
| 111 |
+
f"location must be {self._locstrings[0]!r}, "
|
| 112 |
+
f"{self._locstrings[1]!r}, or a float, not {location!r}")
|
| 113 |
+
|
| 114 |
+
self._loc = location
|
| 115 |
+
|
| 116 |
+
if self._orientation == 'x':
|
| 117 |
+
# An x-secondary axes is like an inset axes from x = 0 to x = 1 and
|
| 118 |
+
# from y = pos to y = pos + eps, in the parent's transAxes coords.
|
| 119 |
+
bounds = [0, self._pos, 1., 1e-10]
|
| 120 |
+
|
| 121 |
+
# If a transformation is provided, use its y component rather than
|
| 122 |
+
# the parent's transAxes. This can be used to place axes in the data
|
| 123 |
+
# coords, for instance.
|
| 124 |
+
if transform is not None:
|
| 125 |
+
transform = transforms.blended_transform_factory(
|
| 126 |
+
self._parent.transAxes, transform)
|
| 127 |
+
else: # 'y'
|
| 128 |
+
bounds = [self._pos, 0, 1e-10, 1]
|
| 129 |
+
if transform is not None:
|
| 130 |
+
transform = transforms.blended_transform_factory(
|
| 131 |
+
transform, self._parent.transAxes) # Use provided x axis
|
| 132 |
+
|
| 133 |
+
# If no transform is provided, use the parent's transAxes
|
| 134 |
+
if transform is None:
|
| 135 |
+
transform = self._parent.transAxes
|
| 136 |
+
|
| 137 |
+
# this locator lets the axes move in the parent axes coordinates.
|
| 138 |
+
# so it never needs to know where the parent is explicitly in
|
| 139 |
+
# figure coordinates.
|
| 140 |
+
# it gets called in ax.apply_aspect() (of all places)
|
| 141 |
+
self.set_axes_locator(_TransformedBoundsLocator(bounds, transform))
|
| 142 |
+
|
| 143 |
+
def apply_aspect(self, position=None):
|
| 144 |
+
# docstring inherited.
|
| 145 |
+
self._set_lims()
|
| 146 |
+
super().apply_aspect(position)
|
| 147 |
+
|
| 148 |
+
@_docstring.copy(Axis.set_ticks)
|
| 149 |
+
def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
|
| 150 |
+
ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs)
|
| 151 |
+
self.stale = True
|
| 152 |
+
self._ticks_set = True
|
| 153 |
+
return ret
|
| 154 |
+
|
| 155 |
+
def set_functions(self, functions):
|
| 156 |
+
"""
|
| 157 |
+
Set how the secondary axis converts limits from the parent Axes.
|
| 158 |
+
|
| 159 |
+
Parameters
|
| 160 |
+
----------
|
| 161 |
+
functions : 2-tuple of func, or `Transform` with an inverse.
|
| 162 |
+
Transform between the parent axis values and the secondary axis
|
| 163 |
+
values.
|
| 164 |
+
|
| 165 |
+
If supplied as a 2-tuple of functions, the first function is
|
| 166 |
+
the forward transform function and the second is the inverse
|
| 167 |
+
transform.
|
| 168 |
+
|
| 169 |
+
If a transform is supplied, then the transform must have an
|
| 170 |
+
inverse.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
if (isinstance(functions, tuple) and len(functions) == 2 and
|
| 174 |
+
callable(functions[0]) and callable(functions[1])):
|
| 175 |
+
# make an arbitrary convert from a two-tuple of functions
|
| 176 |
+
# forward and inverse.
|
| 177 |
+
self._functions = functions
|
| 178 |
+
elif isinstance(functions, Transform):
|
| 179 |
+
self._functions = (
|
| 180 |
+
functions.transform,
|
| 181 |
+
lambda x: functions.inverted().transform(x)
|
| 182 |
+
)
|
| 183 |
+
elif functions is None:
|
| 184 |
+
self._functions = (lambda x: x, lambda x: x)
|
| 185 |
+
else:
|
| 186 |
+
raise ValueError('functions argument of secondary Axes '
|
| 187 |
+
'must be a two-tuple of callable functions '
|
| 188 |
+
'with the first function being the transform '
|
| 189 |
+
'and the second being the inverse')
|
| 190 |
+
self._set_scale()
|
| 191 |
+
|
| 192 |
+
def draw(self, renderer):
|
| 193 |
+
"""
|
| 194 |
+
Draw the secondary Axes.
|
| 195 |
+
|
| 196 |
+
Consults the parent Axes for its limits and converts them
|
| 197 |
+
using the converter specified by
|
| 198 |
+
`~.axes._secondary_axes.set_functions` (or *functions*
|
| 199 |
+
parameter when Axes initialized.)
|
| 200 |
+
"""
|
| 201 |
+
self._set_lims()
|
| 202 |
+
# this sets the scale in case the parent has set its scale.
|
| 203 |
+
self._set_scale()
|
| 204 |
+
super().draw(renderer)
|
| 205 |
+
|
| 206 |
+
def _set_scale(self):
|
| 207 |
+
"""
|
| 208 |
+
Check if parent has set its scale
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
if self._orientation == 'x':
|
| 212 |
+
pscale = self._parent.xaxis.get_scale()
|
| 213 |
+
set_scale = self.set_xscale
|
| 214 |
+
else: # 'y'
|
| 215 |
+
pscale = self._parent.yaxis.get_scale()
|
| 216 |
+
set_scale = self.set_yscale
|
| 217 |
+
if pscale == self._parentscale:
|
| 218 |
+
return
|
| 219 |
+
|
| 220 |
+
if self._ticks_set:
|
| 221 |
+
ticks = self._axis.get_ticklocs()
|
| 222 |
+
|
| 223 |
+
# need to invert the roles here for the ticks to line up.
|
| 224 |
+
set_scale('functionlog' if pscale == 'log' else 'function',
|
| 225 |
+
functions=self._functions[::-1])
|
| 226 |
+
|
| 227 |
+
# OK, set_scale sets the locators, but if we've called
|
| 228 |
+
# axsecond.set_ticks, we want to keep those.
|
| 229 |
+
if self._ticks_set:
|
| 230 |
+
self._axis.set_major_locator(mticker.FixedLocator(ticks))
|
| 231 |
+
|
| 232 |
+
# If the parent scale doesn't change, we can skip this next time.
|
| 233 |
+
self._parentscale = pscale
|
| 234 |
+
|
| 235 |
+
def _set_lims(self):
|
| 236 |
+
"""
|
| 237 |
+
Set the limits based on parent limits and the convert method
|
| 238 |
+
between the parent and this secondary Axes.
|
| 239 |
+
"""
|
| 240 |
+
if self._orientation == 'x':
|
| 241 |
+
lims = self._parent.get_xlim()
|
| 242 |
+
set_lim = self.set_xlim
|
| 243 |
+
else: # 'y'
|
| 244 |
+
lims = self._parent.get_ylim()
|
| 245 |
+
set_lim = self.set_ylim
|
| 246 |
+
order = lims[0] < lims[1]
|
| 247 |
+
lims = self._functions[0](np.array(lims))
|
| 248 |
+
neworder = lims[0] < lims[1]
|
| 249 |
+
if neworder != order:
|
| 250 |
+
# Flip because the transform will take care of the flipping.
|
| 251 |
+
lims = lims[::-1]
|
| 252 |
+
set_lim(lims)
|
| 253 |
+
|
| 254 |
+
def set_aspect(self, *args, **kwargs):
|
| 255 |
+
"""
|
| 256 |
+
Secondary Axes cannot set the aspect ratio, so calling this just
|
| 257 |
+
sets a warning.
|
| 258 |
+
"""
|
| 259 |
+
_api.warn_external("Secondary Axes can't set the aspect ratio")
|
| 260 |
+
|
| 261 |
+
def set_color(self, color):
|
| 262 |
+
"""
|
| 263 |
+
Change the color of the secondary Axes and all decorators.
|
| 264 |
+
|
| 265 |
+
Parameters
|
| 266 |
+
----------
|
| 267 |
+
color : :mpltype:`color`
|
| 268 |
+
"""
|
| 269 |
+
axis = self._axis_map[self._orientation]
|
| 270 |
+
axis.set_tick_params(colors=color)
|
| 271 |
+
for spine in self.spines.values():
|
| 272 |
+
if spine.axis is axis:
|
| 273 |
+
spine.set_color(color)
|
| 274 |
+
axis.label.set_color(color)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
_secax_docstring = '''
|
| 278 |
+
Warnings
|
| 279 |
+
--------
|
| 280 |
+
This method is experimental as of 3.1, and the API may change.
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
----------
|
| 284 |
+
location : {'top', 'bottom', 'left', 'right'} or float
|
| 285 |
+
The position to put the secondary axis. Strings can be 'top' or
|
| 286 |
+
'bottom' for orientation='x' and 'right' or 'left' for
|
| 287 |
+
orientation='y'. A float indicates the relative position on the
|
| 288 |
+
parent Axes to put the new Axes, 0.0 being the bottom (or left)
|
| 289 |
+
and 1.0 being the top (or right).
|
| 290 |
+
|
| 291 |
+
functions : 2-tuple of func, or Transform with an inverse
|
| 292 |
+
|
| 293 |
+
If a 2-tuple of functions, the user specifies the transform
|
| 294 |
+
function and its inverse. i.e.
|
| 295 |
+
``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an
|
| 296 |
+
reciprocal transform with a factor of 2. Both functions must accept
|
| 297 |
+
numpy arrays as input.
|
| 298 |
+
|
| 299 |
+
The user can also directly supply a subclass of
|
| 300 |
+
`.transforms.Transform` so long as it has an inverse.
|
| 301 |
+
|
| 302 |
+
See :doc:`/gallery/subplots_axes_and_figures/secondary_axis`
|
| 303 |
+
for examples of making these conversions.
|
| 304 |
+
|
| 305 |
+
transform : `.Transform`, optional
|
| 306 |
+
If specified, *location* will be
|
| 307 |
+
placed relative to this transform (in the direction of the axis)
|
| 308 |
+
rather than the parent's axis. i.e. a secondary x-axis will
|
| 309 |
+
use the provided y transform and the x transform of the parent.
|
| 310 |
+
|
| 311 |
+
.. versionadded:: 3.9
|
| 312 |
+
|
| 313 |
+
Returns
|
| 314 |
+
-------
|
| 315 |
+
ax : axes._secondary_axes.SecondaryAxis
|
| 316 |
+
|
| 317 |
+
Other Parameters
|
| 318 |
+
----------------
|
| 319 |
+
**kwargs : `~matplotlib.axes.Axes` properties.
|
| 320 |
+
Other miscellaneous Axes parameters.
|
| 321 |
+
'''
|
| 322 |
+
_docstring.interpd.register(_secax_docstring=_secax_docstring)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.pyi
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib.axes._base import _AxesBase
|
| 2 |
+
from matplotlib.axis import Tick
|
| 3 |
+
|
| 4 |
+
from matplotlib.transforms import Transform
|
| 5 |
+
|
| 6 |
+
from collections.abc import Callable, Iterable
|
| 7 |
+
from typing import Literal
|
| 8 |
+
from numpy.typing import ArrayLike
|
| 9 |
+
from matplotlib.typing import ColorType
|
| 10 |
+
|
| 11 |
+
class SecondaryAxis(_AxesBase):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
parent: _AxesBase,
|
| 15 |
+
orientation: Literal["x", "y"],
|
| 16 |
+
location: Literal["top", "bottom", "right", "left"] | float,
|
| 17 |
+
functions: tuple[
|
| 18 |
+
Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
|
| 19 |
+
]
|
| 20 |
+
| Transform,
|
| 21 |
+
transform: Transform | None = ...,
|
| 22 |
+
**kwargs
|
| 23 |
+
) -> None: ...
|
| 24 |
+
def set_alignment(
|
| 25 |
+
self, align: Literal["top", "bottom", "right", "left"]
|
| 26 |
+
) -> None: ...
|
| 27 |
+
def set_location(
|
| 28 |
+
self,
|
| 29 |
+
location: Literal["top", "bottom", "right", "left"] | float,
|
| 30 |
+
transform: Transform | None = ...
|
| 31 |
+
) -> None: ...
|
| 32 |
+
def set_ticks(
|
| 33 |
+
self,
|
| 34 |
+
ticks: ArrayLike,
|
| 35 |
+
labels: Iterable[str] | None = ...,
|
| 36 |
+
*,
|
| 37 |
+
minor: bool = ...,
|
| 38 |
+
**kwargs
|
| 39 |
+
) -> list[Tick]: ...
|
| 40 |
+
def set_functions(
|
| 41 |
+
self,
|
| 42 |
+
functions: tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] | Transform,
|
| 43 |
+
) -> None: ...
|
| 44 |
+
def set_aspect(self, *args, **kwargs) -> None: ...
|
| 45 |
+
def set_color(self, color: ColorType) -> None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axis.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/axis.pyi
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 2 |
+
import datetime
|
| 3 |
+
from typing import Any, Literal, overload
|
| 4 |
+
from typing_extensions import Self # < Py 3.11
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from numpy.typing import ArrayLike
|
| 8 |
+
|
| 9 |
+
import matplotlib.artist as martist
|
| 10 |
+
from matplotlib import cbook
|
| 11 |
+
from matplotlib.axes import Axes
|
| 12 |
+
from matplotlib.backend_bases import RendererBase
|
| 13 |
+
from matplotlib.lines import Line2D
|
| 14 |
+
from matplotlib.text import Text
|
| 15 |
+
from matplotlib.ticker import Locator, Formatter
|
| 16 |
+
from matplotlib.transforms import Transform, Bbox
|
| 17 |
+
from matplotlib.typing import ColorType
|
| 18 |
+
from matplotlib.units import ConversionInterface
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
GRIDLINE_INTERPOLATION_STEPS: int
|
| 22 |
+
|
| 23 |
+
class Tick(martist.Artist):
|
| 24 |
+
axes: Axes
|
| 25 |
+
tick1line: Line2D
|
| 26 |
+
tick2line: Line2D
|
| 27 |
+
gridline: Line2D
|
| 28 |
+
label1: Text
|
| 29 |
+
label2: Text
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
axes: Axes,
|
| 33 |
+
loc: float,
|
| 34 |
+
*,
|
| 35 |
+
size: float | None = ...,
|
| 36 |
+
width: float | None = ...,
|
| 37 |
+
color: ColorType | None = ...,
|
| 38 |
+
tickdir: Literal["in", "inout", "out"] | None = ...,
|
| 39 |
+
pad: float | None = ...,
|
| 40 |
+
labelsize: float | None = ...,
|
| 41 |
+
labelcolor: ColorType | None = ...,
|
| 42 |
+
labelfontfamily: str | Sequence[str] | None = ...,
|
| 43 |
+
zorder: float | None = ...,
|
| 44 |
+
gridOn: bool | None = ...,
|
| 45 |
+
tick1On: bool = ...,
|
| 46 |
+
tick2On: bool = ...,
|
| 47 |
+
label1On: bool = ...,
|
| 48 |
+
label2On: bool = ...,
|
| 49 |
+
major: bool = ...,
|
| 50 |
+
labelrotation: float = ...,
|
| 51 |
+
grid_color: ColorType | None = ...,
|
| 52 |
+
grid_linestyle: str | None = ...,
|
| 53 |
+
grid_linewidth: float | None = ...,
|
| 54 |
+
grid_alpha: float | None = ...,
|
| 55 |
+
**kwargs
|
| 56 |
+
) -> None: ...
|
| 57 |
+
def get_tickdir(self) -> Literal["in", "inout", "out"]: ...
|
| 58 |
+
def get_tick_padding(self) -> float: ...
|
| 59 |
+
def get_children(self) -> list[martist.Artist]: ...
|
| 60 |
+
stale: bool
|
| 61 |
+
def set_pad(self, val: float) -> None: ...
|
| 62 |
+
def get_pad(self) -> None: ...
|
| 63 |
+
def get_loc(self) -> float: ...
|
| 64 |
+
def set_url(self, url: str | None) -> None: ...
|
| 65 |
+
def get_view_interval(self) -> ArrayLike: ...
|
| 66 |
+
def update_position(self, loc: float) -> None: ...
|
| 67 |
+
|
| 68 |
+
class XTick(Tick):
|
| 69 |
+
__name__: str
|
| 70 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 71 |
+
stale: bool
|
| 72 |
+
def update_position(self, loc: float) -> None: ...
|
| 73 |
+
def get_view_interval(self) -> np.ndarray: ...
|
| 74 |
+
|
| 75 |
+
class YTick(Tick):
|
| 76 |
+
__name__: str
|
| 77 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 78 |
+
stale: bool
|
| 79 |
+
def update_position(self, loc: float) -> None: ...
|
| 80 |
+
def get_view_interval(self) -> np.ndarray: ...
|
| 81 |
+
|
| 82 |
+
class Ticker:
|
| 83 |
+
def __init__(self) -> None: ...
|
| 84 |
+
@property
|
| 85 |
+
def locator(self) -> Locator | None: ...
|
| 86 |
+
@locator.setter
|
| 87 |
+
def locator(self, locator: Locator) -> None: ...
|
| 88 |
+
@property
|
| 89 |
+
def formatter(self) -> Formatter | None: ...
|
| 90 |
+
@formatter.setter
|
| 91 |
+
def formatter(self, formatter: Formatter) -> None: ...
|
| 92 |
+
|
| 93 |
+
class _LazyTickList:
|
| 94 |
+
def __init__(self, major: bool) -> None: ...
|
| 95 |
+
@overload
|
| 96 |
+
def __get__(self, instance: None, owner: None) -> Self: ...
|
| 97 |
+
@overload
|
| 98 |
+
def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ...
|
| 99 |
+
|
| 100 |
+
class Axis(martist.Artist):
|
| 101 |
+
OFFSETTEXTPAD: int
|
| 102 |
+
isDefault_label: bool
|
| 103 |
+
axes: Axes
|
| 104 |
+
major: Ticker
|
| 105 |
+
minor: Ticker
|
| 106 |
+
callbacks: cbook.CallbackRegistry
|
| 107 |
+
label: Text
|
| 108 |
+
offsetText: Text
|
| 109 |
+
labelpad: float
|
| 110 |
+
pickradius: float
|
| 111 |
+
def __init__(self, axes, *, pickradius: float = ...,
|
| 112 |
+
clear: bool = ...) -> None: ...
|
| 113 |
+
@property
|
| 114 |
+
def isDefault_majloc(self) -> bool: ...
|
| 115 |
+
@isDefault_majloc.setter
|
| 116 |
+
def isDefault_majloc(self, value: bool) -> None: ...
|
| 117 |
+
@property
|
| 118 |
+
def isDefault_majfmt(self) -> bool: ...
|
| 119 |
+
@isDefault_majfmt.setter
|
| 120 |
+
def isDefault_majfmt(self, value: bool) -> None: ...
|
| 121 |
+
@property
|
| 122 |
+
def isDefault_minloc(self) -> bool: ...
|
| 123 |
+
@isDefault_minloc.setter
|
| 124 |
+
def isDefault_minloc(self, value: bool) -> None: ...
|
| 125 |
+
@property
|
| 126 |
+
def isDefault_minfmt(self) -> bool: ...
|
| 127 |
+
@isDefault_minfmt.setter
|
| 128 |
+
def isDefault_minfmt(self, value: bool) -> None: ...
|
| 129 |
+
majorTicks: _LazyTickList
|
| 130 |
+
minorTicks: _LazyTickList
|
| 131 |
+
def get_remove_overlapping_locs(self) -> bool: ...
|
| 132 |
+
def set_remove_overlapping_locs(self, val: bool) -> None: ...
|
| 133 |
+
@property
|
| 134 |
+
def remove_overlapping_locs(self) -> bool: ...
|
| 135 |
+
@remove_overlapping_locs.setter
|
| 136 |
+
def remove_overlapping_locs(self, val: bool) -> None: ...
|
| 137 |
+
stale: bool
|
| 138 |
+
def set_label_coords(
|
| 139 |
+
self, x: float, y: float, transform: Transform | None = ...
|
| 140 |
+
) -> None: ...
|
| 141 |
+
def get_transform(self) -> Transform: ...
|
| 142 |
+
def get_scale(self) -> str: ...
|
| 143 |
+
def limit_range_for_scale(
|
| 144 |
+
self, vmin: float, vmax: float
|
| 145 |
+
) -> tuple[float, float]: ...
|
| 146 |
+
def get_children(self) -> list[martist.Artist]: ...
|
| 147 |
+
# TODO units
|
| 148 |
+
converter: Any
|
| 149 |
+
units: Any
|
| 150 |
+
def clear(self) -> None: ...
|
| 151 |
+
def reset_ticks(self) -> None: ...
|
| 152 |
+
def minorticks_on(self) -> None: ...
|
| 153 |
+
def minorticks_off(self) -> None: ...
|
| 154 |
+
def set_tick_params(
|
| 155 |
+
self,
|
| 156 |
+
which: Literal["major", "minor", "both"] = ...,
|
| 157 |
+
reset: bool = ...,
|
| 158 |
+
**kwargs
|
| 159 |
+
) -> None: ...
|
| 160 |
+
def get_tick_params(
|
| 161 |
+
self, which: Literal["major", "minor"] = ...
|
| 162 |
+
) -> dict[str, Any]: ...
|
| 163 |
+
def get_view_interval(self) -> tuple[float, float]: ...
|
| 164 |
+
def set_view_interval(
|
| 165 |
+
self, vmin: float, vmax: float, ignore: bool = ...
|
| 166 |
+
) -> None: ...
|
| 167 |
+
def get_data_interval(self) -> tuple[float, float]: ...
|
| 168 |
+
def set_data_interval(
|
| 169 |
+
self, vmin: float, vmax: float, ignore: bool = ...
|
| 170 |
+
) -> None: ...
|
| 171 |
+
def get_inverted(self) -> bool: ...
|
| 172 |
+
def set_inverted(self, inverted: bool) -> None: ...
|
| 173 |
+
def set_default_intervals(self) -> None: ...
|
| 174 |
+
def get_tightbbox(
|
| 175 |
+
self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ...
|
| 176 |
+
) -> Bbox | None: ...
|
| 177 |
+
def get_tick_padding(self) -> float: ...
|
| 178 |
+
def get_gridlines(self) -> list[Line2D]: ...
|
| 179 |
+
def get_label(self) -> Text: ...
|
| 180 |
+
def get_offset_text(self) -> Text: ...
|
| 181 |
+
def get_pickradius(self) -> float: ...
|
| 182 |
+
def get_majorticklabels(self) -> list[Text]: ...
|
| 183 |
+
def get_minorticklabels(self) -> list[Text]: ...
|
| 184 |
+
def get_ticklabels(
|
| 185 |
+
self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
|
| 186 |
+
) -> list[Text]: ...
|
| 187 |
+
def get_majorticklines(self) -> list[Line2D]: ...
|
| 188 |
+
def get_minorticklines(self) -> list[Line2D]: ...
|
| 189 |
+
def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ...
|
| 190 |
+
def get_majorticklocs(self) -> np.ndarray: ...
|
| 191 |
+
def get_minorticklocs(self) -> np.ndarray: ...
|
| 192 |
+
def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ...
|
| 193 |
+
def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ...
|
| 194 |
+
def get_label_text(self) -> str: ...
|
| 195 |
+
def get_major_locator(self) -> Locator: ...
|
| 196 |
+
def get_minor_locator(self) -> Locator: ...
|
| 197 |
+
def get_major_formatter(self) -> Formatter: ...
|
| 198 |
+
def get_minor_formatter(self) -> Formatter: ...
|
| 199 |
+
def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
|
| 200 |
+
def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
|
| 201 |
+
def grid(
|
| 202 |
+
self,
|
| 203 |
+
visible: bool | None = ...,
|
| 204 |
+
which: Literal["major", "minor", "both"] = ...,
|
| 205 |
+
**kwargs
|
| 206 |
+
) -> None: ...
|
| 207 |
+
# TODO units
|
| 208 |
+
def update_units(self, data): ...
|
| 209 |
+
def have_units(self) -> bool: ...
|
| 210 |
+
def convert_units(self, x): ...
|
| 211 |
+
def get_converter(self) -> ConversionInterface | None: ...
|
| 212 |
+
def set_converter(self, converter: ConversionInterface) -> None: ...
|
| 213 |
+
def set_units(self, u) -> None: ...
|
| 214 |
+
def get_units(self): ...
|
| 215 |
+
def set_label_text(
|
| 216 |
+
self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs
|
| 217 |
+
) -> Text: ...
|
| 218 |
+
def set_major_formatter(
|
| 219 |
+
self, formatter: Formatter | str | Callable[[float, float], str]
|
| 220 |
+
) -> None: ...
|
| 221 |
+
def set_minor_formatter(
|
| 222 |
+
self, formatter: Formatter | str | Callable[[float, float], str]
|
| 223 |
+
) -> None: ...
|
| 224 |
+
def set_major_locator(self, locator: Locator) -> None: ...
|
| 225 |
+
def set_minor_locator(self, locator: Locator) -> None: ...
|
| 226 |
+
def set_pickradius(self, pickradius: float) -> None: ...
|
| 227 |
+
def set_ticklabels(
|
| 228 |
+
self,
|
| 229 |
+
labels: Iterable[str | Text],
|
| 230 |
+
*,
|
| 231 |
+
minor: bool = ...,
|
| 232 |
+
fontdict: dict[str, Any] | None = ...,
|
| 233 |
+
**kwargs
|
| 234 |
+
) -> list[Text]: ...
|
| 235 |
+
def set_ticks(
|
| 236 |
+
self,
|
| 237 |
+
ticks: ArrayLike,
|
| 238 |
+
labels: Iterable[str] | None = ...,
|
| 239 |
+
*,
|
| 240 |
+
minor: bool = ...,
|
| 241 |
+
**kwargs
|
| 242 |
+
) -> list[Tick]: ...
|
| 243 |
+
def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
|
| 244 |
+
def get_tick_space(self) -> int: ...
|
| 245 |
+
def get_label_position(self) -> Literal["top", "bottom"]: ...
|
| 246 |
+
def set_label_position(
|
| 247 |
+
self, position: Literal["top", "bottom", "left", "right"]
|
| 248 |
+
) -> None: ...
|
| 249 |
+
def get_minpos(self) -> float: ...
|
| 250 |
+
|
| 251 |
+
class XAxis(Axis):
|
| 252 |
+
__name__: str
|
| 253 |
+
axis_name: str
|
| 254 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 255 |
+
label_position: Literal["bottom", "top"]
|
| 256 |
+
stale: bool
|
| 257 |
+
def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override]
|
| 258 |
+
def set_ticks_position(
|
| 259 |
+
self, position: Literal["top", "bottom", "both", "default", "none"]
|
| 260 |
+
) -> None: ...
|
| 261 |
+
def tick_top(self) -> None: ...
|
| 262 |
+
def tick_bottom(self) -> None: ...
|
| 263 |
+
def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ...
|
| 264 |
+
def get_tick_space(self) -> int: ...
|
| 265 |
+
|
| 266 |
+
class YAxis(Axis):
|
| 267 |
+
__name__: str
|
| 268 |
+
axis_name: str
|
| 269 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 270 |
+
label_position: Literal["left", "right"]
|
| 271 |
+
stale: bool
|
| 272 |
+
def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override]
|
| 273 |
+
def set_offset_position(self, position: Literal["left", "right"]) -> None: ...
|
| 274 |
+
def set_ticks_position(
|
| 275 |
+
self, position: Literal["left", "right", "both", "default", "none"]
|
| 276 |
+
) -> None: ...
|
| 277 |
+
def tick_right(self) -> None: ...
|
| 278 |
+
def tick_left(self) -> None: ...
|
| 279 |
+
def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ...
|
| 280 |
+
def get_tick_space(self) -> int: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_bases.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_bases.pyi
ADDED
|
@@ -0,0 +1,482 @@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es
|
| 11 |
+
from matplotlib.backend_managers import ToolManager
|
| 12 |
+
from matplotlib.backend_tools import Cursors, ToolBase
|
| 13 |
+
from matplotlib.colorbar import Colorbar
|
| 14 |
+
from matplotlib.figure import Figure
|
| 15 |
+
from matplotlib.font_manager import FontProperties
|
| 16 |
+
from matplotlib.path import Path
|
| 17 |
+
from matplotlib.texmanager import TexManager
|
| 18 |
+
from matplotlib.text import Text
|
| 19 |
+
from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 22 |
+
from typing import Any, IO, Literal, NamedTuple, TypeVar
|
| 23 |
+
from numpy.typing import ArrayLike
|
| 24 |
+
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
|
| 25 |
+
|
| 26 |
+
def register_backend(
|
| 27 |
+
format: str, backend: str | type[FigureCanvasBase], description: str | None = ...
|
| 28 |
+
) -> None: ...
|
| 29 |
+
def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ...
|
| 30 |
+
|
| 31 |
+
class RendererBase:
|
| 32 |
+
def __init__(self) -> None: ...
|
| 33 |
+
def open_group(self, s: str, gid: str | None = ...) -> None: ...
|
| 34 |
+
def close_group(self, s: str) -> None: ...
|
| 35 |
+
def draw_path(
|
| 36 |
+
self,
|
| 37 |
+
gc: GraphicsContextBase,
|
| 38 |
+
path: Path,
|
| 39 |
+
transform: Transform,
|
| 40 |
+
rgbFace: ColorType | None = ...,
|
| 41 |
+
) -> None: ...
|
| 42 |
+
def draw_markers(
|
| 43 |
+
self,
|
| 44 |
+
gc: GraphicsContextBase,
|
| 45 |
+
marker_path: Path,
|
| 46 |
+
marker_trans: Transform,
|
| 47 |
+
path: Path,
|
| 48 |
+
trans: Transform,
|
| 49 |
+
rgbFace: ColorType | None = ...,
|
| 50 |
+
) -> None: ...
|
| 51 |
+
def draw_path_collection(
|
| 52 |
+
self,
|
| 53 |
+
gc: GraphicsContextBase,
|
| 54 |
+
master_transform: Transform,
|
| 55 |
+
paths: Sequence[Path],
|
| 56 |
+
all_transforms: Sequence[ArrayLike],
|
| 57 |
+
offsets: ArrayLike | Sequence[ArrayLike],
|
| 58 |
+
offset_trans: Transform,
|
| 59 |
+
facecolors: ColorType | Sequence[ColorType],
|
| 60 |
+
edgecolors: ColorType | Sequence[ColorType],
|
| 61 |
+
linewidths: float | Sequence[float],
|
| 62 |
+
linestyles: LineStyleType | Sequence[LineStyleType],
|
| 63 |
+
antialiaseds: bool | Sequence[bool],
|
| 64 |
+
urls: str | Sequence[str],
|
| 65 |
+
offset_position: Any,
|
| 66 |
+
) -> None: ...
|
| 67 |
+
def draw_quad_mesh(
|
| 68 |
+
self,
|
| 69 |
+
gc: GraphicsContextBase,
|
| 70 |
+
master_transform: Transform,
|
| 71 |
+
meshWidth,
|
| 72 |
+
meshHeight,
|
| 73 |
+
coordinates: ArrayLike,
|
| 74 |
+
offsets: ArrayLike | Sequence[ArrayLike],
|
| 75 |
+
offsetTrans: Transform,
|
| 76 |
+
facecolors: Sequence[ColorType],
|
| 77 |
+
antialiased: bool,
|
| 78 |
+
edgecolors: Sequence[ColorType] | ColorType | None,
|
| 79 |
+
) -> None: ...
|
| 80 |
+
def draw_gouraud_triangles(
|
| 81 |
+
self,
|
| 82 |
+
gc: GraphicsContextBase,
|
| 83 |
+
triangles_array: ArrayLike,
|
| 84 |
+
colors_array: ArrayLike,
|
| 85 |
+
transform: Transform,
|
| 86 |
+
) -> None: ...
|
| 87 |
+
def get_image_magnification(self) -> float: ...
|
| 88 |
+
def draw_image(
|
| 89 |
+
self,
|
| 90 |
+
gc: GraphicsContextBase,
|
| 91 |
+
x: float,
|
| 92 |
+
y: float,
|
| 93 |
+
im: ArrayLike,
|
| 94 |
+
transform: transforms.Affine2DBase | None = ...,
|
| 95 |
+
) -> None: ...
|
| 96 |
+
def option_image_nocomposite(self) -> bool: ...
|
| 97 |
+
def option_scale_image(self) -> bool: ...
|
| 98 |
+
def draw_tex(
|
| 99 |
+
self,
|
| 100 |
+
gc: GraphicsContextBase,
|
| 101 |
+
x: float,
|
| 102 |
+
y: float,
|
| 103 |
+
s: str,
|
| 104 |
+
prop: FontProperties,
|
| 105 |
+
angle: float,
|
| 106 |
+
*,
|
| 107 |
+
mtext: Text | None = ...
|
| 108 |
+
) -> None: ...
|
| 109 |
+
def draw_text(
|
| 110 |
+
self,
|
| 111 |
+
gc: GraphicsContextBase,
|
| 112 |
+
x: float,
|
| 113 |
+
y: float,
|
| 114 |
+
s: str,
|
| 115 |
+
prop: FontProperties,
|
| 116 |
+
angle: float,
|
| 117 |
+
ismath: bool | Literal["TeX"] = ...,
|
| 118 |
+
mtext: Text | None = ...,
|
| 119 |
+
) -> None: ...
|
| 120 |
+
def get_text_width_height_descent(
|
| 121 |
+
self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
|
| 122 |
+
) -> tuple[float, float, float]: ...
|
| 123 |
+
def flipy(self) -> bool: ...
|
| 124 |
+
def get_canvas_width_height(self) -> tuple[float, float]: ...
|
| 125 |
+
def get_texmanager(self) -> TexManager: ...
|
| 126 |
+
def new_gc(self) -> GraphicsContextBase: ...
|
| 127 |
+
def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ...
|
| 128 |
+
def start_rasterizing(self) -> None: ...
|
| 129 |
+
def stop_rasterizing(self) -> None: ...
|
| 130 |
+
def start_filter(self) -> None: ...
|
| 131 |
+
def stop_filter(self, filter_func) -> None: ...
|
| 132 |
+
|
| 133 |
+
class GraphicsContextBase:
|
| 134 |
+
def __init__(self) -> None: ...
|
| 135 |
+
def copy_properties(self, gc: GraphicsContextBase) -> None: ...
|
| 136 |
+
def restore(self) -> None: ...
|
| 137 |
+
def get_alpha(self) -> float: ...
|
| 138 |
+
def get_antialiased(self) -> int: ...
|
| 139 |
+
def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
|
| 140 |
+
def get_clip_rectangle(self) -> Bbox | None: ...
|
| 141 |
+
def get_clip_path(
|
| 142 |
+
self,
|
| 143 |
+
) -> tuple[TransformedPath, Transform] | tuple[None, None]: ...
|
| 144 |
+
def get_dashes(self) -> tuple[float, ArrayLike | None]: ...
|
| 145 |
+
def get_forced_alpha(self) -> bool: ...
|
| 146 |
+
def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
|
| 147 |
+
def get_linewidth(self) -> float: ...
|
| 148 |
+
def get_rgb(self) -> tuple[float, float, float, float]: ...
|
| 149 |
+
def get_url(self) -> str | None: ...
|
| 150 |
+
def get_gid(self) -> int | None: ...
|
| 151 |
+
def get_snap(self) -> bool | None: ...
|
| 152 |
+
def set_alpha(self, alpha: float) -> None: ...
|
| 153 |
+
def set_antialiased(self, b: bool) -> None: ...
|
| 154 |
+
def set_capstyle(self, cs: CapStyleType) -> None: ...
|
| 155 |
+
def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ...
|
| 156 |
+
def set_clip_path(self, path: TransformedPath | None) -> None: ...
|
| 157 |
+
def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ...
|
| 158 |
+
def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ...
|
| 159 |
+
def set_joinstyle(self, js: JoinStyleType) -> None: ...
|
| 160 |
+
def set_linewidth(self, w: float) -> None: ...
|
| 161 |
+
def set_url(self, url: str | None) -> None: ...
|
| 162 |
+
def set_gid(self, id: int | None) -> None: ...
|
| 163 |
+
def set_snap(self, snap: bool | None) -> None: ...
|
| 164 |
+
def set_hatch(self, hatch: str | None) -> None: ...
|
| 165 |
+
def get_hatch(self) -> str | None: ...
|
| 166 |
+
def get_hatch_path(self, density: float = ...) -> Path: ...
|
| 167 |
+
def get_hatch_color(self) -> ColorType: ...
|
| 168 |
+
def set_hatch_color(self, hatch_color: ColorType) -> None: ...
|
| 169 |
+
def get_hatch_linewidth(self) -> float: ...
|
| 170 |
+
def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
|
| 171 |
+
def get_sketch_params(self) -> tuple[float, float, float] | None: ...
|
| 172 |
+
def set_sketch_params(
|
| 173 |
+
self,
|
| 174 |
+
scale: float | None = ...,
|
| 175 |
+
length: float | None = ...,
|
| 176 |
+
randomness: float | None = ...,
|
| 177 |
+
) -> None: ...
|
| 178 |
+
|
| 179 |
+
class TimerBase:
|
| 180 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]]
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
interval: int | None = ...,
|
| 184 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
|
| 185 |
+
) -> None: ...
|
| 186 |
+
def __del__(self) -> None: ...
|
| 187 |
+
def start(self, interval: int | None = ...) -> None: ...
|
| 188 |
+
def stop(self) -> None: ...
|
| 189 |
+
@property
|
| 190 |
+
def interval(self) -> int: ...
|
| 191 |
+
@interval.setter
|
| 192 |
+
def interval(self, interval: int) -> None: ...
|
| 193 |
+
@property
|
| 194 |
+
def single_shot(self) -> bool: ...
|
| 195 |
+
@single_shot.setter
|
| 196 |
+
def single_shot(self, ss: bool) -> None: ...
|
| 197 |
+
def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ...
|
| 198 |
+
def remove_callback(self, func: Callable, *args, **kwargs) -> None: ...
|
| 199 |
+
|
| 200 |
+
class Event:
|
| 201 |
+
name: str
|
| 202 |
+
canvas: FigureCanvasBase
|
| 203 |
+
guiEvent: Any
|
| 204 |
+
def __init__(
|
| 205 |
+
self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ...
|
| 206 |
+
) -> None: ...
|
| 207 |
+
|
| 208 |
+
class DrawEvent(Event):
|
| 209 |
+
renderer: RendererBase
|
| 210 |
+
def __init__(
|
| 211 |
+
self, name: str, canvas: FigureCanvasBase, renderer: RendererBase
|
| 212 |
+
) -> None: ...
|
| 213 |
+
|
| 214 |
+
class ResizeEvent(Event):
|
| 215 |
+
width: int
|
| 216 |
+
height: int
|
| 217 |
+
def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ...
|
| 218 |
+
|
| 219 |
+
class CloseEvent(Event): ...
|
| 220 |
+
|
| 221 |
+
class LocationEvent(Event):
|
| 222 |
+
x: int
|
| 223 |
+
y: int
|
| 224 |
+
inaxes: Axes | None
|
| 225 |
+
xdata: float | None
|
| 226 |
+
ydata: float | None
|
| 227 |
+
def __init__(
|
| 228 |
+
self,
|
| 229 |
+
name: str,
|
| 230 |
+
canvas: FigureCanvasBase,
|
| 231 |
+
x: int,
|
| 232 |
+
y: int,
|
| 233 |
+
guiEvent: Any | None = ...,
|
| 234 |
+
*,
|
| 235 |
+
modifiers: Iterable[str] | None = ...,
|
| 236 |
+
) -> None: ...
|
| 237 |
+
|
| 238 |
+
class MouseButton(IntEnum):
|
| 239 |
+
LEFT = 1
|
| 240 |
+
MIDDLE = 2
|
| 241 |
+
RIGHT = 3
|
| 242 |
+
BACK = 8
|
| 243 |
+
FORWARD = 9
|
| 244 |
+
|
| 245 |
+
class MouseEvent(LocationEvent):
|
| 246 |
+
button: MouseButton | Literal["up", "down"] | None
|
| 247 |
+
key: str | None
|
| 248 |
+
step: float
|
| 249 |
+
dblclick: bool
|
| 250 |
+
def __init__(
|
| 251 |
+
self,
|
| 252 |
+
name: str,
|
| 253 |
+
canvas: FigureCanvasBase,
|
| 254 |
+
x: int,
|
| 255 |
+
y: int,
|
| 256 |
+
button: MouseButton | Literal["up", "down"] | None = ...,
|
| 257 |
+
key: str | None = ...,
|
| 258 |
+
step: float = ...,
|
| 259 |
+
dblclick: bool = ...,
|
| 260 |
+
guiEvent: Any | None = ...,
|
| 261 |
+
*,
|
| 262 |
+
buttons: Iterable[MouseButton] | None = ...,
|
| 263 |
+
modifiers: Iterable[str] | None = ...,
|
| 264 |
+
) -> None: ...
|
| 265 |
+
|
| 266 |
+
class PickEvent(Event):
|
| 267 |
+
mouseevent: MouseEvent
|
| 268 |
+
artist: Artist
|
| 269 |
+
def __init__(
|
| 270 |
+
self,
|
| 271 |
+
name: str,
|
| 272 |
+
canvas: FigureCanvasBase,
|
| 273 |
+
mouseevent: MouseEvent,
|
| 274 |
+
artist: Artist,
|
| 275 |
+
guiEvent: Any | None = ...,
|
| 276 |
+
**kwargs
|
| 277 |
+
) -> None: ...
|
| 278 |
+
|
| 279 |
+
class KeyEvent(LocationEvent):
|
| 280 |
+
key: str | None
|
| 281 |
+
def __init__(
|
| 282 |
+
self,
|
| 283 |
+
name: str,
|
| 284 |
+
canvas: FigureCanvasBase,
|
| 285 |
+
key: str | None,
|
| 286 |
+
x: int = ...,
|
| 287 |
+
y: int = ...,
|
| 288 |
+
guiEvent: Any | None = ...,
|
| 289 |
+
) -> None: ...
|
| 290 |
+
|
| 291 |
+
class FigureCanvasBase:
|
| 292 |
+
required_interactive_framework: str | None
|
| 293 |
+
|
| 294 |
+
@_api.classproperty
|
| 295 |
+
def manager_class(cls) -> type[FigureManagerBase]: ...
|
| 296 |
+
events: list[str]
|
| 297 |
+
fixed_dpi: None | float
|
| 298 |
+
filetypes: dict[str, str]
|
| 299 |
+
|
| 300 |
+
@_api.classproperty
|
| 301 |
+
def supports_blit(cls) -> bool: ...
|
| 302 |
+
|
| 303 |
+
figure: Figure
|
| 304 |
+
manager: None | FigureManagerBase
|
| 305 |
+
widgetlock: widgets.LockDraw
|
| 306 |
+
mouse_grabber: None | Axes
|
| 307 |
+
toolbar: None | NavigationToolbar2
|
| 308 |
+
def __init__(self, figure: Figure | None = ...) -> None: ...
|
| 309 |
+
@property
|
| 310 |
+
def callbacks(self) -> cbook.CallbackRegistry: ...
|
| 311 |
+
@property
|
| 312 |
+
def button_pick_id(self) -> int: ...
|
| 313 |
+
@property
|
| 314 |
+
def scroll_pick_id(self) -> int: ...
|
| 315 |
+
@classmethod
|
| 316 |
+
def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ...
|
| 317 |
+
def is_saving(self) -> bool: ...
|
| 318 |
+
def blit(self, bbox: BboxBase | None = ...) -> None: ...
|
| 319 |
+
def inaxes(self, xy: tuple[float, float]) -> Axes | None: ...
|
| 320 |
+
def grab_mouse(self, ax: Axes) -> None: ...
|
| 321 |
+
def release_mouse(self, ax: Axes) -> None: ...
|
| 322 |
+
def set_cursor(self, cursor: Cursors) -> None: ...
|
| 323 |
+
def draw(self, *args, **kwargs) -> None: ...
|
| 324 |
+
def draw_idle(self, *args, **kwargs) -> None: ...
|
| 325 |
+
@property
|
| 326 |
+
def device_pixel_ratio(self) -> float: ...
|
| 327 |
+
def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ...
|
| 328 |
+
@classmethod
|
| 329 |
+
def get_supported_filetypes(cls) -> dict[str, str]: ...
|
| 330 |
+
@classmethod
|
| 331 |
+
def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ...
|
| 332 |
+
def print_figure(
|
| 333 |
+
self,
|
| 334 |
+
filename: str | os.PathLike | IO,
|
| 335 |
+
dpi: float | None = ...,
|
| 336 |
+
facecolor: ColorType | Literal["auto"] | None = ...,
|
| 337 |
+
edgecolor: ColorType | Literal["auto"] | None = ...,
|
| 338 |
+
orientation: str = ...,
|
| 339 |
+
format: str | None = ...,
|
| 340 |
+
*,
|
| 341 |
+
bbox_inches: Literal["tight"] | Bbox | None = ...,
|
| 342 |
+
pad_inches: float | None = ...,
|
| 343 |
+
bbox_extra_artists: list[Artist] | None = ...,
|
| 344 |
+
backend: str | None = ...,
|
| 345 |
+
**kwargs
|
| 346 |
+
) -> Any: ...
|
| 347 |
+
@classmethod
|
| 348 |
+
def get_default_filetype(cls) -> str: ...
|
| 349 |
+
def get_default_filename(self) -> str: ...
|
| 350 |
+
_T = TypeVar("_T", bound=FigureCanvasBase)
|
| 351 |
+
def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ...
|
| 352 |
+
def mpl_disconnect(self, cid: int) -> None: ...
|
| 353 |
+
def new_timer(
|
| 354 |
+
self,
|
| 355 |
+
interval: int | None = ...,
|
| 356 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
|
| 357 |
+
) -> TimerBase: ...
|
| 358 |
+
def flush_events(self) -> None: ...
|
| 359 |
+
def start_event_loop(self, timeout: float = ...) -> None: ...
|
| 360 |
+
def stop_event_loop(self) -> None: ...
|
| 361 |
+
|
| 362 |
+
def key_press_handler(
|
| 363 |
+
event: KeyEvent,
|
| 364 |
+
canvas: FigureCanvasBase | None = ...,
|
| 365 |
+
toolbar: NavigationToolbar2 | None = ...,
|
| 366 |
+
) -> None: ...
|
| 367 |
+
def button_press_handler(
|
| 368 |
+
event: MouseEvent,
|
| 369 |
+
canvas: FigureCanvasBase | None = ...,
|
| 370 |
+
toolbar: NavigationToolbar2 | None = ...,
|
| 371 |
+
) -> None: ...
|
| 372 |
+
|
| 373 |
+
class NonGuiException(Exception): ...
|
| 374 |
+
|
| 375 |
+
class FigureManagerBase:
|
| 376 |
+
canvas: FigureCanvasBase
|
| 377 |
+
num: int | str
|
| 378 |
+
key_press_handler_id: int | None
|
| 379 |
+
button_press_handler_id: int | None
|
| 380 |
+
toolmanager: ToolManager | None
|
| 381 |
+
toolbar: NavigationToolbar2 | ToolContainerBase | None
|
| 382 |
+
def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ...
|
| 383 |
+
@classmethod
|
| 384 |
+
def create_with_canvas(
|
| 385 |
+
cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str
|
| 386 |
+
) -> FigureManagerBase: ...
|
| 387 |
+
@classmethod
|
| 388 |
+
def start_main_loop(cls) -> None: ...
|
| 389 |
+
@classmethod
|
| 390 |
+
def pyplot_show(cls, *, block: bool | None = ...) -> None: ...
|
| 391 |
+
def show(self) -> None: ...
|
| 392 |
+
def destroy(self) -> None: ...
|
| 393 |
+
def full_screen_toggle(self) -> None: ...
|
| 394 |
+
def resize(self, w: int, h: int) -> None: ...
|
| 395 |
+
def get_window_title(self) -> str: ...
|
| 396 |
+
def set_window_title(self, title: str) -> None: ...
|
| 397 |
+
|
| 398 |
+
cursors = Cursors
|
| 399 |
+
|
| 400 |
+
class _Mode(str, Enum):
|
| 401 |
+
NONE = ""
|
| 402 |
+
PAN = "pan/zoom"
|
| 403 |
+
ZOOM = "zoom rect"
|
| 404 |
+
|
| 405 |
+
class NavigationToolbar2:
|
| 406 |
+
toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...]
|
| 407 |
+
UNKNOWN_SAVED_STATUS: object
|
| 408 |
+
canvas: FigureCanvasBase
|
| 409 |
+
mode: _Mode
|
| 410 |
+
def __init__(self, canvas: FigureCanvasBase) -> None: ...
|
| 411 |
+
def set_message(self, s: str) -> None: ...
|
| 412 |
+
def draw_rubberband(
|
| 413 |
+
self, event: Event, x0: float, y0: float, x1: float, y1: float
|
| 414 |
+
) -> None: ...
|
| 415 |
+
def remove_rubberband(self) -> None: ...
|
| 416 |
+
def home(self, *args) -> None: ...
|
| 417 |
+
def back(self, *args) -> None: ...
|
| 418 |
+
def forward(self, *args) -> None: ...
|
| 419 |
+
def mouse_move(self, event: MouseEvent) -> None: ...
|
| 420 |
+
def pan(self, *args) -> None: ...
|
| 421 |
+
|
| 422 |
+
class _PanInfo(NamedTuple):
|
| 423 |
+
button: MouseButton
|
| 424 |
+
axes: list[Axes]
|
| 425 |
+
cid: int
|
| 426 |
+
def press_pan(self, event: Event) -> None: ...
|
| 427 |
+
def drag_pan(self, event: Event) -> None: ...
|
| 428 |
+
def release_pan(self, event: Event) -> None: ...
|
| 429 |
+
def zoom(self, *args) -> None: ...
|
| 430 |
+
|
| 431 |
+
class _ZoomInfo(NamedTuple):
|
| 432 |
+
direction: Literal["in", "out"]
|
| 433 |
+
start_xy: tuple[float, float]
|
| 434 |
+
axes: list[Axes]
|
| 435 |
+
cid: int
|
| 436 |
+
cbar: Colorbar
|
| 437 |
+
def press_zoom(self, event: Event) -> None: ...
|
| 438 |
+
def drag_zoom(self, event: Event) -> None: ...
|
| 439 |
+
def release_zoom(self, event: Event) -> None: ...
|
| 440 |
+
def push_current(self) -> None: ...
|
| 441 |
+
subplot_tool: widgets.SubplotTool
|
| 442 |
+
def configure_subplots(self, *args): ...
|
| 443 |
+
def save_figure(self, *args) -> str | None | object: ...
|
| 444 |
+
def update(self) -> None: ...
|
| 445 |
+
def set_history_buttons(self) -> None: ...
|
| 446 |
+
|
| 447 |
+
class ToolContainerBase:
|
| 448 |
+
toolmanager: ToolManager
|
| 449 |
+
def __init__(self, toolmanager: ToolManager) -> None: ...
|
| 450 |
+
def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ...
|
| 451 |
+
def trigger_tool(self, name: str) -> None: ...
|
| 452 |
+
def add_toolitem(
|
| 453 |
+
self,
|
| 454 |
+
name: str,
|
| 455 |
+
group: str,
|
| 456 |
+
position: int,
|
| 457 |
+
image: str,
|
| 458 |
+
description: str,
|
| 459 |
+
toggle: bool,
|
| 460 |
+
) -> None: ...
|
| 461 |
+
def toggle_toolitem(self, name: str, toggled: bool) -> None: ...
|
| 462 |
+
def remove_toolitem(self, name: str) -> None: ...
|
| 463 |
+
def set_message(self, s: str) -> None: ...
|
| 464 |
+
|
| 465 |
+
class _Backend:
|
| 466 |
+
backend_version: str
|
| 467 |
+
FigureCanvas: type[FigureCanvasBase] | None
|
| 468 |
+
FigureManager: type[FigureManagerBase]
|
| 469 |
+
mainloop: None | Callable[[], Any]
|
| 470 |
+
@classmethod
|
| 471 |
+
def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ...
|
| 472 |
+
@classmethod
|
| 473 |
+
def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ...
|
| 474 |
+
@classmethod
|
| 475 |
+
def draw_if_interactive(cls) -> None: ...
|
| 476 |
+
@classmethod
|
| 477 |
+
def show(cls, *, block: bool | None = ...) -> None: ...
|
| 478 |
+
@staticmethod
|
| 479 |
+
def export(cls) -> type[_Backend]: ...
|
| 480 |
+
|
| 481 |
+
class ShowBase(_Backend):
|
| 482 |
+
def __call__(self, block: bool | None = ...) -> None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_managers.py
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import _api, backend_tools, cbook, widgets
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ToolEvent:
|
| 5 |
+
"""Event for tool manipulation (add/remove)."""
|
| 6 |
+
def __init__(self, name, sender, tool, data=None):
|
| 7 |
+
self.name = name
|
| 8 |
+
self.sender = sender
|
| 9 |
+
self.tool = tool
|
| 10 |
+
self.data = data
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ToolTriggerEvent(ToolEvent):
|
| 14 |
+
"""Event to inform that a tool has been triggered."""
|
| 15 |
+
def __init__(self, name, sender, tool, canvasevent=None, data=None):
|
| 16 |
+
super().__init__(name, sender, tool, data)
|
| 17 |
+
self.canvasevent = canvasevent
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ToolManagerMessageEvent:
|
| 21 |
+
"""
|
| 22 |
+
Event carrying messages from toolmanager.
|
| 23 |
+
|
| 24 |
+
Messages usually get displayed to the user by the toolbar.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, name, sender, message):
|
| 27 |
+
self.name = name
|
| 28 |
+
self.sender = sender
|
| 29 |
+
self.message = message
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ToolManager:
|
| 33 |
+
"""
|
| 34 |
+
Manager for actions triggered by user interactions (key press, toolbar
|
| 35 |
+
clicks, ...) on a Figure.
|
| 36 |
+
|
| 37 |
+
Attributes
|
| 38 |
+
----------
|
| 39 |
+
figure : `.Figure`
|
| 40 |
+
keypresslock : `~matplotlib.widgets.LockDraw`
|
| 41 |
+
`.LockDraw` object to know if the `canvas` key_press_event is locked.
|
| 42 |
+
messagelock : `~matplotlib.widgets.LockDraw`
|
| 43 |
+
`.LockDraw` object to know if the message is available to write.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, figure=None):
|
| 47 |
+
|
| 48 |
+
self._key_press_handler_id = None
|
| 49 |
+
|
| 50 |
+
self._tools = {}
|
| 51 |
+
self._keys = {}
|
| 52 |
+
self._toggled = {}
|
| 53 |
+
self._callbacks = cbook.CallbackRegistry()
|
| 54 |
+
|
| 55 |
+
# to process keypress event
|
| 56 |
+
self.keypresslock = widgets.LockDraw()
|
| 57 |
+
self.messagelock = widgets.LockDraw()
|
| 58 |
+
|
| 59 |
+
self._figure = None
|
| 60 |
+
self.set_figure(figure)
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def canvas(self):
|
| 64 |
+
"""Canvas managed by FigureManager."""
|
| 65 |
+
if not self._figure:
|
| 66 |
+
return None
|
| 67 |
+
return self._figure.canvas
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def figure(self):
|
| 71 |
+
"""Figure that holds the canvas."""
|
| 72 |
+
return self._figure
|
| 73 |
+
|
| 74 |
+
@figure.setter
|
| 75 |
+
def figure(self, figure):
|
| 76 |
+
self.set_figure(figure)
|
| 77 |
+
|
| 78 |
+
def set_figure(self, figure, update_tools=True):
|
| 79 |
+
"""
|
| 80 |
+
Bind the given figure to the tools.
|
| 81 |
+
|
| 82 |
+
Parameters
|
| 83 |
+
----------
|
| 84 |
+
figure : `.Figure`
|
| 85 |
+
update_tools : bool, default: True
|
| 86 |
+
Force tools to update figure.
|
| 87 |
+
"""
|
| 88 |
+
if self._key_press_handler_id:
|
| 89 |
+
self.canvas.mpl_disconnect(self._key_press_handler_id)
|
| 90 |
+
self._figure = figure
|
| 91 |
+
if figure:
|
| 92 |
+
self._key_press_handler_id = self.canvas.mpl_connect(
|
| 93 |
+
'key_press_event', self._key_press)
|
| 94 |
+
if update_tools:
|
| 95 |
+
for tool in self._tools.values():
|
| 96 |
+
tool.figure = figure
|
| 97 |
+
|
| 98 |
+
def toolmanager_connect(self, s, func):
|
| 99 |
+
"""
|
| 100 |
+
Connect event with string *s* to *func*.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
s : str
|
| 105 |
+
The name of the event. The following events are recognized:
|
| 106 |
+
|
| 107 |
+
- 'tool_message_event'
|
| 108 |
+
- 'tool_removed_event'
|
| 109 |
+
- 'tool_added_event'
|
| 110 |
+
|
| 111 |
+
For every tool added a new event is created
|
| 112 |
+
|
| 113 |
+
- 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool.
|
| 114 |
+
|
| 115 |
+
func : callable
|
| 116 |
+
Callback function for the toolmanager event with signature::
|
| 117 |
+
|
| 118 |
+
def func(event: ToolEvent) -> Any
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
cid
|
| 123 |
+
The callback id for the connection. This can be used in
|
| 124 |
+
`.toolmanager_disconnect`.
|
| 125 |
+
"""
|
| 126 |
+
return self._callbacks.connect(s, func)
|
| 127 |
+
|
| 128 |
+
def toolmanager_disconnect(self, cid):
|
| 129 |
+
"""
|
| 130 |
+
Disconnect callback id *cid*.
|
| 131 |
+
|
| 132 |
+
Example usage::
|
| 133 |
+
|
| 134 |
+
cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
|
| 135 |
+
#...later
|
| 136 |
+
toolmanager.toolmanager_disconnect(cid)
|
| 137 |
+
"""
|
| 138 |
+
return self._callbacks.disconnect(cid)
|
| 139 |
+
|
| 140 |
+
def message_event(self, message, sender=None):
|
| 141 |
+
"""Emit a `ToolManagerMessageEvent`."""
|
| 142 |
+
if sender is None:
|
| 143 |
+
sender = self
|
| 144 |
+
|
| 145 |
+
s = 'tool_message_event'
|
| 146 |
+
event = ToolManagerMessageEvent(s, sender, message)
|
| 147 |
+
self._callbacks.process(s, event)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def active_toggle(self):
|
| 151 |
+
"""Currently toggled tools."""
|
| 152 |
+
return self._toggled
|
| 153 |
+
|
| 154 |
+
def get_tool_keymap(self, name):
|
| 155 |
+
"""
|
| 156 |
+
Return the keymap associated with the specified tool.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
----------
|
| 160 |
+
name : str
|
| 161 |
+
Name of the Tool.
|
| 162 |
+
|
| 163 |
+
Returns
|
| 164 |
+
-------
|
| 165 |
+
list of str
|
| 166 |
+
List of keys associated with the tool.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
keys = [k for k, i in self._keys.items() if i == name]
|
| 170 |
+
return keys
|
| 171 |
+
|
| 172 |
+
def _remove_keys(self, name):
|
| 173 |
+
for k in self.get_tool_keymap(name):
|
| 174 |
+
del self._keys[k]
|
| 175 |
+
|
| 176 |
+
def update_keymap(self, name, key):
|
| 177 |
+
"""
|
| 178 |
+
Set the keymap to associate with the specified tool.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
name : str
|
| 183 |
+
Name of the Tool.
|
| 184 |
+
key : str or list of str
|
| 185 |
+
Keys to associate with the tool.
|
| 186 |
+
"""
|
| 187 |
+
if name not in self._tools:
|
| 188 |
+
raise KeyError(f'{name!r} not in Tools')
|
| 189 |
+
self._remove_keys(name)
|
| 190 |
+
if isinstance(key, str):
|
| 191 |
+
key = [key]
|
| 192 |
+
for k in key:
|
| 193 |
+
if k in self._keys:
|
| 194 |
+
_api.warn_external(
|
| 195 |
+
f'Key {k} changed from {self._keys[k]} to {name}')
|
| 196 |
+
self._keys[k] = name
|
| 197 |
+
|
| 198 |
+
def remove_tool(self, name):
|
| 199 |
+
"""
|
| 200 |
+
Remove tool named *name*.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
name : str
|
| 205 |
+
Name of the tool.
|
| 206 |
+
"""
|
| 207 |
+
tool = self.get_tool(name)
|
| 208 |
+
if getattr(tool, 'toggled', False): # If it's a toggled toggle tool, untoggle
|
| 209 |
+
self.trigger_tool(tool, 'toolmanager')
|
| 210 |
+
self._remove_keys(name)
|
| 211 |
+
event = ToolEvent('tool_removed_event', self, tool)
|
| 212 |
+
self._callbacks.process(event.name, event)
|
| 213 |
+
del self._tools[name]
|
| 214 |
+
|
| 215 |
+
def add_tool(self, name, tool, *args, **kwargs):
|
| 216 |
+
"""
|
| 217 |
+
Add *tool* to `ToolManager`.
|
| 218 |
+
|
| 219 |
+
If successful, adds a new event ``tool_trigger_{name}`` where
|
| 220 |
+
``{name}`` is the *name* of the tool; the event is fired every time the
|
| 221 |
+
tool is triggered.
|
| 222 |
+
|
| 223 |
+
Parameters
|
| 224 |
+
----------
|
| 225 |
+
name : str
|
| 226 |
+
Name of the tool, treated as the ID, has to be unique.
|
| 227 |
+
tool : type
|
| 228 |
+
Class of the tool to be added. A subclass will be used
|
| 229 |
+
instead if one was registered for the current canvas class.
|
| 230 |
+
*args, **kwargs
|
| 231 |
+
Passed to the *tool*'s constructor.
|
| 232 |
+
|
| 233 |
+
See Also
|
| 234 |
+
--------
|
| 235 |
+
matplotlib.backend_tools.ToolBase : The base class for tools.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
tool_cls = backend_tools._find_tool_class(type(self.canvas), tool)
|
| 239 |
+
if not tool_cls:
|
| 240 |
+
raise ValueError('Impossible to find class for %s' % str(tool))
|
| 241 |
+
|
| 242 |
+
if name in self._tools:
|
| 243 |
+
_api.warn_external('A "Tool class" with the same name already '
|
| 244 |
+
'exists, not added')
|
| 245 |
+
return self._tools[name]
|
| 246 |
+
|
| 247 |
+
tool_obj = tool_cls(self, name, *args, **kwargs)
|
| 248 |
+
self._tools[name] = tool_obj
|
| 249 |
+
|
| 250 |
+
if tool_obj.default_keymap is not None:
|
| 251 |
+
self.update_keymap(name, tool_obj.default_keymap)
|
| 252 |
+
|
| 253 |
+
# For toggle tools init the radio_group in self._toggled
|
| 254 |
+
if isinstance(tool_obj, backend_tools.ToolToggleBase):
|
| 255 |
+
# None group is not mutually exclusive, a set is used to keep track
|
| 256 |
+
# of all toggled tools in this group
|
| 257 |
+
if tool_obj.radio_group is None:
|
| 258 |
+
self._toggled.setdefault(None, set())
|
| 259 |
+
else:
|
| 260 |
+
self._toggled.setdefault(tool_obj.radio_group, None)
|
| 261 |
+
|
| 262 |
+
# If initially toggled
|
| 263 |
+
if tool_obj.toggled:
|
| 264 |
+
self._handle_toggle(tool_obj, None, None)
|
| 265 |
+
tool_obj.set_figure(self.figure)
|
| 266 |
+
|
| 267 |
+
event = ToolEvent('tool_added_event', self, tool_obj)
|
| 268 |
+
self._callbacks.process(event.name, event)
|
| 269 |
+
|
| 270 |
+
return tool_obj
|
| 271 |
+
|
| 272 |
+
def _handle_toggle(self, tool, canvasevent, data):
|
| 273 |
+
"""
|
| 274 |
+
Toggle tools, need to untoggle prior to using other Toggle tool.
|
| 275 |
+
Called from trigger_tool.
|
| 276 |
+
|
| 277 |
+
Parameters
|
| 278 |
+
----------
|
| 279 |
+
tool : `.ToolBase`
|
| 280 |
+
canvasevent : Event
|
| 281 |
+
Original Canvas event or None.
|
| 282 |
+
data : object
|
| 283 |
+
Extra data to pass to the tool when triggering.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
radio_group = tool.radio_group
|
| 287 |
+
# radio_group None is not mutually exclusive
|
| 288 |
+
# just keep track of toggled tools in this group
|
| 289 |
+
if radio_group is None:
|
| 290 |
+
if tool.name in self._toggled[None]:
|
| 291 |
+
self._toggled[None].remove(tool.name)
|
| 292 |
+
else:
|
| 293 |
+
self._toggled[None].add(tool.name)
|
| 294 |
+
return
|
| 295 |
+
|
| 296 |
+
# If the tool already has a toggled state, untoggle it
|
| 297 |
+
if self._toggled[radio_group] == tool.name:
|
| 298 |
+
toggled = None
|
| 299 |
+
# If no tool was toggled in the radio_group
|
| 300 |
+
# toggle it
|
| 301 |
+
elif self._toggled[radio_group] is None:
|
| 302 |
+
toggled = tool.name
|
| 303 |
+
# Other tool in the radio_group is toggled
|
| 304 |
+
else:
|
| 305 |
+
# Untoggle previously toggled tool
|
| 306 |
+
self.trigger_tool(self._toggled[radio_group],
|
| 307 |
+
self,
|
| 308 |
+
canvasevent,
|
| 309 |
+
data)
|
| 310 |
+
toggled = tool.name
|
| 311 |
+
|
| 312 |
+
# Keep track of the toggled tool in the radio_group
|
| 313 |
+
self._toggled[radio_group] = toggled
|
| 314 |
+
|
| 315 |
+
def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
|
| 316 |
+
"""
|
| 317 |
+
Trigger a tool and emit the ``tool_trigger_{name}`` event.
|
| 318 |
+
|
| 319 |
+
Parameters
|
| 320 |
+
----------
|
| 321 |
+
name : str
|
| 322 |
+
Name of the tool.
|
| 323 |
+
sender : object
|
| 324 |
+
Object that wishes to trigger the tool.
|
| 325 |
+
canvasevent : Event
|
| 326 |
+
Original Canvas event or None.
|
| 327 |
+
data : object
|
| 328 |
+
Extra data to pass to the tool when triggering.
|
| 329 |
+
"""
|
| 330 |
+
tool = self.get_tool(name)
|
| 331 |
+
if tool is None:
|
| 332 |
+
return
|
| 333 |
+
|
| 334 |
+
if sender is None:
|
| 335 |
+
sender = self
|
| 336 |
+
|
| 337 |
+
if isinstance(tool, backend_tools.ToolToggleBase):
|
| 338 |
+
self._handle_toggle(tool, canvasevent, data)
|
| 339 |
+
|
| 340 |
+
tool.trigger(sender, canvasevent, data) # Actually trigger Tool.
|
| 341 |
+
|
| 342 |
+
s = 'tool_trigger_%s' % name
|
| 343 |
+
event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
|
| 344 |
+
self._callbacks.process(s, event)
|
| 345 |
+
|
| 346 |
+
def _key_press(self, event):
|
| 347 |
+
if event.key is None or self.keypresslock.locked():
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
name = self._keys.get(event.key, None)
|
| 351 |
+
if name is None:
|
| 352 |
+
return
|
| 353 |
+
self.trigger_tool(name, canvasevent=event)
|
| 354 |
+
|
| 355 |
+
@property
|
| 356 |
+
def tools(self):
|
| 357 |
+
"""A dict mapping tool name -> controlled tool."""
|
| 358 |
+
return self._tools
|
| 359 |
+
|
| 360 |
+
def get_tool(self, name, warn=True):
|
| 361 |
+
"""
|
| 362 |
+
Return the tool object with the given name.
|
| 363 |
+
|
| 364 |
+
For convenience, this passes tool objects through.
|
| 365 |
+
|
| 366 |
+
Parameters
|
| 367 |
+
----------
|
| 368 |
+
name : str or `.ToolBase`
|
| 369 |
+
Name of the tool, or the tool itself.
|
| 370 |
+
warn : bool, default: True
|
| 371 |
+
Whether a warning should be emitted it no tool with the given name
|
| 372 |
+
exists.
|
| 373 |
+
|
| 374 |
+
Returns
|
| 375 |
+
-------
|
| 376 |
+
`.ToolBase` or None
|
| 377 |
+
The tool or None if no tool with the given name exists.
|
| 378 |
+
"""
|
| 379 |
+
if (isinstance(name, backend_tools.ToolBase)
|
| 380 |
+
and name.name in self._tools):
|
| 381 |
+
return name
|
| 382 |
+
if name not in self._tools:
|
| 383 |
+
if warn:
|
| 384 |
+
_api.warn_external(
|
| 385 |
+
f"ToolManager does not control tool {name!r}")
|
| 386 |
+
return None
|
| 387 |
+
return self._tools[name]
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_managers.pyi
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import backend_tools, widgets
|
| 2 |
+
from matplotlib.backend_bases import FigureCanvasBase
|
| 3 |
+
from matplotlib.figure import Figure
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable, Iterable
|
| 6 |
+
from typing import Any, TypeVar
|
| 7 |
+
|
| 8 |
+
class ToolEvent:
|
| 9 |
+
name: str
|
| 10 |
+
sender: Any
|
| 11 |
+
tool: backend_tools.ToolBase
|
| 12 |
+
data: Any
|
| 13 |
+
def __init__(self, name, sender, tool, data: Any | None = ...) -> None: ...
|
| 14 |
+
|
| 15 |
+
class ToolTriggerEvent(ToolEvent):
|
| 16 |
+
canvasevent: ToolEvent
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
name,
|
| 20 |
+
sender,
|
| 21 |
+
tool,
|
| 22 |
+
canvasevent: ToolEvent | None = ...,
|
| 23 |
+
data: Any | None = ...,
|
| 24 |
+
) -> None: ...
|
| 25 |
+
|
| 26 |
+
class ToolManagerMessageEvent:
|
| 27 |
+
name: str
|
| 28 |
+
sender: Any
|
| 29 |
+
message: str
|
| 30 |
+
def __init__(self, name: str, sender: Any, message: str) -> None: ...
|
| 31 |
+
|
| 32 |
+
class ToolManager:
|
| 33 |
+
keypresslock: widgets.LockDraw
|
| 34 |
+
messagelock: widgets.LockDraw
|
| 35 |
+
def __init__(self, figure: Figure | None = ...) -> None: ...
|
| 36 |
+
@property
|
| 37 |
+
def canvas(self) -> FigureCanvasBase | None: ...
|
| 38 |
+
@property
|
| 39 |
+
def figure(self) -> Figure | None: ...
|
| 40 |
+
@figure.setter
|
| 41 |
+
def figure(self, figure: Figure) -> None: ...
|
| 42 |
+
def set_figure(self, figure: Figure, update_tools: bool = ...) -> None: ...
|
| 43 |
+
def toolmanager_connect(self, s: str, func: Callable[[ToolEvent], Any]) -> int: ...
|
| 44 |
+
def toolmanager_disconnect(self, cid: int) -> None: ...
|
| 45 |
+
def message_event(self, message: str, sender: Any | None = ...) -> None: ...
|
| 46 |
+
@property
|
| 47 |
+
def active_toggle(self) -> dict[str | None, list[str] | str]: ...
|
| 48 |
+
def get_tool_keymap(self, name: str) -> list[str]: ...
|
| 49 |
+
def update_keymap(self, name: str, key: str | Iterable[str]) -> None: ...
|
| 50 |
+
def remove_tool(self, name: str) -> None: ...
|
| 51 |
+
_T = TypeVar("_T", bound=backend_tools.ToolBase)
|
| 52 |
+
def add_tool(self, name: str, tool: type[_T], *args, **kwargs) -> _T: ...
|
| 53 |
+
def trigger_tool(
|
| 54 |
+
self,
|
| 55 |
+
name: str | backend_tools.ToolBase,
|
| 56 |
+
sender: Any | None = ...,
|
| 57 |
+
canvasevent: ToolEvent | None = ...,
|
| 58 |
+
data: Any | None = ...,
|
| 59 |
+
) -> None: ...
|
| 60 |
+
@property
|
| 61 |
+
def tools(self) -> dict[str, backend_tools.ToolBase]: ...
|
| 62 |
+
def get_tool(
|
| 63 |
+
self, name: str | backend_tools.ToolBase, warn: bool = ...
|
| 64 |
+
) -> backend_tools.ToolBase | None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_tools.py
ADDED
|
@@ -0,0 +1,998 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Abstract base classes define the primitives for Tools.
|
| 3 |
+
These tools are used by `matplotlib.backend_managers.ToolManager`
|
| 4 |
+
|
| 5 |
+
:class:`ToolBase`
|
| 6 |
+
Simple stateless tool
|
| 7 |
+
|
| 8 |
+
:class:`ToolToggleBase`
|
| 9 |
+
Tool that has two states, only one Toggle tool can be
|
| 10 |
+
active at any given time for the same
|
| 11 |
+
`matplotlib.backend_managers.ToolManager`
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import enum
|
| 15 |
+
import functools
|
| 16 |
+
import re
|
| 17 |
+
import time
|
| 18 |
+
from types import SimpleNamespace
|
| 19 |
+
import uuid
|
| 20 |
+
from weakref import WeakKeyDictionary
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import matplotlib as mpl
|
| 25 |
+
from matplotlib._pylab_helpers import Gcf
|
| 26 |
+
from matplotlib import _api, cbook
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
|
| 30 |
+
"""Backend-independent cursor types."""
|
| 31 |
+
POINTER = enum.auto()
|
| 32 |
+
HAND = enum.auto()
|
| 33 |
+
SELECT_REGION = enum.auto()
|
| 34 |
+
MOVE = enum.auto()
|
| 35 |
+
WAIT = enum.auto()
|
| 36 |
+
RESIZE_HORIZONTAL = enum.auto()
|
| 37 |
+
RESIZE_VERTICAL = enum.auto()
|
| 38 |
+
cursors = Cursors # Backcompat.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# _tool_registry, _register_tool_class, and _find_tool_class implement a
|
| 42 |
+
# mechanism through which ToolManager.add_tool can determine whether a subclass
|
| 43 |
+
# of the requested tool class has been registered (either for the current
|
| 44 |
+
# canvas class or for a parent class), in which case that tool subclass will be
|
| 45 |
+
# instantiated instead. This is the mechanism used e.g. to allow different
|
| 46 |
+
# GUI backends to implement different specializations for ConfigureSubplots.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_tool_registry = set()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _register_tool_class(canvas_cls, tool_cls=None):
|
| 53 |
+
"""Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
|
| 54 |
+
if tool_cls is None:
|
| 55 |
+
return functools.partial(_register_tool_class, canvas_cls)
|
| 56 |
+
_tool_registry.add((canvas_cls, tool_cls))
|
| 57 |
+
return tool_cls
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _find_tool_class(canvas_cls, tool_cls):
|
| 61 |
+
"""Find a subclass of *tool_cls* registered for *canvas_cls*."""
|
| 62 |
+
for canvas_parent in canvas_cls.__mro__:
|
| 63 |
+
for tool_child in _api.recursive_subclasses(tool_cls):
|
| 64 |
+
if (canvas_parent, tool_child) in _tool_registry:
|
| 65 |
+
return tool_child
|
| 66 |
+
return tool_cls
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Views positions tool
|
| 70 |
+
_views_positions = 'viewpos'
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ToolBase:
|
| 74 |
+
"""
|
| 75 |
+
Base tool class.
|
| 76 |
+
|
| 77 |
+
A base tool, only implements `trigger` method or no method at all.
|
| 78 |
+
The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
default_keymap = None
|
| 82 |
+
"""
|
| 83 |
+
Keymap to associate with this tool.
|
| 84 |
+
|
| 85 |
+
``list[str]``: List of keys that will trigger this tool when a keypress
|
| 86 |
+
event is emitted on ``self.figure.canvas``. Note that this attribute is
|
| 87 |
+
looked up on the instance, and can therefore be a property (this is used
|
| 88 |
+
e.g. by the built-in tools to load the rcParams at instantiation time).
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
description = None
|
| 92 |
+
"""
|
| 93 |
+
Description of the Tool.
|
| 94 |
+
|
| 95 |
+
`str`: Tooltip used if the Tool is included in a Toolbar.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
image = None
|
| 99 |
+
"""
|
| 100 |
+
Icon filename.
|
| 101 |
+
|
| 102 |
+
``str | None``: Filename of the Toolbar icon; either absolute, or relative to the
|
| 103 |
+
directory containing the Python source file where the ``Tool.image`` class attribute
|
| 104 |
+
is defined (in the latter case, this cannot be defined as an instance attribute).
|
| 105 |
+
In either case, the extension is optional; leaving it off lets individual backends
|
| 106 |
+
select the icon format they prefer. If None, the *name* is used as a label in the
|
| 107 |
+
toolbar button.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(self, toolmanager, name):
|
| 111 |
+
self._name = name
|
| 112 |
+
self._toolmanager = toolmanager
|
| 113 |
+
self._figure = None
|
| 114 |
+
|
| 115 |
+
name = property(
|
| 116 |
+
lambda self: self._name,
|
| 117 |
+
doc="The tool id (str, must be unique among tools of a tool manager).")
|
| 118 |
+
toolmanager = property(
|
| 119 |
+
lambda self: self._toolmanager,
|
| 120 |
+
doc="The `.ToolManager` that controls this tool.")
|
| 121 |
+
canvas = property(
|
| 122 |
+
lambda self: self._figure.canvas if self._figure is not None else None,
|
| 123 |
+
doc="The canvas of the figure affected by this tool, or None.")
|
| 124 |
+
|
| 125 |
+
def set_figure(self, figure):
|
| 126 |
+
self._figure = figure
|
| 127 |
+
|
| 128 |
+
figure = property(
|
| 129 |
+
lambda self: self._figure,
|
| 130 |
+
# The setter must explicitly call self.set_figure so that subclasses can
|
| 131 |
+
# meaningfully override it.
|
| 132 |
+
lambda self, figure: self.set_figure(figure),
|
| 133 |
+
doc="The Figure affected by this tool, or None.")
|
| 134 |
+
|
| 135 |
+
def _make_classic_style_pseudo_toolbar(self):
|
| 136 |
+
"""
|
| 137 |
+
Return a placeholder object with a single `canvas` attribute.
|
| 138 |
+
|
| 139 |
+
This is useful to reuse the implementations of tools already provided
|
| 140 |
+
by the classic Toolbars.
|
| 141 |
+
"""
|
| 142 |
+
return SimpleNamespace(canvas=self.canvas)
|
| 143 |
+
|
| 144 |
+
def trigger(self, sender, event, data=None):
|
| 145 |
+
"""
|
| 146 |
+
Called when this tool gets used.
|
| 147 |
+
|
| 148 |
+
This method is called by `.ToolManager.trigger_tool`.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
event : `.Event`
|
| 153 |
+
The canvas event that caused this tool to be called.
|
| 154 |
+
sender : object
|
| 155 |
+
Object that requested the tool to be triggered.
|
| 156 |
+
data : object
|
| 157 |
+
Extra data.
|
| 158 |
+
"""
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class ToolToggleBase(ToolBase):
|
| 163 |
+
"""
|
| 164 |
+
Toggleable tool.
|
| 165 |
+
|
| 166 |
+
Every time it is triggered, it switches between enable and disable.
|
| 167 |
+
|
| 168 |
+
Parameters
|
| 169 |
+
----------
|
| 170 |
+
``*args``
|
| 171 |
+
Variable length argument to be used by the Tool.
|
| 172 |
+
``**kwargs``
|
| 173 |
+
`toggled` if present and True, sets the initial state of the Tool
|
| 174 |
+
Arbitrary keyword arguments to be consumed by the Tool
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
radio_group = None
|
| 178 |
+
"""
|
| 179 |
+
Attribute to group 'radio' like tools (mutually exclusive).
|
| 180 |
+
|
| 181 |
+
`str` that identifies the group or **None** if not belonging to a group.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
cursor = None
|
| 185 |
+
"""Cursor to use when the tool is active."""
|
| 186 |
+
|
| 187 |
+
default_toggled = False
|
| 188 |
+
"""Default of toggled state."""
|
| 189 |
+
|
| 190 |
+
def __init__(self, *args, **kwargs):
|
| 191 |
+
self._toggled = kwargs.pop('toggled', self.default_toggled)
|
| 192 |
+
super().__init__(*args, **kwargs)
|
| 193 |
+
|
| 194 |
+
def trigger(self, sender, event, data=None):
|
| 195 |
+
"""Calls `enable` or `disable` based on `toggled` value."""
|
| 196 |
+
if self._toggled:
|
| 197 |
+
self.disable(event)
|
| 198 |
+
else:
|
| 199 |
+
self.enable(event)
|
| 200 |
+
self._toggled = not self._toggled
|
| 201 |
+
|
| 202 |
+
def enable(self, event=None):
|
| 203 |
+
"""
|
| 204 |
+
Enable the toggle tool.
|
| 205 |
+
|
| 206 |
+
`trigger` calls this method when `toggled` is False.
|
| 207 |
+
"""
|
| 208 |
+
pass
|
| 209 |
+
|
| 210 |
+
def disable(self, event=None):
|
| 211 |
+
"""
|
| 212 |
+
Disable the toggle tool.
|
| 213 |
+
|
| 214 |
+
`trigger` call this method when `toggled` is True.
|
| 215 |
+
|
| 216 |
+
This can happen in different circumstances.
|
| 217 |
+
|
| 218 |
+
* Click on the toolbar tool button.
|
| 219 |
+
* Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
|
| 220 |
+
* Another `ToolToggleBase` derived tool is triggered
|
| 221 |
+
(from the same `.ToolManager`).
|
| 222 |
+
"""
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
@property
|
| 226 |
+
def toggled(self):
|
| 227 |
+
"""State of the toggled tool."""
|
| 228 |
+
return self._toggled
|
| 229 |
+
|
| 230 |
+
def set_figure(self, figure):
|
| 231 |
+
toggled = self.toggled
|
| 232 |
+
if toggled:
|
| 233 |
+
if self.figure:
|
| 234 |
+
self.trigger(self, None)
|
| 235 |
+
else:
|
| 236 |
+
# if no figure the internal state is not changed
|
| 237 |
+
# we change it here so next call to trigger will change it back
|
| 238 |
+
self._toggled = False
|
| 239 |
+
super().set_figure(figure)
|
| 240 |
+
if toggled:
|
| 241 |
+
if figure:
|
| 242 |
+
self.trigger(self, None)
|
| 243 |
+
else:
|
| 244 |
+
# if there is no figure, trigger won't change the internal
|
| 245 |
+
# state we change it back
|
| 246 |
+
self._toggled = True
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class ToolSetCursor(ToolBase):
|
| 250 |
+
"""
|
| 251 |
+
Change to the current cursor while inaxes.
|
| 252 |
+
|
| 253 |
+
This tool, keeps track of all `ToolToggleBase` derived tools, and updates
|
| 254 |
+
the cursor when a tool gets triggered.
|
| 255 |
+
"""
|
| 256 |
+
def __init__(self, *args, **kwargs):
|
| 257 |
+
super().__init__(*args, **kwargs)
|
| 258 |
+
self._id_drag = None
|
| 259 |
+
self._current_tool = None
|
| 260 |
+
self._default_cursor = cursors.POINTER
|
| 261 |
+
self._last_cursor = self._default_cursor
|
| 262 |
+
self.toolmanager.toolmanager_connect('tool_added_event',
|
| 263 |
+
self._add_tool_cbk)
|
| 264 |
+
for tool in self.toolmanager.tools.values(): # process current tools
|
| 265 |
+
self._add_tool_cbk(mpl.backend_managers.ToolEvent(
|
| 266 |
+
'tool_added_event', self.toolmanager, tool))
|
| 267 |
+
|
| 268 |
+
def set_figure(self, figure):
|
| 269 |
+
if self._id_drag:
|
| 270 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 271 |
+
super().set_figure(figure)
|
| 272 |
+
if figure:
|
| 273 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 274 |
+
'motion_notify_event', self._set_cursor_cbk)
|
| 275 |
+
|
| 276 |
+
def _add_tool_cbk(self, event):
|
| 277 |
+
"""Process every newly added tool."""
|
| 278 |
+
if getattr(event.tool, 'cursor', None) is not None:
|
| 279 |
+
self.toolmanager.toolmanager_connect(
|
| 280 |
+
f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk)
|
| 281 |
+
|
| 282 |
+
def _tool_trigger_cbk(self, event):
|
| 283 |
+
self._current_tool = event.tool if event.tool.toggled else None
|
| 284 |
+
self._set_cursor_cbk(event.canvasevent)
|
| 285 |
+
|
| 286 |
+
def _set_cursor_cbk(self, event):
|
| 287 |
+
if not event or not self.canvas:
|
| 288 |
+
return
|
| 289 |
+
if (self._current_tool and getattr(event, "inaxes", None)
|
| 290 |
+
and event.inaxes.get_navigate()):
|
| 291 |
+
if self._last_cursor != self._current_tool.cursor:
|
| 292 |
+
self.canvas.set_cursor(self._current_tool.cursor)
|
| 293 |
+
self._last_cursor = self._current_tool.cursor
|
| 294 |
+
elif self._last_cursor != self._default_cursor:
|
| 295 |
+
self.canvas.set_cursor(self._default_cursor)
|
| 296 |
+
self._last_cursor = self._default_cursor
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class ToolCursorPosition(ToolBase):
|
| 300 |
+
"""
|
| 301 |
+
Send message with the current pointer position.
|
| 302 |
+
|
| 303 |
+
This tool runs in the background reporting the position of the cursor.
|
| 304 |
+
"""
|
| 305 |
+
def __init__(self, *args, **kwargs):
|
| 306 |
+
self._id_drag = None
|
| 307 |
+
super().__init__(*args, **kwargs)
|
| 308 |
+
|
| 309 |
+
def set_figure(self, figure):
|
| 310 |
+
if self._id_drag:
|
| 311 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 312 |
+
super().set_figure(figure)
|
| 313 |
+
if figure:
|
| 314 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 315 |
+
'motion_notify_event', self.send_message)
|
| 316 |
+
|
| 317 |
+
def send_message(self, event):
|
| 318 |
+
"""Call `matplotlib.backend_managers.ToolManager.message_event`."""
|
| 319 |
+
if self.toolmanager.messagelock.locked():
|
| 320 |
+
return
|
| 321 |
+
|
| 322 |
+
from matplotlib.backend_bases import NavigationToolbar2
|
| 323 |
+
message = NavigationToolbar2._mouse_event_to_message(event)
|
| 324 |
+
self.toolmanager.message_event(message, self)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class RubberbandBase(ToolBase):
|
| 328 |
+
"""Draw and remove a rubberband."""
|
| 329 |
+
def trigger(self, sender, event, data=None):
|
| 330 |
+
"""Call `draw_rubberband` or `remove_rubberband` based on data."""
|
| 331 |
+
if not self.figure.canvas.widgetlock.available(sender):
|
| 332 |
+
return
|
| 333 |
+
if data is not None:
|
| 334 |
+
self.draw_rubberband(*data)
|
| 335 |
+
else:
|
| 336 |
+
self.remove_rubberband()
|
| 337 |
+
|
| 338 |
+
def draw_rubberband(self, *data):
|
| 339 |
+
"""
|
| 340 |
+
Draw rubberband.
|
| 341 |
+
|
| 342 |
+
This method must get implemented per backend.
|
| 343 |
+
"""
|
| 344 |
+
raise NotImplementedError
|
| 345 |
+
|
| 346 |
+
def remove_rubberband(self):
|
| 347 |
+
"""
|
| 348 |
+
Remove rubberband.
|
| 349 |
+
|
| 350 |
+
This method should get implemented per backend.
|
| 351 |
+
"""
|
| 352 |
+
pass
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class ToolQuit(ToolBase):
|
| 356 |
+
"""Tool to call the figure manager destroy method."""
|
| 357 |
+
|
| 358 |
+
description = 'Quit the figure'
|
| 359 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
|
| 360 |
+
|
| 361 |
+
def trigger(self, sender, event, data=None):
|
| 362 |
+
Gcf.destroy_fig(self.figure)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class ToolQuitAll(ToolBase):
|
| 366 |
+
"""Tool to call the figure manager destroy method."""
|
| 367 |
+
|
| 368 |
+
description = 'Quit all figures'
|
| 369 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
|
| 370 |
+
|
| 371 |
+
def trigger(self, sender, event, data=None):
|
| 372 |
+
Gcf.destroy_all()
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class ToolGrid(ToolBase):
|
| 376 |
+
"""Tool to toggle the major grids of the figure."""
|
| 377 |
+
|
| 378 |
+
description = 'Toggle major grids'
|
| 379 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
|
| 380 |
+
|
| 381 |
+
def trigger(self, sender, event, data=None):
|
| 382 |
+
sentinel = str(uuid.uuid4())
|
| 383 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid`
|
| 384 |
+
# to a unique key and sending an appropriate event.
|
| 385 |
+
with (cbook._setattr_cm(event, key=sentinel),
|
| 386 |
+
mpl.rc_context({'keymap.grid': sentinel})):
|
| 387 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class ToolMinorGrid(ToolBase):
|
| 391 |
+
"""Tool to toggle the major and minor grids of the figure."""
|
| 392 |
+
|
| 393 |
+
description = 'Toggle major and minor grids'
|
| 394 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
|
| 395 |
+
|
| 396 |
+
def trigger(self, sender, event, data=None):
|
| 397 |
+
sentinel = str(uuid.uuid4())
|
| 398 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
|
| 399 |
+
# to a unique key and sending an appropriate event.
|
| 400 |
+
with (cbook._setattr_cm(event, key=sentinel),
|
| 401 |
+
mpl.rc_context({'keymap.grid_minor': sentinel})):
|
| 402 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class ToolFullScreen(ToolBase):
|
| 406 |
+
"""Tool to toggle full screen."""
|
| 407 |
+
|
| 408 |
+
description = 'Toggle fullscreen mode'
|
| 409 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
|
| 410 |
+
|
| 411 |
+
def trigger(self, sender, event, data=None):
|
| 412 |
+
self.figure.canvas.manager.full_screen_toggle()
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class AxisScaleBase(ToolToggleBase):
|
| 416 |
+
"""Base Tool to toggle between linear and logarithmic."""
|
| 417 |
+
|
| 418 |
+
def trigger(self, sender, event, data=None):
|
| 419 |
+
if event.inaxes is None:
|
| 420 |
+
return
|
| 421 |
+
super().trigger(sender, event, data)
|
| 422 |
+
|
| 423 |
+
def enable(self, event=None):
|
| 424 |
+
self.set_scale(event.inaxes, 'log')
|
| 425 |
+
self.figure.canvas.draw_idle()
|
| 426 |
+
|
| 427 |
+
def disable(self, event=None):
|
| 428 |
+
self.set_scale(event.inaxes, 'linear')
|
| 429 |
+
self.figure.canvas.draw_idle()
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class ToolYScale(AxisScaleBase):
|
| 433 |
+
"""Tool to toggle between linear and logarithmic scales on the Y axis."""
|
| 434 |
+
|
| 435 |
+
description = 'Toggle scale Y axis'
|
| 436 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
|
| 437 |
+
|
| 438 |
+
def set_scale(self, ax, scale):
|
| 439 |
+
ax.set_yscale(scale)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class ToolXScale(AxisScaleBase):
|
| 443 |
+
"""Tool to toggle between linear and logarithmic scales on the X axis."""
|
| 444 |
+
|
| 445 |
+
description = 'Toggle scale X axis'
|
| 446 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
|
| 447 |
+
|
| 448 |
+
def set_scale(self, ax, scale):
|
| 449 |
+
ax.set_xscale(scale)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class ToolViewsPositions(ToolBase):
|
| 453 |
+
"""
|
| 454 |
+
Auxiliary Tool to handle changes in views and positions.
|
| 455 |
+
|
| 456 |
+
Runs in the background and should get used by all the tools that
|
| 457 |
+
need to access the figure's history of views and positions, e.g.
|
| 458 |
+
|
| 459 |
+
* `ToolZoom`
|
| 460 |
+
* `ToolPan`
|
| 461 |
+
* `ToolHome`
|
| 462 |
+
* `ToolBack`
|
| 463 |
+
* `ToolForward`
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
def __init__(self, *args, **kwargs):
|
| 467 |
+
self.views = WeakKeyDictionary()
|
| 468 |
+
self.positions = WeakKeyDictionary()
|
| 469 |
+
self.home_views = WeakKeyDictionary()
|
| 470 |
+
super().__init__(*args, **kwargs)
|
| 471 |
+
|
| 472 |
+
def add_figure(self, figure):
|
| 473 |
+
"""Add the current figure to the stack of views and positions."""
|
| 474 |
+
|
| 475 |
+
if figure not in self.views:
|
| 476 |
+
self.views[figure] = cbook._Stack()
|
| 477 |
+
self.positions[figure] = cbook._Stack()
|
| 478 |
+
self.home_views[figure] = WeakKeyDictionary()
|
| 479 |
+
# Define Home
|
| 480 |
+
self.push_current(figure)
|
| 481 |
+
# Make sure we add a home view for new Axes as they're added
|
| 482 |
+
figure.add_axobserver(lambda fig: self.update_home_views(fig))
|
| 483 |
+
|
| 484 |
+
def clear(self, figure):
|
| 485 |
+
"""Reset the Axes stack."""
|
| 486 |
+
if figure in self.views:
|
| 487 |
+
self.views[figure].clear()
|
| 488 |
+
self.positions[figure].clear()
|
| 489 |
+
self.home_views[figure].clear()
|
| 490 |
+
self.update_home_views()
|
| 491 |
+
|
| 492 |
+
def update_view(self):
|
| 493 |
+
"""
|
| 494 |
+
Update the view limits and position for each Axes from the current
|
| 495 |
+
stack position. If any Axes are present in the figure that aren't in
|
| 496 |
+
the current stack position, use the home view limits for those Axes and
|
| 497 |
+
don't update *any* positions.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
views = self.views[self.figure]()
|
| 501 |
+
if views is None:
|
| 502 |
+
return
|
| 503 |
+
pos = self.positions[self.figure]()
|
| 504 |
+
if pos is None:
|
| 505 |
+
return
|
| 506 |
+
home_views = self.home_views[self.figure]
|
| 507 |
+
all_axes = self.figure.get_axes()
|
| 508 |
+
for a in all_axes:
|
| 509 |
+
if a in views:
|
| 510 |
+
cur_view = views[a]
|
| 511 |
+
else:
|
| 512 |
+
cur_view = home_views[a]
|
| 513 |
+
a._set_view(cur_view)
|
| 514 |
+
|
| 515 |
+
if set(all_axes).issubset(pos):
|
| 516 |
+
for a in all_axes:
|
| 517 |
+
# Restore both the original and modified positions
|
| 518 |
+
a._set_position(pos[a][0], 'original')
|
| 519 |
+
a._set_position(pos[a][1], 'active')
|
| 520 |
+
|
| 521 |
+
self.figure.canvas.draw_idle()
|
| 522 |
+
|
| 523 |
+
def push_current(self, figure=None):
|
| 524 |
+
"""
|
| 525 |
+
Push the current view limits and position onto their respective stacks.
|
| 526 |
+
"""
|
| 527 |
+
if not figure:
|
| 528 |
+
figure = self.figure
|
| 529 |
+
views = WeakKeyDictionary()
|
| 530 |
+
pos = WeakKeyDictionary()
|
| 531 |
+
for a in figure.get_axes():
|
| 532 |
+
views[a] = a._get_view()
|
| 533 |
+
pos[a] = self._axes_pos(a)
|
| 534 |
+
self.views[figure].push(views)
|
| 535 |
+
self.positions[figure].push(pos)
|
| 536 |
+
|
| 537 |
+
def _axes_pos(self, ax):
|
| 538 |
+
"""
|
| 539 |
+
Return the original and modified positions for the specified Axes.
|
| 540 |
+
|
| 541 |
+
Parameters
|
| 542 |
+
----------
|
| 543 |
+
ax : matplotlib.axes.Axes
|
| 544 |
+
The `.Axes` to get the positions for.
|
| 545 |
+
|
| 546 |
+
Returns
|
| 547 |
+
-------
|
| 548 |
+
original_position, modified_position
|
| 549 |
+
A tuple of the original and modified positions.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
return (ax.get_position(True).frozen(),
|
| 553 |
+
ax.get_position().frozen())
|
| 554 |
+
|
| 555 |
+
def update_home_views(self, figure=None):
|
| 556 |
+
"""
|
| 557 |
+
Make sure that ``self.home_views`` has an entry for all Axes present
|
| 558 |
+
in the figure.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
if not figure:
|
| 562 |
+
figure = self.figure
|
| 563 |
+
for a in figure.get_axes():
|
| 564 |
+
if a not in self.home_views[figure]:
|
| 565 |
+
self.home_views[figure][a] = a._get_view()
|
| 566 |
+
|
| 567 |
+
def home(self):
|
| 568 |
+
"""Recall the first view and position from the stack."""
|
| 569 |
+
self.views[self.figure].home()
|
| 570 |
+
self.positions[self.figure].home()
|
| 571 |
+
|
| 572 |
+
def back(self):
|
| 573 |
+
"""Back one step in the stack of views and positions."""
|
| 574 |
+
self.views[self.figure].back()
|
| 575 |
+
self.positions[self.figure].back()
|
| 576 |
+
|
| 577 |
+
def forward(self):
|
| 578 |
+
"""Forward one step in the stack of views and positions."""
|
| 579 |
+
self.views[self.figure].forward()
|
| 580 |
+
self.positions[self.figure].forward()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
class ViewsPositionsBase(ToolBase):
|
| 584 |
+
"""Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
|
| 585 |
+
|
| 586 |
+
_on_trigger = None
|
| 587 |
+
|
| 588 |
+
def trigger(self, sender, event, data=None):
|
| 589 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 590 |
+
getattr(self.toolmanager.get_tool(_views_positions),
|
| 591 |
+
self._on_trigger)()
|
| 592 |
+
self.toolmanager.get_tool(_views_positions).update_view()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class ToolHome(ViewsPositionsBase):
|
| 596 |
+
"""Restore the original view limits."""
|
| 597 |
+
|
| 598 |
+
description = 'Reset original view'
|
| 599 |
+
image = 'mpl-data/images/home'
|
| 600 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
|
| 601 |
+
_on_trigger = 'home'
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class ToolBack(ViewsPositionsBase):
|
| 605 |
+
"""Move back up the view limits stack."""
|
| 606 |
+
|
| 607 |
+
description = 'Back to previous view'
|
| 608 |
+
image = 'mpl-data/images/back'
|
| 609 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
|
| 610 |
+
_on_trigger = 'back'
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class ToolForward(ViewsPositionsBase):
|
| 614 |
+
"""Move forward in the view lim stack."""
|
| 615 |
+
|
| 616 |
+
description = 'Forward to next view'
|
| 617 |
+
image = 'mpl-data/images/forward'
|
| 618 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
|
| 619 |
+
_on_trigger = 'forward'
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class ConfigureSubplotsBase(ToolBase):
|
| 623 |
+
"""Base tool for the configuration of subplots."""
|
| 624 |
+
|
| 625 |
+
description = 'Configure subplots'
|
| 626 |
+
image = 'mpl-data/images/subplots'
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class SaveFigureBase(ToolBase):
|
| 630 |
+
"""Base tool for figure saving."""
|
| 631 |
+
|
| 632 |
+
description = 'Save the figure'
|
| 633 |
+
image = 'mpl-data/images/filesave'
|
| 634 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class ZoomPanBase(ToolToggleBase):
|
| 638 |
+
"""Base class for `ToolZoom` and `ToolPan`."""
|
| 639 |
+
def __init__(self, *args):
|
| 640 |
+
super().__init__(*args)
|
| 641 |
+
self._button_pressed = None
|
| 642 |
+
self._xypress = None
|
| 643 |
+
self._idPress = None
|
| 644 |
+
self._idRelease = None
|
| 645 |
+
self._idScroll = None
|
| 646 |
+
self.base_scale = 2.
|
| 647 |
+
self.scrollthresh = .5 # .5 second scroll threshold
|
| 648 |
+
self.lastscroll = time.time()-self.scrollthresh
|
| 649 |
+
|
| 650 |
+
def enable(self, event=None):
|
| 651 |
+
"""Connect press/release events and lock the canvas."""
|
| 652 |
+
self.figure.canvas.widgetlock(self)
|
| 653 |
+
self._idPress = self.figure.canvas.mpl_connect(
|
| 654 |
+
'button_press_event', self._press)
|
| 655 |
+
self._idRelease = self.figure.canvas.mpl_connect(
|
| 656 |
+
'button_release_event', self._release)
|
| 657 |
+
self._idScroll = self.figure.canvas.mpl_connect(
|
| 658 |
+
'scroll_event', self.scroll_zoom)
|
| 659 |
+
|
| 660 |
+
def disable(self, event=None):
|
| 661 |
+
"""Release the canvas and disconnect press/release events."""
|
| 662 |
+
self._cancel_action()
|
| 663 |
+
self.figure.canvas.widgetlock.release(self)
|
| 664 |
+
self.figure.canvas.mpl_disconnect(self._idPress)
|
| 665 |
+
self.figure.canvas.mpl_disconnect(self._idRelease)
|
| 666 |
+
self.figure.canvas.mpl_disconnect(self._idScroll)
|
| 667 |
+
|
| 668 |
+
def trigger(self, sender, event, data=None):
|
| 669 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 670 |
+
super().trigger(sender, event, data)
|
| 671 |
+
new_navigate_mode = self.name.upper() if self.toggled else None
|
| 672 |
+
for ax in self.figure.axes:
|
| 673 |
+
ax.set_navigate_mode(new_navigate_mode)
|
| 674 |
+
|
| 675 |
+
def scroll_zoom(self, event):
|
| 676 |
+
# https://gist.github.com/tacaswell/3144287
|
| 677 |
+
if event.inaxes is None:
|
| 678 |
+
return
|
| 679 |
+
|
| 680 |
+
if event.button == 'up':
|
| 681 |
+
# deal with zoom in
|
| 682 |
+
scl = self.base_scale
|
| 683 |
+
elif event.button == 'down':
|
| 684 |
+
# deal with zoom out
|
| 685 |
+
scl = 1/self.base_scale
|
| 686 |
+
else:
|
| 687 |
+
# deal with something that should never happen
|
| 688 |
+
scl = 1
|
| 689 |
+
|
| 690 |
+
ax = event.inaxes
|
| 691 |
+
ax._set_view_from_bbox([event.x, event.y, scl])
|
| 692 |
+
|
| 693 |
+
# If last scroll was done within the timing threshold, delete the
|
| 694 |
+
# previous view
|
| 695 |
+
if (time.time()-self.lastscroll) < self.scrollthresh:
|
| 696 |
+
self.toolmanager.get_tool(_views_positions).back()
|
| 697 |
+
|
| 698 |
+
self.figure.canvas.draw_idle() # force re-draw
|
| 699 |
+
|
| 700 |
+
self.lastscroll = time.time()
|
| 701 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class ToolZoom(ZoomPanBase):
|
| 705 |
+
"""A Tool for zooming using a rectangle selector."""
|
| 706 |
+
|
| 707 |
+
description = 'Zoom to rectangle'
|
| 708 |
+
image = 'mpl-data/images/zoom_to_rect'
|
| 709 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
|
| 710 |
+
cursor = cursors.SELECT_REGION
|
| 711 |
+
radio_group = 'default'
|
| 712 |
+
|
| 713 |
+
def __init__(self, *args):
|
| 714 |
+
super().__init__(*args)
|
| 715 |
+
self._ids_zoom = []
|
| 716 |
+
|
| 717 |
+
def _cancel_action(self):
|
| 718 |
+
for zoom_id in self._ids_zoom:
|
| 719 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 720 |
+
self.toolmanager.trigger_tool('rubberband', self)
|
| 721 |
+
self.figure.canvas.draw_idle()
|
| 722 |
+
self._xypress = None
|
| 723 |
+
self._button_pressed = None
|
| 724 |
+
self._ids_zoom = []
|
| 725 |
+
return
|
| 726 |
+
|
| 727 |
+
def _press(self, event):
|
| 728 |
+
"""Callback for mouse button presses in zoom-to-rectangle mode."""
|
| 729 |
+
|
| 730 |
+
# If we're already in the middle of a zoom, pressing another
|
| 731 |
+
# button works to "cancel"
|
| 732 |
+
if self._ids_zoom:
|
| 733 |
+
self._cancel_action()
|
| 734 |
+
|
| 735 |
+
if event.button == 1:
|
| 736 |
+
self._button_pressed = 1
|
| 737 |
+
elif event.button == 3:
|
| 738 |
+
self._button_pressed = 3
|
| 739 |
+
else:
|
| 740 |
+
self._cancel_action()
|
| 741 |
+
return
|
| 742 |
+
|
| 743 |
+
x, y = event.x, event.y
|
| 744 |
+
|
| 745 |
+
self._xypress = []
|
| 746 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 747 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 748 |
+
a.get_navigate() and a.can_zoom()):
|
| 749 |
+
self._xypress.append((x, y, a, i, a._get_view()))
|
| 750 |
+
|
| 751 |
+
id1 = self.figure.canvas.mpl_connect(
|
| 752 |
+
'motion_notify_event', self._mouse_move)
|
| 753 |
+
id2 = self.figure.canvas.mpl_connect(
|
| 754 |
+
'key_press_event', self._switch_on_zoom_mode)
|
| 755 |
+
id3 = self.figure.canvas.mpl_connect(
|
| 756 |
+
'key_release_event', self._switch_off_zoom_mode)
|
| 757 |
+
|
| 758 |
+
self._ids_zoom = id1, id2, id3
|
| 759 |
+
self._zoom_mode = event.key
|
| 760 |
+
|
| 761 |
+
def _switch_on_zoom_mode(self, event):
|
| 762 |
+
self._zoom_mode = event.key
|
| 763 |
+
self._mouse_move(event)
|
| 764 |
+
|
| 765 |
+
def _switch_off_zoom_mode(self, event):
|
| 766 |
+
self._zoom_mode = None
|
| 767 |
+
self._mouse_move(event)
|
| 768 |
+
|
| 769 |
+
def _mouse_move(self, event):
|
| 770 |
+
"""Callback for mouse moves in zoom-to-rectangle mode."""
|
| 771 |
+
|
| 772 |
+
if self._xypress:
|
| 773 |
+
x, y = event.x, event.y
|
| 774 |
+
lastx, lasty, a, ind, view = self._xypress[0]
|
| 775 |
+
(x1, y1), (x2, y2) = np.clip(
|
| 776 |
+
[[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
|
| 777 |
+
if self._zoom_mode == "x":
|
| 778 |
+
y1, y2 = a.bbox.intervaly
|
| 779 |
+
elif self._zoom_mode == "y":
|
| 780 |
+
x1, x2 = a.bbox.intervalx
|
| 781 |
+
self.toolmanager.trigger_tool(
|
| 782 |
+
'rubberband', self, data=(x1, y1, x2, y2))
|
| 783 |
+
|
| 784 |
+
def _release(self, event):
|
| 785 |
+
"""Callback for mouse button releases in zoom-to-rectangle mode."""
|
| 786 |
+
|
| 787 |
+
for zoom_id in self._ids_zoom:
|
| 788 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 789 |
+
self._ids_zoom = []
|
| 790 |
+
|
| 791 |
+
if not self._xypress:
|
| 792 |
+
self._cancel_action()
|
| 793 |
+
return
|
| 794 |
+
|
| 795 |
+
done_ax = []
|
| 796 |
+
|
| 797 |
+
for cur_xypress in self._xypress:
|
| 798 |
+
x, y = event.x, event.y
|
| 799 |
+
lastx, lasty, a, _ind, view = cur_xypress
|
| 800 |
+
# ignore singular clicks - 5 pixels is a threshold
|
| 801 |
+
if abs(x - lastx) < 5 or abs(y - lasty) < 5:
|
| 802 |
+
self._cancel_action()
|
| 803 |
+
return
|
| 804 |
+
|
| 805 |
+
# detect twinx, twiny Axes and avoid double zooming
|
| 806 |
+
twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
|
| 807 |
+
twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
|
| 808 |
+
done_ax.append(a)
|
| 809 |
+
|
| 810 |
+
if self._button_pressed == 1:
|
| 811 |
+
direction = 'in'
|
| 812 |
+
elif self._button_pressed == 3:
|
| 813 |
+
direction = 'out'
|
| 814 |
+
else:
|
| 815 |
+
continue
|
| 816 |
+
|
| 817 |
+
a._set_view_from_bbox((lastx, lasty, x, y), direction,
|
| 818 |
+
self._zoom_mode, twinx, twiny)
|
| 819 |
+
|
| 820 |
+
self._zoom_mode = None
|
| 821 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 822 |
+
self._cancel_action()
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class ToolPan(ZoomPanBase):
|
| 826 |
+
"""Pan Axes with left mouse, zoom with right."""
|
| 827 |
+
|
| 828 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
|
| 829 |
+
description = 'Pan axes with left mouse, zoom with right'
|
| 830 |
+
image = 'mpl-data/images/move'
|
| 831 |
+
cursor = cursors.MOVE
|
| 832 |
+
radio_group = 'default'
|
| 833 |
+
|
| 834 |
+
def __init__(self, *args):
|
| 835 |
+
super().__init__(*args)
|
| 836 |
+
self._id_drag = None
|
| 837 |
+
|
| 838 |
+
def _cancel_action(self):
|
| 839 |
+
self._button_pressed = None
|
| 840 |
+
self._xypress = []
|
| 841 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 842 |
+
self.toolmanager.messagelock.release(self)
|
| 843 |
+
self.figure.canvas.draw_idle()
|
| 844 |
+
|
| 845 |
+
def _press(self, event):
|
| 846 |
+
if event.button == 1:
|
| 847 |
+
self._button_pressed = 1
|
| 848 |
+
elif event.button == 3:
|
| 849 |
+
self._button_pressed = 3
|
| 850 |
+
else:
|
| 851 |
+
self._cancel_action()
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
x, y = event.x, event.y
|
| 855 |
+
|
| 856 |
+
self._xypress = []
|
| 857 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 858 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 859 |
+
a.get_navigate() and a.can_pan()):
|
| 860 |
+
a.start_pan(x, y, event.button)
|
| 861 |
+
self._xypress.append((a, i))
|
| 862 |
+
self.toolmanager.messagelock(self)
|
| 863 |
+
self._id_drag = self.figure.canvas.mpl_connect(
|
| 864 |
+
'motion_notify_event', self._mouse_move)
|
| 865 |
+
|
| 866 |
+
def _release(self, event):
|
| 867 |
+
if self._button_pressed is None:
|
| 868 |
+
self._cancel_action()
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 872 |
+
self.toolmanager.messagelock.release(self)
|
| 873 |
+
|
| 874 |
+
for a, _ind in self._xypress:
|
| 875 |
+
a.end_pan()
|
| 876 |
+
if not self._xypress:
|
| 877 |
+
self._cancel_action()
|
| 878 |
+
return
|
| 879 |
+
|
| 880 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 881 |
+
self._cancel_action()
|
| 882 |
+
|
| 883 |
+
def _mouse_move(self, event):
|
| 884 |
+
for a, _ind in self._xypress:
|
| 885 |
+
# safer to use the recorded button at the _press than current
|
| 886 |
+
# button: # multiple button can get pressed during motion...
|
| 887 |
+
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
|
| 888 |
+
self.toolmanager.canvas.draw_idle()
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
class ToolHelpBase(ToolBase):
|
| 892 |
+
description = 'Print tool list, shortcuts and description'
|
| 893 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
|
| 894 |
+
image = 'mpl-data/images/help'
|
| 895 |
+
|
| 896 |
+
@staticmethod
|
| 897 |
+
def format_shortcut(key_sequence):
|
| 898 |
+
"""
|
| 899 |
+
Convert a shortcut string from the notation used in rc config to the
|
| 900 |
+
standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
|
| 901 |
+
"""
|
| 902 |
+
return (key_sequence if len(key_sequence) == 1 else
|
| 903 |
+
re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
|
| 904 |
+
|
| 905 |
+
def _format_tool_keymap(self, name):
|
| 906 |
+
keymaps = self.toolmanager.get_tool_keymap(name)
|
| 907 |
+
return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
|
| 908 |
+
|
| 909 |
+
def _get_help_entries(self):
|
| 910 |
+
return [(name, self._format_tool_keymap(name), tool.description)
|
| 911 |
+
for name, tool in sorted(self.toolmanager.tools.items())
|
| 912 |
+
if tool.description]
|
| 913 |
+
|
| 914 |
+
def _get_help_text(self):
|
| 915 |
+
entries = self._get_help_entries()
|
| 916 |
+
entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
|
| 917 |
+
return "\n".join(entries)
|
| 918 |
+
|
| 919 |
+
def _get_help_html(self):
|
| 920 |
+
fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
|
| 921 |
+
rows = [fmt.format(
|
| 922 |
+
"<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
|
| 923 |
+
rows += [fmt.format(*row) for row in self._get_help_entries()]
|
| 924 |
+
return ("<style>td {padding: 0px 4px}</style>"
|
| 925 |
+
"<table><thead>" + rows[0] + "</thead>"
|
| 926 |
+
"<tbody>".join(rows[1:]) + "</tbody></table>")
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
class ToolCopyToClipboardBase(ToolBase):
|
| 930 |
+
"""Tool to copy the figure to the clipboard."""
|
| 931 |
+
|
| 932 |
+
description = 'Copy the canvas figure to clipboard'
|
| 933 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
|
| 934 |
+
|
| 935 |
+
def trigger(self, *args, **kwargs):
|
| 936 |
+
message = "Copy tool is not available"
|
| 937 |
+
self.toolmanager.message_event(message, self)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
|
| 941 |
+
'zoom': ToolZoom, 'pan': ToolPan,
|
| 942 |
+
'subplots': ConfigureSubplotsBase,
|
| 943 |
+
'save': SaveFigureBase,
|
| 944 |
+
'grid': ToolGrid,
|
| 945 |
+
'grid_minor': ToolMinorGrid,
|
| 946 |
+
'fullscreen': ToolFullScreen,
|
| 947 |
+
'quit': ToolQuit,
|
| 948 |
+
'quit_all': ToolQuitAll,
|
| 949 |
+
'xscale': ToolXScale,
|
| 950 |
+
'yscale': ToolYScale,
|
| 951 |
+
'position': ToolCursorPosition,
|
| 952 |
+
_views_positions: ToolViewsPositions,
|
| 953 |
+
'cursor': ToolSetCursor,
|
| 954 |
+
'rubberband': RubberbandBase,
|
| 955 |
+
'help': ToolHelpBase,
|
| 956 |
+
'copy': ToolCopyToClipboardBase,
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
|
| 960 |
+
['zoompan', ['pan', 'zoom', 'subplots']],
|
| 961 |
+
['io', ['save', 'help']]]
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def add_tools_to_manager(toolmanager, tools=default_tools):
|
| 965 |
+
"""
|
| 966 |
+
Add multiple tools to a `.ToolManager`.
|
| 967 |
+
|
| 968 |
+
Parameters
|
| 969 |
+
----------
|
| 970 |
+
toolmanager : `.backend_managers.ToolManager`
|
| 971 |
+
Manager to which the tools are added.
|
| 972 |
+
tools : {str: class_like}, optional
|
| 973 |
+
The tools to add in a {name: tool} dict, see
|
| 974 |
+
`.backend_managers.ToolManager.add_tool` for more info.
|
| 975 |
+
"""
|
| 976 |
+
|
| 977 |
+
for name, tool in tools.items():
|
| 978 |
+
toolmanager.add_tool(name, tool)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def add_tools_to_container(container, tools=default_toolbar_tools):
|
| 982 |
+
"""
|
| 983 |
+
Add multiple tools to the container.
|
| 984 |
+
|
| 985 |
+
Parameters
|
| 986 |
+
----------
|
| 987 |
+
container : Container
|
| 988 |
+
`.backend_bases.ToolContainerBase` object that will get the tools
|
| 989 |
+
added.
|
| 990 |
+
tools : list, optional
|
| 991 |
+
List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
|
| 992 |
+
where the tools ``[tool1, tool2, ...]`` will display in group1.
|
| 993 |
+
See `.backend_bases.ToolContainerBase.add_tool` for details.
|
| 994 |
+
"""
|
| 995 |
+
|
| 996 |
+
for group, grouptools in tools:
|
| 997 |
+
for position, tool in enumerate(grouptools):
|
| 998 |
+
container.add_tool(tool, group, position)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backend_tools.pyi
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
from matplotlib import cbook
|
| 3 |
+
from matplotlib.axes import Axes
|
| 4 |
+
from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase
|
| 5 |
+
from matplotlib.backend_managers import ToolManager, ToolEvent
|
| 6 |
+
from matplotlib.figure import Figure
|
| 7 |
+
from matplotlib.scale import ScaleBase
|
| 8 |
+
|
| 9 |
+
from typing import Any, cast
|
| 10 |
+
|
| 11 |
+
class Cursors(enum.IntEnum):
|
| 12 |
+
POINTER = cast(int, ...)
|
| 13 |
+
HAND = cast(int, ...)
|
| 14 |
+
SELECT_REGION = cast(int, ...)
|
| 15 |
+
MOVE = cast(int, ...)
|
| 16 |
+
WAIT = cast(int, ...)
|
| 17 |
+
RESIZE_HORIZONTAL = cast(int, ...)
|
| 18 |
+
RESIZE_VERTICAL = cast(int, ...)
|
| 19 |
+
|
| 20 |
+
cursors = Cursors
|
| 21 |
+
|
| 22 |
+
class ToolBase:
|
| 23 |
+
@property
|
| 24 |
+
def default_keymap(self) -> list[str] | None: ...
|
| 25 |
+
description: str | None
|
| 26 |
+
image: str | None
|
| 27 |
+
def __init__(self, toolmanager: ToolManager, name: str) -> None: ...
|
| 28 |
+
@property
|
| 29 |
+
def name(self) -> str: ...
|
| 30 |
+
@property
|
| 31 |
+
def toolmanager(self) -> ToolManager: ...
|
| 32 |
+
@property
|
| 33 |
+
def canvas(self) -> FigureCanvasBase | None: ...
|
| 34 |
+
@property
|
| 35 |
+
def figure(self) -> Figure | None: ...
|
| 36 |
+
@figure.setter
|
| 37 |
+
def figure(self, figure: Figure | None) -> None: ...
|
| 38 |
+
def set_figure(self, figure: Figure | None) -> None: ...
|
| 39 |
+
def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ...
|
| 40 |
+
|
| 41 |
+
class ToolToggleBase(ToolBase):
|
| 42 |
+
radio_group: str | None
|
| 43 |
+
cursor: Cursors | None
|
| 44 |
+
default_toggled: bool
|
| 45 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 46 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 47 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 48 |
+
@property
|
| 49 |
+
def toggled(self) -> bool: ...
|
| 50 |
+
def set_figure(self, figure: Figure | None) -> None: ...
|
| 51 |
+
|
| 52 |
+
class ToolSetCursor(ToolBase): ...
|
| 53 |
+
|
| 54 |
+
class ToolCursorPosition(ToolBase):
|
| 55 |
+
def send_message(self, event: ToolEvent) -> None: ...
|
| 56 |
+
|
| 57 |
+
class RubberbandBase(ToolBase):
|
| 58 |
+
def draw_rubberband(self, *data) -> None: ...
|
| 59 |
+
def remove_rubberband(self) -> None: ...
|
| 60 |
+
|
| 61 |
+
class ToolQuit(ToolBase): ...
|
| 62 |
+
class ToolQuitAll(ToolBase): ...
|
| 63 |
+
class ToolGrid(ToolBase): ...
|
| 64 |
+
class ToolMinorGrid(ToolBase): ...
|
| 65 |
+
class ToolFullScreen(ToolBase): ...
|
| 66 |
+
|
| 67 |
+
class AxisScaleBase(ToolToggleBase):
|
| 68 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 69 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 70 |
+
|
| 71 |
+
class ToolYScale(AxisScaleBase):
|
| 72 |
+
def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ...
|
| 73 |
+
|
| 74 |
+
class ToolXScale(AxisScaleBase):
|
| 75 |
+
def set_scale(self, ax, scale: str | ScaleBase) -> None: ...
|
| 76 |
+
|
| 77 |
+
class ToolViewsPositions(ToolBase):
|
| 78 |
+
views: dict[Figure | Axes, cbook._Stack]
|
| 79 |
+
positions: dict[Figure | Axes, cbook._Stack]
|
| 80 |
+
home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]]
|
| 81 |
+
def add_figure(self, figure: Figure) -> None: ...
|
| 82 |
+
def clear(self, figure: Figure) -> None: ...
|
| 83 |
+
def update_view(self) -> None: ...
|
| 84 |
+
def push_current(self, figure: Figure | None = ...) -> None: ...
|
| 85 |
+
def update_home_views(self, figure: Figure | None = ...) -> None: ...
|
| 86 |
+
def home(self) -> None: ...
|
| 87 |
+
def back(self) -> None: ...
|
| 88 |
+
def forward(self) -> None: ...
|
| 89 |
+
|
| 90 |
+
class ViewsPositionsBase(ToolBase): ...
|
| 91 |
+
class ToolHome(ViewsPositionsBase): ...
|
| 92 |
+
class ToolBack(ViewsPositionsBase): ...
|
| 93 |
+
class ToolForward(ViewsPositionsBase): ...
|
| 94 |
+
class ConfigureSubplotsBase(ToolBase): ...
|
| 95 |
+
class SaveFigureBase(ToolBase): ...
|
| 96 |
+
|
| 97 |
+
class ZoomPanBase(ToolToggleBase):
|
| 98 |
+
base_scale: float
|
| 99 |
+
scrollthresh: float
|
| 100 |
+
lastscroll: float
|
| 101 |
+
def __init__(self, *args) -> None: ...
|
| 102 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 103 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 104 |
+
def scroll_zoom(self, event: ToolEvent) -> None: ...
|
| 105 |
+
|
| 106 |
+
class ToolZoom(ZoomPanBase): ...
|
| 107 |
+
class ToolPan(ZoomPanBase): ...
|
| 108 |
+
|
| 109 |
+
class ToolHelpBase(ToolBase):
|
| 110 |
+
@staticmethod
|
| 111 |
+
def format_shortcut(key_sequence: str) -> str: ...
|
| 112 |
+
|
| 113 |
+
class ToolCopyToClipboardBase(ToolBase): ...
|
| 114 |
+
|
| 115 |
+
default_tools: dict[str, ToolBase]
|
| 116 |
+
default_toolbar_tools: list[list[str | list[str]]]
|
| 117 |
+
|
| 118 |
+
def add_tools_to_manager(
|
| 119 |
+
toolmanager: ToolManager, tools: dict[str, type[ToolBase]] = ...
|
| 120 |
+
) -> None: ...
|
| 121 |
+
def add_tools_to_container(container: ToolContainerBase, tools: list[Any] = ...) -> None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .registry import BackendFilter, backend_registry # noqa: F401
|
| 2 |
+
|
| 3 |
+
# NOTE: plt.switch_backend() (called at import time) will add a "backend"
|
| 4 |
+
# attribute here for backcompat.
|
| 5 |
+
_QT_FORCE_QT5_BINDING = False
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (331 Bytes). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/__pycache__/registry.cpython-311.pyc
ADDED
|
Binary file (16.1 kB). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:12e2efe19653282533381d2849e142cfdabdbbeef1bb0fc83fe051358f9579dc
|
| 3 |
+
size 771600
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.pyi
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_gtk.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Common code for GTK3 and GTK4 backends.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
import matplotlib as mpl
|
| 9 |
+
from matplotlib import _api, backend_tools, cbook
|
| 10 |
+
from matplotlib._pylab_helpers import Gcf
|
| 11 |
+
from matplotlib.backend_bases import (
|
| 12 |
+
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
|
| 13 |
+
TimerBase)
|
| 14 |
+
from matplotlib.backend_tools import Cursors
|
| 15 |
+
|
| 16 |
+
import gi
|
| 17 |
+
# The GTK3/GTK4 backends will have already called `gi.require_version` to set
|
| 18 |
+
# the desired GTK.
|
| 19 |
+
from gi.repository import Gdk, Gio, GLib, Gtk
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
gi.require_foreign("cairo")
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
raise ImportError("Gtk-based backends require cairo") from e
|
| 26 |
+
|
| 27 |
+
_log = logging.getLogger(__name__)
|
| 28 |
+
_application = None # Placeholder
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _shutdown_application(app):
|
| 32 |
+
# The application might prematurely shut down if Ctrl-C'd out of IPython,
|
| 33 |
+
# so close all windows.
|
| 34 |
+
for win in app.get_windows():
|
| 35 |
+
win.close()
|
| 36 |
+
# The PyGObject wrapper incorrectly thinks that None is not allowed, or we
|
| 37 |
+
# would call this:
|
| 38 |
+
# Gio.Application.set_default(None)
|
| 39 |
+
# Instead, we set this property and ignore default applications with it:
|
| 40 |
+
app._created_by_matplotlib = True
|
| 41 |
+
global _application
|
| 42 |
+
_application = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _create_application():
|
| 46 |
+
global _application
|
| 47 |
+
|
| 48 |
+
if _application is None:
|
| 49 |
+
app = Gio.Application.get_default()
|
| 50 |
+
if app is None or getattr(app, '_created_by_matplotlib', False):
|
| 51 |
+
# display_is_valid returns False only if on Linux and neither X11
|
| 52 |
+
# nor Wayland display can be opened.
|
| 53 |
+
if not mpl._c_internal_utils.display_is_valid():
|
| 54 |
+
raise RuntimeError('Invalid DISPLAY variable')
|
| 55 |
+
_application = Gtk.Application.new('org.matplotlib.Matplotlib3',
|
| 56 |
+
Gio.ApplicationFlags.NON_UNIQUE)
|
| 57 |
+
# The activate signal must be connected, but we don't care for
|
| 58 |
+
# handling it, since we don't do any remote processing.
|
| 59 |
+
_application.connect('activate', lambda *args, **kwargs: None)
|
| 60 |
+
_application.connect('shutdown', _shutdown_application)
|
| 61 |
+
_application.register()
|
| 62 |
+
cbook._setup_new_guiapp()
|
| 63 |
+
else:
|
| 64 |
+
_application = app
|
| 65 |
+
|
| 66 |
+
return _application
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def mpl_to_gtk_cursor_name(mpl_cursor):
|
| 70 |
+
return _api.check_getitem({
|
| 71 |
+
Cursors.MOVE: "move",
|
| 72 |
+
Cursors.HAND: "pointer",
|
| 73 |
+
Cursors.POINTER: "default",
|
| 74 |
+
Cursors.SELECT_REGION: "crosshair",
|
| 75 |
+
Cursors.WAIT: "wait",
|
| 76 |
+
Cursors.RESIZE_HORIZONTAL: "ew-resize",
|
| 77 |
+
Cursors.RESIZE_VERTICAL: "ns-resize",
|
| 78 |
+
}, cursor=mpl_cursor)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class TimerGTK(TimerBase):
|
| 82 |
+
"""Subclass of `.TimerBase` using GTK timer events."""
|
| 83 |
+
|
| 84 |
+
def __init__(self, *args, **kwargs):
|
| 85 |
+
self._timer = None
|
| 86 |
+
super().__init__(*args, **kwargs)
|
| 87 |
+
|
| 88 |
+
def _timer_start(self):
|
| 89 |
+
# Need to stop it, otherwise we potentially leak a timer id that will
|
| 90 |
+
# never be stopped.
|
| 91 |
+
self._timer_stop()
|
| 92 |
+
self._timer = GLib.timeout_add(self._interval, self._on_timer)
|
| 93 |
+
|
| 94 |
+
def _timer_stop(self):
|
| 95 |
+
if self._timer is not None:
|
| 96 |
+
GLib.source_remove(self._timer)
|
| 97 |
+
self._timer = None
|
| 98 |
+
|
| 99 |
+
def _timer_set_interval(self):
|
| 100 |
+
# Only stop and restart it if the timer has already been started.
|
| 101 |
+
if self._timer is not None:
|
| 102 |
+
self._timer_stop()
|
| 103 |
+
self._timer_start()
|
| 104 |
+
|
| 105 |
+
def _on_timer(self):
|
| 106 |
+
super()._on_timer()
|
| 107 |
+
|
| 108 |
+
# Gtk timeout_add() requires that the callback returns True if it
|
| 109 |
+
# is to be called again.
|
| 110 |
+
if self.callbacks and not self._single:
|
| 111 |
+
return True
|
| 112 |
+
else:
|
| 113 |
+
self._timer = None
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class _FigureCanvasGTK(FigureCanvasBase):
|
| 118 |
+
_timer_cls = TimerGTK
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class _FigureManagerGTK(FigureManagerBase):
|
| 122 |
+
"""
|
| 123 |
+
Attributes
|
| 124 |
+
----------
|
| 125 |
+
canvas : `FigureCanvas`
|
| 126 |
+
The FigureCanvas instance
|
| 127 |
+
num : int or str
|
| 128 |
+
The Figure number
|
| 129 |
+
toolbar : Gtk.Toolbar or Gtk.Box
|
| 130 |
+
The toolbar
|
| 131 |
+
vbox : Gtk.VBox
|
| 132 |
+
The Gtk.VBox containing the canvas and toolbar
|
| 133 |
+
window : Gtk.Window
|
| 134 |
+
The Gtk.Window
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def __init__(self, canvas, num):
|
| 138 |
+
self._gtk_ver = gtk_ver = Gtk.get_major_version()
|
| 139 |
+
|
| 140 |
+
app = _create_application()
|
| 141 |
+
self.window = Gtk.Window()
|
| 142 |
+
app.add_window(self.window)
|
| 143 |
+
super().__init__(canvas, num)
|
| 144 |
+
|
| 145 |
+
if gtk_ver == 3:
|
| 146 |
+
icon_ext = "png" if sys.platform == "win32" else "svg"
|
| 147 |
+
self.window.set_icon_from_file(
|
| 148 |
+
str(cbook._get_data_path(f"images/matplotlib.{icon_ext}")))
|
| 149 |
+
|
| 150 |
+
self.vbox = Gtk.Box()
|
| 151 |
+
self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
|
| 152 |
+
|
| 153 |
+
if gtk_ver == 3:
|
| 154 |
+
self.window.add(self.vbox)
|
| 155 |
+
self.vbox.show()
|
| 156 |
+
self.canvas.show()
|
| 157 |
+
self.vbox.pack_start(self.canvas, True, True, 0)
|
| 158 |
+
elif gtk_ver == 4:
|
| 159 |
+
self.window.set_child(self.vbox)
|
| 160 |
+
self.vbox.prepend(self.canvas)
|
| 161 |
+
|
| 162 |
+
# calculate size for window
|
| 163 |
+
w, h = self.canvas.get_width_height()
|
| 164 |
+
|
| 165 |
+
if self.toolbar is not None:
|
| 166 |
+
if gtk_ver == 3:
|
| 167 |
+
self.toolbar.show()
|
| 168 |
+
self.vbox.pack_end(self.toolbar, False, False, 0)
|
| 169 |
+
elif gtk_ver == 4:
|
| 170 |
+
sw = Gtk.ScrolledWindow(vscrollbar_policy=Gtk.PolicyType.NEVER)
|
| 171 |
+
sw.set_child(self.toolbar)
|
| 172 |
+
self.vbox.append(sw)
|
| 173 |
+
min_size, nat_size = self.toolbar.get_preferred_size()
|
| 174 |
+
h += nat_size.height
|
| 175 |
+
|
| 176 |
+
self.window.set_default_size(w, h)
|
| 177 |
+
|
| 178 |
+
self._destroying = False
|
| 179 |
+
self.window.connect("destroy", lambda *args: Gcf.destroy(self))
|
| 180 |
+
self.window.connect({3: "delete_event", 4: "close-request"}[gtk_ver],
|
| 181 |
+
lambda *args: Gcf.destroy(self))
|
| 182 |
+
if mpl.is_interactive():
|
| 183 |
+
self.window.show()
|
| 184 |
+
self.canvas.draw_idle()
|
| 185 |
+
|
| 186 |
+
self.canvas.grab_focus()
|
| 187 |
+
|
| 188 |
+
def destroy(self, *args):
|
| 189 |
+
if self._destroying:
|
| 190 |
+
# Otherwise, this can be called twice when the user presses 'q',
|
| 191 |
+
# which calls Gcf.destroy(self), then this destroy(), then triggers
|
| 192 |
+
# Gcf.destroy(self) once again via
|
| 193 |
+
# `connect("destroy", lambda *args: Gcf.destroy(self))`.
|
| 194 |
+
return
|
| 195 |
+
self._destroying = True
|
| 196 |
+
self.window.destroy()
|
| 197 |
+
self.canvas.destroy()
|
| 198 |
+
|
| 199 |
+
@classmethod
|
| 200 |
+
def start_main_loop(cls):
|
| 201 |
+
global _application
|
| 202 |
+
if _application is None:
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
_application.run() # Quits when all added windows close.
|
| 207 |
+
except KeyboardInterrupt:
|
| 208 |
+
# Ensure all windows can process their close event from
|
| 209 |
+
# _shutdown_application.
|
| 210 |
+
context = GLib.MainContext.default()
|
| 211 |
+
while context.pending():
|
| 212 |
+
context.iteration(True)
|
| 213 |
+
raise
|
| 214 |
+
finally:
|
| 215 |
+
# Running after quit is undefined, so create a new one next time.
|
| 216 |
+
_application = None
|
| 217 |
+
|
| 218 |
+
def show(self):
|
| 219 |
+
# show the figure window
|
| 220 |
+
self.window.show()
|
| 221 |
+
self.canvas.draw()
|
| 222 |
+
if mpl.rcParams["figure.raise_window"]:
|
| 223 |
+
meth_name = {3: "get_window", 4: "get_surface"}[self._gtk_ver]
|
| 224 |
+
if getattr(self.window, meth_name)():
|
| 225 |
+
self.window.present()
|
| 226 |
+
else:
|
| 227 |
+
# If this is called by a callback early during init,
|
| 228 |
+
# self.window (a GtkWindow) may not have an associated
|
| 229 |
+
# low-level GdkWindow (on GTK3) or GdkSurface (on GTK4) yet,
|
| 230 |
+
# and present() would crash.
|
| 231 |
+
_api.warn_external("Cannot raise window yet to be setup")
|
| 232 |
+
|
| 233 |
+
def full_screen_toggle(self):
|
| 234 |
+
is_fullscreen = {
|
| 235 |
+
3: lambda w: (w.get_window().get_state()
|
| 236 |
+
& Gdk.WindowState.FULLSCREEN),
|
| 237 |
+
4: lambda w: w.is_fullscreen(),
|
| 238 |
+
}[self._gtk_ver]
|
| 239 |
+
if is_fullscreen(self.window):
|
| 240 |
+
self.window.unfullscreen()
|
| 241 |
+
else:
|
| 242 |
+
self.window.fullscreen()
|
| 243 |
+
|
| 244 |
+
def get_window_title(self):
|
| 245 |
+
return self.window.get_title()
|
| 246 |
+
|
| 247 |
+
def set_window_title(self, title):
|
| 248 |
+
self.window.set_title(title)
|
| 249 |
+
|
| 250 |
+
def resize(self, width, height):
|
| 251 |
+
width = int(width / self.canvas.device_pixel_ratio)
|
| 252 |
+
height = int(height / self.canvas.device_pixel_ratio)
|
| 253 |
+
if self.toolbar:
|
| 254 |
+
min_size, nat_size = self.toolbar.get_preferred_size()
|
| 255 |
+
height += nat_size.height
|
| 256 |
+
canvas_size = self.canvas.get_allocation()
|
| 257 |
+
if self._gtk_ver >= 4 or canvas_size.width == canvas_size.height == 1:
|
| 258 |
+
# A canvas size of (1, 1) cannot exist in most cases, because
|
| 259 |
+
# window decorations would prevent such a small window. This call
|
| 260 |
+
# must be before the window has been mapped and widgets have been
|
| 261 |
+
# sized, so just change the window's starting size.
|
| 262 |
+
self.window.set_default_size(width, height)
|
| 263 |
+
else:
|
| 264 |
+
self.window.resize(width, height)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class _NavigationToolbar2GTK(NavigationToolbar2):
|
| 268 |
+
# Must be implemented in GTK3/GTK4 backends:
|
| 269 |
+
# * __init__
|
| 270 |
+
# * save_figure
|
| 271 |
+
|
| 272 |
+
def set_message(self, s):
|
| 273 |
+
escaped = GLib.markup_escape_text(s)
|
| 274 |
+
self.message.set_markup(f'<small>{escaped}</small>')
|
| 275 |
+
|
| 276 |
+
def draw_rubberband(self, event, x0, y0, x1, y1):
|
| 277 |
+
height = self.canvas.figure.bbox.height
|
| 278 |
+
y1 = height - y1
|
| 279 |
+
y0 = height - y0
|
| 280 |
+
rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
|
| 281 |
+
self.canvas._draw_rubberband(rect)
|
| 282 |
+
|
| 283 |
+
def remove_rubberband(self):
|
| 284 |
+
self.canvas._draw_rubberband(None)
|
| 285 |
+
|
| 286 |
+
def _update_buttons_checked(self):
|
| 287 |
+
for name, active in [("Pan", "PAN"), ("Zoom", "ZOOM")]:
|
| 288 |
+
button = self._gtk_ids.get(name)
|
| 289 |
+
if button:
|
| 290 |
+
with button.handler_block(button._signal_handler):
|
| 291 |
+
button.set_active(self.mode.name == active)
|
| 292 |
+
|
| 293 |
+
def pan(self, *args):
|
| 294 |
+
super().pan(*args)
|
| 295 |
+
self._update_buttons_checked()
|
| 296 |
+
|
| 297 |
+
def zoom(self, *args):
|
| 298 |
+
super().zoom(*args)
|
| 299 |
+
self._update_buttons_checked()
|
| 300 |
+
|
| 301 |
+
def set_history_buttons(self):
|
| 302 |
+
can_backward = self._nav_stack._pos > 0
|
| 303 |
+
can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
|
| 304 |
+
if 'Back' in self._gtk_ids:
|
| 305 |
+
self._gtk_ids['Back'].set_sensitive(can_backward)
|
| 306 |
+
if 'Forward' in self._gtk_ids:
|
| 307 |
+
self._gtk_ids['Forward'].set_sensitive(can_forward)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class RubberbandGTK(backend_tools.RubberbandBase):
|
| 311 |
+
def draw_rubberband(self, x0, y0, x1, y1):
|
| 312 |
+
_NavigationToolbar2GTK.draw_rubberband(
|
| 313 |
+
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
|
| 314 |
+
|
| 315 |
+
def remove_rubberband(self):
|
| 316 |
+
_NavigationToolbar2GTK.remove_rubberband(
|
| 317 |
+
self._make_classic_style_pseudo_toolbar())
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class ConfigureSubplotsGTK(backend_tools.ConfigureSubplotsBase):
|
| 321 |
+
def trigger(self, *args):
|
| 322 |
+
_NavigationToolbar2GTK.configure_subplots(self, None)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class _BackendGTK(_Backend):
|
| 326 |
+
backend_version = "{}.{}.{}".format(
|
| 327 |
+
Gtk.get_major_version(),
|
| 328 |
+
Gtk.get_minor_version(),
|
| 329 |
+
Gtk.get_micro_version(),
|
| 330 |
+
)
|
| 331 |
+
mainloop = _FigureManagerGTK.start_main_loop
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_pdf_ps.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Common functionality between the PDF and PS backends.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import functools
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
from fontTools import subset
|
| 10 |
+
|
| 11 |
+
import matplotlib as mpl
|
| 12 |
+
from .. import font_manager, ft2font
|
| 13 |
+
from .._afm import AFM
|
| 14 |
+
from ..backend_bases import RendererBase
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@functools.lru_cache(50)
|
| 18 |
+
def _cached_get_afm_from_fname(fname):
|
| 19 |
+
with open(fname, "rb") as fh:
|
| 20 |
+
return AFM(fh)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_glyphs_subset(fontfile, characters):
|
| 24 |
+
"""
|
| 25 |
+
Subset a TTF font
|
| 26 |
+
|
| 27 |
+
Reads the named fontfile and restricts the font to the characters.
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
fontfile : str
|
| 32 |
+
Path to the font file
|
| 33 |
+
characters : str
|
| 34 |
+
Continuous set of characters to include in subset
|
| 35 |
+
|
| 36 |
+
Returns
|
| 37 |
+
-------
|
| 38 |
+
fontTools.ttLib.ttFont.TTFont
|
| 39 |
+
An open font object representing the subset, which needs to
|
| 40 |
+
be closed by the caller.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
options = subset.Options(glyph_names=True, recommended_glyphs=True)
|
| 44 |
+
|
| 45 |
+
# Prevent subsetting extra tables.
|
| 46 |
+
options.drop_tables += [
|
| 47 |
+
'FFTM', # FontForge Timestamp.
|
| 48 |
+
'PfEd', # FontForge personal table.
|
| 49 |
+
'BDF', # X11 BDF header.
|
| 50 |
+
'meta', # Metadata stores design/supported languages (meaningless for subsets).
|
| 51 |
+
'MERG', # Merge Table.
|
| 52 |
+
'TSIV', # Microsoft Visual TrueType extension.
|
| 53 |
+
'Zapf', # Information about the individual glyphs in the font.
|
| 54 |
+
'bdat', # The bitmap data table.
|
| 55 |
+
'bloc', # The bitmap location table.
|
| 56 |
+
'cidg', # CID to Glyph ID table (Apple Advanced Typography).
|
| 57 |
+
'fdsc', # The font descriptors table.
|
| 58 |
+
'feat', # Feature name table (Apple Advanced Typography).
|
| 59 |
+
'fmtx', # The Font Metrics Table.
|
| 60 |
+
'fond', # Data-fork font information (Apple Advanced Typography).
|
| 61 |
+
'just', # The justification table (Apple Advanced Typography).
|
| 62 |
+
'kerx', # An extended kerning table (Apple Advanced Typography).
|
| 63 |
+
'ltag', # Language Tag.
|
| 64 |
+
'morx', # Extended Glyph Metamorphosis Table.
|
| 65 |
+
'trak', # Tracking table.
|
| 66 |
+
'xref', # The cross-reference table (some Apple font tooling information).
|
| 67 |
+
]
|
| 68 |
+
# if fontfile is a ttc, specify font number
|
| 69 |
+
if fontfile.endswith(".ttc"):
|
| 70 |
+
options.font_number = 0
|
| 71 |
+
|
| 72 |
+
font = subset.load_font(fontfile, options)
|
| 73 |
+
subsetter = subset.Subsetter(options=options)
|
| 74 |
+
subsetter.populate(text=characters)
|
| 75 |
+
subsetter.subset(font)
|
| 76 |
+
return font
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def font_as_file(font):
|
| 80 |
+
"""
|
| 81 |
+
Convert a TTFont object into a file-like object.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
font : fontTools.ttLib.ttFont.TTFont
|
| 86 |
+
A font object
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
BytesIO
|
| 91 |
+
A file object with the font saved into it
|
| 92 |
+
"""
|
| 93 |
+
fh = BytesIO()
|
| 94 |
+
font.save(fh, reorderTables=False)
|
| 95 |
+
return fh
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class CharacterTracker:
|
| 99 |
+
"""
|
| 100 |
+
Helper for font subsetting by the pdf and ps backends.
|
| 101 |
+
|
| 102 |
+
Maintains a mapping of font paths to the set of character codepoints that
|
| 103 |
+
are being used from that font.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self):
|
| 107 |
+
self.used = {}
|
| 108 |
+
|
| 109 |
+
def track(self, font, s):
|
| 110 |
+
"""Record that string *s* is being typeset using font *font*."""
|
| 111 |
+
char_to_font = font._get_fontmap(s)
|
| 112 |
+
for _c, _f in char_to_font.items():
|
| 113 |
+
self.used.setdefault(_f.fname, set()).add(ord(_c))
|
| 114 |
+
|
| 115 |
+
def track_glyph(self, font, glyph):
|
| 116 |
+
"""Record that codepoint *glyph* is being typeset using font *font*."""
|
| 117 |
+
self.used.setdefault(font.fname, set()).add(glyph)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class RendererPDFPSBase(RendererBase):
|
| 121 |
+
# The following attributes must be defined by the subclasses:
|
| 122 |
+
# - _afm_font_dir
|
| 123 |
+
# - _use_afm_rc_name
|
| 124 |
+
|
| 125 |
+
def __init__(self, width, height):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.width = width
|
| 128 |
+
self.height = height
|
| 129 |
+
|
| 130 |
+
def flipy(self):
|
| 131 |
+
# docstring inherited
|
| 132 |
+
return False # y increases from bottom to top.
|
| 133 |
+
|
| 134 |
+
def option_scale_image(self):
|
| 135 |
+
# docstring inherited
|
| 136 |
+
return True # PDF and PS support arbitrary image scaling.
|
| 137 |
+
|
| 138 |
+
def option_image_nocomposite(self):
|
| 139 |
+
# docstring inherited
|
| 140 |
+
# Decide whether to composite image based on rcParam value.
|
| 141 |
+
return not mpl.rcParams["image.composite_image"]
|
| 142 |
+
|
| 143 |
+
def get_canvas_width_height(self):
|
| 144 |
+
# docstring inherited
|
| 145 |
+
return self.width * 72.0, self.height * 72.0
|
| 146 |
+
|
| 147 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 148 |
+
# docstring inherited
|
| 149 |
+
if ismath == "TeX":
|
| 150 |
+
return super().get_text_width_height_descent(s, prop, ismath)
|
| 151 |
+
elif ismath:
|
| 152 |
+
parse = self._text2path.mathtext_parser.parse(s, 72, prop)
|
| 153 |
+
return parse.width, parse.height, parse.depth
|
| 154 |
+
elif mpl.rcParams[self._use_afm_rc_name]:
|
| 155 |
+
font = self._get_font_afm(prop)
|
| 156 |
+
l, b, w, h, d = font.get_str_bbox_and_descent(s)
|
| 157 |
+
scale = prop.get_size_in_points() / 1000
|
| 158 |
+
w *= scale
|
| 159 |
+
h *= scale
|
| 160 |
+
d *= scale
|
| 161 |
+
return w, h, d
|
| 162 |
+
else:
|
| 163 |
+
font = self._get_font_ttf(prop)
|
| 164 |
+
font.set_text(s, 0.0, flags=ft2font.LoadFlags.NO_HINTING)
|
| 165 |
+
w, h = font.get_width_height()
|
| 166 |
+
d = font.get_descent()
|
| 167 |
+
scale = 1 / 64
|
| 168 |
+
w *= scale
|
| 169 |
+
h *= scale
|
| 170 |
+
d *= scale
|
| 171 |
+
return w, h, d
|
| 172 |
+
|
| 173 |
+
def _get_font_afm(self, prop):
|
| 174 |
+
fname = font_manager.findfont(
|
| 175 |
+
prop, fontext="afm", directory=self._afm_font_dir)
|
| 176 |
+
return _cached_get_afm_from_fname(fname)
|
| 177 |
+
|
| 178 |
+
def _get_font_ttf(self, prop):
|
| 179 |
+
fnames = font_manager.fontManager._find_fonts_by_props(prop)
|
| 180 |
+
try:
|
| 181 |
+
font = font_manager.get_font(fnames)
|
| 182 |
+
font.clear()
|
| 183 |
+
font.set_size(prop.get_size_in_points(), 72)
|
| 184 |
+
return font
|
| 185 |
+
except RuntimeError:
|
| 186 |
+
logging.getLogger(__name__).warning(
|
| 187 |
+
"The PostScript/PDF backend does not currently "
|
| 188 |
+
"support the selected font (%s).", fnames)
|
| 189 |
+
raise
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_backend_tk.py
ADDED
|
@@ -0,0 +1,1105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
import weakref
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
import logging
|
| 5 |
+
import math
|
| 6 |
+
import os.path
|
| 7 |
+
import pathlib
|
| 8 |
+
import sys
|
| 9 |
+
import tkinter as tk
|
| 10 |
+
import tkinter.filedialog
|
| 11 |
+
import tkinter.font
|
| 12 |
+
import tkinter.messagebox
|
| 13 |
+
from tkinter.simpledialog import SimpleDialog
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from PIL import Image, ImageTk
|
| 17 |
+
|
| 18 |
+
import matplotlib as mpl
|
| 19 |
+
from matplotlib import _api, backend_tools, cbook, _c_internal_utils
|
| 20 |
+
from matplotlib.backend_bases import (
|
| 21 |
+
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
|
| 22 |
+
TimerBase, ToolContainerBase, cursors, _Mode, MouseButton,
|
| 23 |
+
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
|
| 24 |
+
from matplotlib._pylab_helpers import Gcf
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from . import _tkagg
|
| 28 |
+
from ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET
|
| 29 |
+
except ImportError as e:
|
| 30 |
+
# catch incompatibility of python-build-standalone with Tk
|
| 31 |
+
cause1 = getattr(e, '__cause__', None)
|
| 32 |
+
cause2 = getattr(cause1, '__cause__', None)
|
| 33 |
+
if (isinstance(cause1, ImportError) and
|
| 34 |
+
isinstance(cause2, AttributeError) and
|
| 35 |
+
"'_tkinter' has no attribute '__file__'" in str(cause2)):
|
| 36 |
+
|
| 37 |
+
is_uv_python = "/uv/python" in (os.path.realpath(sys.executable))
|
| 38 |
+
if is_uv_python:
|
| 39 |
+
raise ImportError(
|
| 40 |
+
"Failed to import tkagg backend. You appear to be using an outdated "
|
| 41 |
+
"version of uv's managed Python distribution which is not compatible "
|
| 42 |
+
"with Tk. Please upgrade to the latest uv version, then update "
|
| 43 |
+
"Python with: `uv python upgrade --reinstall`"
|
| 44 |
+
) from e
|
| 45 |
+
else:
|
| 46 |
+
raise ImportError(
|
| 47 |
+
"Failed to import tkagg backend. This is likely caused by using a "
|
| 48 |
+
"Python executable based on python-build-standalone, which is not "
|
| 49 |
+
"compatible with Tk. Recent versions of python-build-standalone "
|
| 50 |
+
"should be compatible with Tk. Please update your python version "
|
| 51 |
+
"or select another backend."
|
| 52 |
+
) from e
|
| 53 |
+
else:
|
| 54 |
+
raise
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
_log = logging.getLogger(__name__)
|
| 58 |
+
cursord = {
|
| 59 |
+
cursors.MOVE: "fleur",
|
| 60 |
+
cursors.HAND: "hand2",
|
| 61 |
+
cursors.POINTER: "arrow",
|
| 62 |
+
cursors.SELECT_REGION: "crosshair",
|
| 63 |
+
cursors.WAIT: "watch",
|
| 64 |
+
cursors.RESIZE_HORIZONTAL: "sb_h_double_arrow",
|
| 65 |
+
cursors.RESIZE_VERTICAL: "sb_v_double_arrow",
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@contextmanager
|
| 70 |
+
def _restore_foreground_window_at_end():
|
| 71 |
+
foreground = _c_internal_utils.Win32_GetForegroundWindow()
|
| 72 |
+
try:
|
| 73 |
+
yield
|
| 74 |
+
finally:
|
| 75 |
+
if foreground and mpl.rcParams['tk.window_focus']:
|
| 76 |
+
_c_internal_utils.Win32_SetForegroundWindow(foreground)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
_blit_args = {}
|
| 80 |
+
# Initialize to a non-empty string that is not a Tcl command
|
| 81 |
+
_blit_tcl_name = "mpl_blit_" + uuid.uuid4().hex
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _blit(argsid):
|
| 85 |
+
"""
|
| 86 |
+
Thin wrapper to blit called via tkapp.call.
|
| 87 |
+
|
| 88 |
+
*argsid* is a unique string identifier to fetch the correct arguments from
|
| 89 |
+
the ``_blit_args`` dict, since arguments cannot be passed directly.
|
| 90 |
+
"""
|
| 91 |
+
photoimage, data, offsets, bbox, comp_rule = _blit_args.pop(argsid)
|
| 92 |
+
if not photoimage.tk.call("info", "commands", photoimage):
|
| 93 |
+
return
|
| 94 |
+
_tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets,
|
| 95 |
+
bbox)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def blit(photoimage, aggimage, offsets, bbox=None):
|
| 99 |
+
"""
|
| 100 |
+
Blit *aggimage* to *photoimage*.
|
| 101 |
+
|
| 102 |
+
*offsets* is a tuple describing how to fill the ``offset`` field of the
|
| 103 |
+
``Tk_PhotoImageBlock`` struct: it should be (0, 1, 2, 3) for RGBA8888 data,
|
| 104 |
+
(2, 1, 0, 3) for little-endian ARBG32 (i.e. GBRA8888) data and (1, 2, 3, 0)
|
| 105 |
+
for big-endian ARGB32 (i.e. ARGB8888) data.
|
| 106 |
+
|
| 107 |
+
If *bbox* is passed, it defines the region that gets blitted. That region
|
| 108 |
+
will be composed with the previous data according to the alpha channel.
|
| 109 |
+
Blitting will be clipped to pixels inside the canvas, including silently
|
| 110 |
+
doing nothing if the *bbox* region is entirely outside the canvas.
|
| 111 |
+
|
| 112 |
+
Tcl events must be dispatched to trigger a blit from a non-Tcl thread.
|
| 113 |
+
"""
|
| 114 |
+
data = np.asarray(aggimage)
|
| 115 |
+
height, width = data.shape[:2]
|
| 116 |
+
if bbox is not None:
|
| 117 |
+
(x1, y1), (x2, y2) = bbox.__array__()
|
| 118 |
+
x1 = max(math.floor(x1), 0)
|
| 119 |
+
x2 = min(math.ceil(x2), width)
|
| 120 |
+
y1 = max(math.floor(y1), 0)
|
| 121 |
+
y2 = min(math.ceil(y2), height)
|
| 122 |
+
if (x1 > x2) or (y1 > y2):
|
| 123 |
+
return
|
| 124 |
+
bboxptr = (x1, x2, y1, y2)
|
| 125 |
+
comp_rule = TK_PHOTO_COMPOSITE_OVERLAY
|
| 126 |
+
else:
|
| 127 |
+
bboxptr = (0, width, 0, height)
|
| 128 |
+
comp_rule = TK_PHOTO_COMPOSITE_SET
|
| 129 |
+
|
| 130 |
+
# NOTE: _tkagg.blit is thread unsafe and will crash the process if called
|
| 131 |
+
# from a thread (GH#13293). Instead of blanking and blitting here,
|
| 132 |
+
# use tkapp.call to post a cross-thread event if this function is called
|
| 133 |
+
# from a non-Tcl thread.
|
| 134 |
+
|
| 135 |
+
# tkapp.call coerces all arguments to strings, so to avoid string parsing
|
| 136 |
+
# within _blit, pack up the arguments into a global data structure.
|
| 137 |
+
args = photoimage, data, offsets, bboxptr, comp_rule
|
| 138 |
+
# Need a unique key to avoid thread races.
|
| 139 |
+
# Again, make the key a string to avoid string parsing in _blit.
|
| 140 |
+
argsid = str(id(args))
|
| 141 |
+
_blit_args[argsid] = args
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
photoimage.tk.call(_blit_tcl_name, argsid)
|
| 145 |
+
except tk.TclError as e:
|
| 146 |
+
if "invalid command name" not in str(e):
|
| 147 |
+
raise
|
| 148 |
+
photoimage.tk.createcommand(_blit_tcl_name, _blit)
|
| 149 |
+
photoimage.tk.call(_blit_tcl_name, argsid)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class TimerTk(TimerBase):
|
| 153 |
+
"""Subclass of `backend_bases.TimerBase` using Tk timer events."""
|
| 154 |
+
|
| 155 |
+
def __init__(self, parent, *args, **kwargs):
|
| 156 |
+
self._timer = None
|
| 157 |
+
super().__init__(*args, **kwargs)
|
| 158 |
+
self.parent = parent
|
| 159 |
+
|
| 160 |
+
def _timer_start(self):
|
| 161 |
+
self._timer_stop()
|
| 162 |
+
self._timer = self.parent.after(self._interval, self._on_timer)
|
| 163 |
+
|
| 164 |
+
def _timer_stop(self):
|
| 165 |
+
if self._timer is not None:
|
| 166 |
+
self.parent.after_cancel(self._timer)
|
| 167 |
+
self._timer = None
|
| 168 |
+
|
| 169 |
+
def _on_timer(self):
|
| 170 |
+
super()._on_timer()
|
| 171 |
+
# Tk after() is only a single shot, so we need to add code here to
|
| 172 |
+
# reset the timer if we're not operating in single shot mode. However,
|
| 173 |
+
# if _timer is None, this means that _timer_stop has been called; so
|
| 174 |
+
# don't recreate the timer in that case.
|
| 175 |
+
if not self._single and self._timer:
|
| 176 |
+
if self._interval > 0:
|
| 177 |
+
self._timer = self.parent.after(self._interval, self._on_timer)
|
| 178 |
+
else:
|
| 179 |
+
# Edge case: Tcl after 0 *prepends* events to the queue
|
| 180 |
+
# so a 0 interval does not allow any other events to run.
|
| 181 |
+
# This incantation is cancellable and runs as fast as possible
|
| 182 |
+
# while also allowing events and drawing every frame. GH#18236
|
| 183 |
+
self._timer = self.parent.after_idle(
|
| 184 |
+
lambda: self.parent.after(self._interval, self._on_timer)
|
| 185 |
+
)
|
| 186 |
+
else:
|
| 187 |
+
self._timer = None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class FigureCanvasTk(FigureCanvasBase):
|
| 191 |
+
required_interactive_framework = "tk"
|
| 192 |
+
manager_class = _api.classproperty(lambda cls: FigureManagerTk)
|
| 193 |
+
|
| 194 |
+
def __init__(self, figure=None, master=None):
|
| 195 |
+
super().__init__(figure)
|
| 196 |
+
self._idle_draw_id = None
|
| 197 |
+
self._event_loop_id = None
|
| 198 |
+
w, h = self.get_width_height(physical=True)
|
| 199 |
+
self._tkcanvas = tk.Canvas(
|
| 200 |
+
master=master, background="white",
|
| 201 |
+
width=w, height=h, borderwidth=0, highlightthickness=0)
|
| 202 |
+
self._tkphoto = tk.PhotoImage(
|
| 203 |
+
master=self._tkcanvas, width=w, height=h)
|
| 204 |
+
self._tkcanvas_image_region = self._tkcanvas.create_image(
|
| 205 |
+
w//2, h//2, image=self._tkphoto)
|
| 206 |
+
self._tkcanvas.bind("<Configure>", self.resize)
|
| 207 |
+
self._tkcanvas.bind("<Map>", self._update_device_pixel_ratio)
|
| 208 |
+
self._tkcanvas.bind("<Key>", self.key_press)
|
| 209 |
+
self._tkcanvas.bind("<Motion>", self.motion_notify_event)
|
| 210 |
+
self._tkcanvas.bind("<Enter>", self.enter_notify_event)
|
| 211 |
+
self._tkcanvas.bind("<Leave>", self.leave_notify_event)
|
| 212 |
+
self._tkcanvas.bind("<KeyRelease>", self.key_release)
|
| 213 |
+
for name in ["<Button-1>", "<Button-2>", "<Button-3>"]:
|
| 214 |
+
self._tkcanvas.bind(name, self.button_press_event)
|
| 215 |
+
for name in [
|
| 216 |
+
"<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>"]:
|
| 217 |
+
self._tkcanvas.bind(name, self.button_dblclick_event)
|
| 218 |
+
for name in [
|
| 219 |
+
"<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>"]:
|
| 220 |
+
self._tkcanvas.bind(name, self.button_release_event)
|
| 221 |
+
|
| 222 |
+
# Mouse wheel on Linux generates button 4/5 events
|
| 223 |
+
for name in "<Button-4>", "<Button-5>":
|
| 224 |
+
self._tkcanvas.bind(name, self.scroll_event)
|
| 225 |
+
# Mouse wheel for windows goes to the window with the focus.
|
| 226 |
+
# Since the canvas won't usually have the focus, bind the
|
| 227 |
+
# event to the window containing the canvas instead.
|
| 228 |
+
# See https://wiki.tcl-lang.org/3893 (mousewheel) for details
|
| 229 |
+
root = self._tkcanvas.winfo_toplevel()
|
| 230 |
+
|
| 231 |
+
# Prevent long-lived references via tkinter callback structure GH-24820
|
| 232 |
+
weakself = weakref.ref(self)
|
| 233 |
+
weakroot = weakref.ref(root)
|
| 234 |
+
|
| 235 |
+
def scroll_event_windows(event):
|
| 236 |
+
self = weakself()
|
| 237 |
+
if self is None:
|
| 238 |
+
root = weakroot()
|
| 239 |
+
if root is not None:
|
| 240 |
+
root.unbind("<MouseWheel>", scroll_event_windows_id)
|
| 241 |
+
return
|
| 242 |
+
return self.scroll_event_windows(event)
|
| 243 |
+
scroll_event_windows_id = root.bind("<MouseWheel>", scroll_event_windows, "+")
|
| 244 |
+
|
| 245 |
+
# Can't get destroy events by binding to _tkcanvas. Therefore, bind
|
| 246 |
+
# to the window and filter.
|
| 247 |
+
def filter_destroy(event):
|
| 248 |
+
self = weakself()
|
| 249 |
+
if self is None:
|
| 250 |
+
root = weakroot()
|
| 251 |
+
if root is not None:
|
| 252 |
+
root.unbind("<Destroy>", filter_destroy_id)
|
| 253 |
+
return
|
| 254 |
+
if event.widget is self._tkcanvas:
|
| 255 |
+
CloseEvent("close_event", self)._process()
|
| 256 |
+
filter_destroy_id = root.bind("<Destroy>", filter_destroy, "+")
|
| 257 |
+
|
| 258 |
+
self._tkcanvas.focus_set()
|
| 259 |
+
|
| 260 |
+
self._rubberband_rect_black = None
|
| 261 |
+
self._rubberband_rect_white = None
|
| 262 |
+
|
| 263 |
+
def _update_device_pixel_ratio(self, event=None):
|
| 264 |
+
ratio = None
|
| 265 |
+
if sys.platform == 'win32':
|
| 266 |
+
# Tk gives scaling with respect to 72 DPI, but Windows screens are
|
| 267 |
+
# scaled vs 96 dpi, and pixel ratio settings are given in whole
|
| 268 |
+
# percentages, so round to 2 digits.
|
| 269 |
+
ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2)
|
| 270 |
+
elif sys.platform == "linux":
|
| 271 |
+
ratio = self._tkcanvas.winfo_fpixels('1i') / 96
|
| 272 |
+
if ratio is not None and self._set_device_pixel_ratio(ratio):
|
| 273 |
+
# The easiest way to resize the canvas is to resize the canvas
|
| 274 |
+
# widget itself, since we implement all the logic for resizing the
|
| 275 |
+
# canvas backing store on that event.
|
| 276 |
+
w, h = self.get_width_height(physical=True)
|
| 277 |
+
self._tkcanvas.configure(width=w, height=h)
|
| 278 |
+
|
| 279 |
+
def resize(self, event):
|
| 280 |
+
width, height = event.width, event.height
|
| 281 |
+
|
| 282 |
+
# compute desired figure size in inches
|
| 283 |
+
dpival = self.figure.dpi
|
| 284 |
+
winch = width / dpival
|
| 285 |
+
hinch = height / dpival
|
| 286 |
+
self.figure.set_size_inches(winch, hinch, forward=False)
|
| 287 |
+
|
| 288 |
+
self._tkcanvas.delete(self._tkcanvas_image_region)
|
| 289 |
+
self._tkphoto.configure(width=int(width), height=int(height))
|
| 290 |
+
self._tkcanvas_image_region = self._tkcanvas.create_image(
|
| 291 |
+
int(width / 2), int(height / 2), image=self._tkphoto)
|
| 292 |
+
ResizeEvent("resize_event", self)._process()
|
| 293 |
+
self.draw_idle()
|
| 294 |
+
|
| 295 |
+
def draw_idle(self):
|
| 296 |
+
# docstring inherited
|
| 297 |
+
if self._idle_draw_id:
|
| 298 |
+
return
|
| 299 |
+
|
| 300 |
+
def idle_draw(*args):
|
| 301 |
+
try:
|
| 302 |
+
self.draw()
|
| 303 |
+
finally:
|
| 304 |
+
self._idle_draw_id = None
|
| 305 |
+
|
| 306 |
+
self._idle_draw_id = self._tkcanvas.after_idle(idle_draw)
|
| 307 |
+
|
| 308 |
+
def get_tk_widget(self):
|
| 309 |
+
"""
|
| 310 |
+
Return the Tk widget used to implement FigureCanvasTkAgg.
|
| 311 |
+
|
| 312 |
+
Although the initial implementation uses a Tk canvas, this routine
|
| 313 |
+
is intended to hide that fact.
|
| 314 |
+
"""
|
| 315 |
+
return self._tkcanvas
|
| 316 |
+
|
| 317 |
+
def _event_mpl_coords(self, event):
|
| 318 |
+
# calling canvasx/canvasy allows taking scrollbars into account (i.e.
|
| 319 |
+
# the top of the widget may have been scrolled out of view).
|
| 320 |
+
return (self._tkcanvas.canvasx(event.x),
|
| 321 |
+
# flipy so y=0 is bottom of canvas
|
| 322 |
+
self.figure.bbox.height - self._tkcanvas.canvasy(event.y))
|
| 323 |
+
|
| 324 |
+
def motion_notify_event(self, event):
|
| 325 |
+
MouseEvent("motion_notify_event", self,
|
| 326 |
+
*self._event_mpl_coords(event),
|
| 327 |
+
buttons=self._mpl_buttons(event),
|
| 328 |
+
modifiers=self._mpl_modifiers(event),
|
| 329 |
+
guiEvent=event)._process()
|
| 330 |
+
|
| 331 |
+
def enter_notify_event(self, event):
|
| 332 |
+
LocationEvent("figure_enter_event", self,
|
| 333 |
+
*self._event_mpl_coords(event),
|
| 334 |
+
modifiers=self._mpl_modifiers(event),
|
| 335 |
+
guiEvent=event)._process()
|
| 336 |
+
|
| 337 |
+
def leave_notify_event(self, event):
|
| 338 |
+
LocationEvent("figure_leave_event", self,
|
| 339 |
+
*self._event_mpl_coords(event),
|
| 340 |
+
modifiers=self._mpl_modifiers(event),
|
| 341 |
+
guiEvent=event)._process()
|
| 342 |
+
|
| 343 |
+
def button_press_event(self, event, dblclick=False):
|
| 344 |
+
# set focus to the canvas so that it can receive keyboard events
|
| 345 |
+
self._tkcanvas.focus_set()
|
| 346 |
+
|
| 347 |
+
num = getattr(event, 'num', None)
|
| 348 |
+
if sys.platform == 'darwin': # 2 and 3 are reversed.
|
| 349 |
+
num = {2: 3, 3: 2}.get(num, num)
|
| 350 |
+
MouseEvent("button_press_event", self,
|
| 351 |
+
*self._event_mpl_coords(event), num, dblclick=dblclick,
|
| 352 |
+
modifiers=self._mpl_modifiers(event),
|
| 353 |
+
guiEvent=event)._process()
|
| 354 |
+
|
| 355 |
+
def button_dblclick_event(self, event):
|
| 356 |
+
self.button_press_event(event, dblclick=True)
|
| 357 |
+
|
| 358 |
+
def button_release_event(self, event):
|
| 359 |
+
num = getattr(event, 'num', None)
|
| 360 |
+
if sys.platform == 'darwin': # 2 and 3 are reversed.
|
| 361 |
+
num = {2: 3, 3: 2}.get(num, num)
|
| 362 |
+
MouseEvent("button_release_event", self,
|
| 363 |
+
*self._event_mpl_coords(event), num,
|
| 364 |
+
modifiers=self._mpl_modifiers(event),
|
| 365 |
+
guiEvent=event)._process()
|
| 366 |
+
|
| 367 |
+
def scroll_event(self, event):
|
| 368 |
+
num = getattr(event, 'num', None)
|
| 369 |
+
step = 1 if num == 4 else -1 if num == 5 else 0
|
| 370 |
+
MouseEvent("scroll_event", self,
|
| 371 |
+
*self._event_mpl_coords(event), step=step,
|
| 372 |
+
modifiers=self._mpl_modifiers(event),
|
| 373 |
+
guiEvent=event)._process()
|
| 374 |
+
|
| 375 |
+
def scroll_event_windows(self, event):
|
| 376 |
+
"""MouseWheel event processor"""
|
| 377 |
+
# need to find the window that contains the mouse
|
| 378 |
+
w = event.widget.winfo_containing(event.x_root, event.y_root)
|
| 379 |
+
if w != self._tkcanvas:
|
| 380 |
+
return
|
| 381 |
+
x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx())
|
| 382 |
+
y = (self.figure.bbox.height
|
| 383 |
+
- self._tkcanvas.canvasy(event.y_root - w.winfo_rooty()))
|
| 384 |
+
step = event.delta / 120
|
| 385 |
+
MouseEvent("scroll_event", self,
|
| 386 |
+
x, y, step=step, modifiers=self._mpl_modifiers(event),
|
| 387 |
+
guiEvent=event)._process()
|
| 388 |
+
|
| 389 |
+
@staticmethod
|
| 390 |
+
def _mpl_buttons(event): # See _mpl_modifiers.
|
| 391 |
+
# NOTE: This fails to report multiclicks on macOS; only one button is
|
| 392 |
+
# reported (multiclicks work correctly on Linux & Windows).
|
| 393 |
+
modifiers = [
|
| 394 |
+
# macOS appears to swap right and middle (look for "Swap buttons
|
| 395 |
+
# 2/3" in tk/macosx/tkMacOSXMouseEvent.c).
|
| 396 |
+
(MouseButton.LEFT, 1 << 8),
|
| 397 |
+
(MouseButton.RIGHT, 1 << 9),
|
| 398 |
+
(MouseButton.MIDDLE, 1 << 10),
|
| 399 |
+
(MouseButton.BACK, 1 << 11),
|
| 400 |
+
(MouseButton.FORWARD, 1 << 12),
|
| 401 |
+
] if sys.platform == "darwin" else [
|
| 402 |
+
(MouseButton.LEFT, 1 << 8),
|
| 403 |
+
(MouseButton.MIDDLE, 1 << 9),
|
| 404 |
+
(MouseButton.RIGHT, 1 << 10),
|
| 405 |
+
(MouseButton.BACK, 1 << 11),
|
| 406 |
+
(MouseButton.FORWARD, 1 << 12),
|
| 407 |
+
]
|
| 408 |
+
# State *before* press/release.
|
| 409 |
+
return [name for name, mask in modifiers if event.state & mask]
|
| 410 |
+
|
| 411 |
+
@staticmethod
|
| 412 |
+
def _mpl_modifiers(event, *, exclude=None):
|
| 413 |
+
# Add modifier keys to the key string. Bit values are inferred from
|
| 414 |
+
# the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... =
|
| 415 |
+
# Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5)
|
| 416 |
+
# In general, the modifier key is excluded from the modifier flag,
|
| 417 |
+
# however this is not the case on "darwin", so double check that
|
| 418 |
+
# we aren't adding repeat modifier flags to a modifier key.
|
| 419 |
+
modifiers = [
|
| 420 |
+
("ctrl", 1 << 2, "control"),
|
| 421 |
+
("alt", 1 << 17, "alt"),
|
| 422 |
+
("shift", 1 << 0, "shift"),
|
| 423 |
+
] if sys.platform == "win32" else [
|
| 424 |
+
("ctrl", 1 << 2, "control"),
|
| 425 |
+
("alt", 1 << 4, "alt"),
|
| 426 |
+
("shift", 1 << 0, "shift"),
|
| 427 |
+
("cmd", 1 << 3, "cmd"),
|
| 428 |
+
] if sys.platform == "darwin" else [
|
| 429 |
+
("ctrl", 1 << 2, "control"),
|
| 430 |
+
("alt", 1 << 3, "alt"),
|
| 431 |
+
("shift", 1 << 0, "shift"),
|
| 432 |
+
("super", 1 << 6, "super"),
|
| 433 |
+
]
|
| 434 |
+
return [name for name, mask, key in modifiers
|
| 435 |
+
if event.state & mask and exclude != key]
|
| 436 |
+
|
| 437 |
+
def _get_key(self, event):
|
| 438 |
+
unikey = event.char
|
| 439 |
+
key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym)
|
| 440 |
+
if key is not None:
|
| 441 |
+
mods = self._mpl_modifiers(event, exclude=key)
|
| 442 |
+
# shift is not added to the keys as this is already accounted for.
|
| 443 |
+
if "shift" in mods and unikey:
|
| 444 |
+
mods.remove("shift")
|
| 445 |
+
return "+".join([*mods, key])
|
| 446 |
+
|
| 447 |
+
def key_press(self, event):
|
| 448 |
+
KeyEvent("key_press_event", self,
|
| 449 |
+
self._get_key(event), *self._event_mpl_coords(event),
|
| 450 |
+
guiEvent=event)._process()
|
| 451 |
+
|
| 452 |
+
def key_release(self, event):
|
| 453 |
+
KeyEvent("key_release_event", self,
|
| 454 |
+
self._get_key(event), *self._event_mpl_coords(event),
|
| 455 |
+
guiEvent=event)._process()
|
| 456 |
+
|
| 457 |
+
def new_timer(self, *args, **kwargs):
|
| 458 |
+
# docstring inherited
|
| 459 |
+
return TimerTk(self._tkcanvas, *args, **kwargs)
|
| 460 |
+
|
| 461 |
+
def flush_events(self):
|
| 462 |
+
# docstring inherited
|
| 463 |
+
self._tkcanvas.update()
|
| 464 |
+
|
| 465 |
+
def start_event_loop(self, timeout=0):
|
| 466 |
+
# docstring inherited
|
| 467 |
+
if timeout > 0:
|
| 468 |
+
milliseconds = int(1000 * timeout)
|
| 469 |
+
if milliseconds > 0:
|
| 470 |
+
self._event_loop_id = self._tkcanvas.after(
|
| 471 |
+
milliseconds, self.stop_event_loop)
|
| 472 |
+
else:
|
| 473 |
+
self._event_loop_id = self._tkcanvas.after_idle(
|
| 474 |
+
self.stop_event_loop)
|
| 475 |
+
self._tkcanvas.mainloop()
|
| 476 |
+
|
| 477 |
+
def stop_event_loop(self):
|
| 478 |
+
# docstring inherited
|
| 479 |
+
if self._event_loop_id:
|
| 480 |
+
self._tkcanvas.after_cancel(self._event_loop_id)
|
| 481 |
+
self._event_loop_id = None
|
| 482 |
+
self._tkcanvas.quit()
|
| 483 |
+
|
| 484 |
+
def set_cursor(self, cursor):
|
| 485 |
+
try:
|
| 486 |
+
self._tkcanvas.configure(cursor=cursord[cursor])
|
| 487 |
+
except tkinter.TclError:
|
| 488 |
+
pass
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
class FigureManagerTk(FigureManagerBase):
|
| 492 |
+
"""
|
| 493 |
+
Attributes
|
| 494 |
+
----------
|
| 495 |
+
canvas : `FigureCanvas`
|
| 496 |
+
The FigureCanvas instance
|
| 497 |
+
num : int or str
|
| 498 |
+
The Figure number
|
| 499 |
+
toolbar : tk.Toolbar
|
| 500 |
+
The tk.Toolbar
|
| 501 |
+
window : tk.Window
|
| 502 |
+
The tk.Window
|
| 503 |
+
"""
|
| 504 |
+
|
| 505 |
+
_owns_mainloop = False
|
| 506 |
+
|
| 507 |
+
def __init__(self, canvas, num, window):
|
| 508 |
+
self.window = window
|
| 509 |
+
super().__init__(canvas, num)
|
| 510 |
+
self.window.withdraw()
|
| 511 |
+
# packing toolbar first, because if space is getting low, last packed
|
| 512 |
+
# widget is getting shrunk first (-> the canvas)
|
| 513 |
+
self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
|
| 514 |
+
|
| 515 |
+
# If the window has per-monitor DPI awareness, then setup a Tk variable
|
| 516 |
+
# to store the DPI, which will be updated by the C code, and the trace
|
| 517 |
+
# will handle it on the Python side.
|
| 518 |
+
window_frame = int(window.wm_frame(), 16)
|
| 519 |
+
self._window_dpi = tk.IntVar(master=window, value=96,
|
| 520 |
+
name=f'window_dpi{window_frame}')
|
| 521 |
+
self._window_dpi_cbname = ''
|
| 522 |
+
if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()):
|
| 523 |
+
self._window_dpi_cbname = self._window_dpi.trace_add(
|
| 524 |
+
'write', self._update_window_dpi)
|
| 525 |
+
|
| 526 |
+
self._shown = False
|
| 527 |
+
|
| 528 |
+
@classmethod
|
| 529 |
+
def create_with_canvas(cls, canvas_class, figure, num):
|
| 530 |
+
# docstring inherited
|
| 531 |
+
with _restore_foreground_window_at_end():
|
| 532 |
+
if cbook._get_running_interactive_framework() is None:
|
| 533 |
+
cbook._setup_new_guiapp()
|
| 534 |
+
_c_internal_utils.Win32_SetProcessDpiAwareness_max()
|
| 535 |
+
window = tk.Tk(className="matplotlib")
|
| 536 |
+
window.withdraw()
|
| 537 |
+
|
| 538 |
+
# Put a Matplotlib icon on the window rather than the default tk
|
| 539 |
+
# icon. See https://www.tcl.tk/man/tcl/TkCmd/wm.html#M50
|
| 540 |
+
#
|
| 541 |
+
# `ImageTk` can be replaced with `tk` whenever the minimum
|
| 542 |
+
# supported Tk version is increased to 8.6, as Tk 8.6+ natively
|
| 543 |
+
# supports PNG images.
|
| 544 |
+
icon_fname = str(cbook._get_data_path(
|
| 545 |
+
'images/matplotlib.png'))
|
| 546 |
+
icon_img = ImageTk.PhotoImage(file=icon_fname, master=window)
|
| 547 |
+
|
| 548 |
+
icon_fname_large = str(cbook._get_data_path(
|
| 549 |
+
'images/matplotlib_large.png'))
|
| 550 |
+
icon_img_large = ImageTk.PhotoImage(
|
| 551 |
+
file=icon_fname_large, master=window)
|
| 552 |
+
|
| 553 |
+
window.iconphoto(False, icon_img_large, icon_img)
|
| 554 |
+
|
| 555 |
+
canvas = canvas_class(figure, master=window)
|
| 556 |
+
manager = cls(canvas, num, window)
|
| 557 |
+
if mpl.is_interactive():
|
| 558 |
+
manager.show()
|
| 559 |
+
canvas.draw_idle()
|
| 560 |
+
return manager
|
| 561 |
+
|
| 562 |
+
@classmethod
|
| 563 |
+
def start_main_loop(cls):
|
| 564 |
+
managers = Gcf.get_all_fig_managers()
|
| 565 |
+
if managers:
|
| 566 |
+
first_manager = managers[0]
|
| 567 |
+
manager_class = type(first_manager)
|
| 568 |
+
if manager_class._owns_mainloop:
|
| 569 |
+
return
|
| 570 |
+
manager_class._owns_mainloop = True
|
| 571 |
+
try:
|
| 572 |
+
first_manager.window.mainloop()
|
| 573 |
+
finally:
|
| 574 |
+
manager_class._owns_mainloop = False
|
| 575 |
+
|
| 576 |
+
def _update_window_dpi(self, *args):
|
| 577 |
+
newdpi = self._window_dpi.get()
|
| 578 |
+
self.window.call('tk', 'scaling', newdpi / 72)
|
| 579 |
+
if self.toolbar and hasattr(self.toolbar, '_rescale'):
|
| 580 |
+
self.toolbar._rescale()
|
| 581 |
+
self.canvas._update_device_pixel_ratio()
|
| 582 |
+
|
| 583 |
+
def resize(self, width, height):
|
| 584 |
+
max_size = 1_400_000 # the measured max on xorg 1.20.8 was 1_409_023
|
| 585 |
+
|
| 586 |
+
if (width > max_size or height > max_size) and sys.platform == 'linux':
|
| 587 |
+
raise ValueError(
|
| 588 |
+
'You have requested to resize the '
|
| 589 |
+
f'Tk window to ({width}, {height}), one of which '
|
| 590 |
+
f'is bigger than {max_size}. At larger sizes xorg will '
|
| 591 |
+
'either exit with an error on newer versions (~1.20) or '
|
| 592 |
+
'cause corruption on older version (~1.19). We '
|
| 593 |
+
'do not expect a window over a million pixel wide or tall '
|
| 594 |
+
'to be intended behavior.')
|
| 595 |
+
self.canvas._tkcanvas.configure(width=width, height=height)
|
| 596 |
+
|
| 597 |
+
def show(self):
|
| 598 |
+
with _restore_foreground_window_at_end():
|
| 599 |
+
if not self._shown:
|
| 600 |
+
def destroy(*args):
|
| 601 |
+
Gcf.destroy(self)
|
| 602 |
+
self.window.protocol("WM_DELETE_WINDOW", destroy)
|
| 603 |
+
self.window.deiconify()
|
| 604 |
+
self.canvas._tkcanvas.focus_set()
|
| 605 |
+
else:
|
| 606 |
+
self.canvas.draw_idle()
|
| 607 |
+
if mpl.rcParams['figure.raise_window']:
|
| 608 |
+
self.canvas.manager.window.attributes('-topmost', 1)
|
| 609 |
+
self.canvas.manager.window.attributes('-topmost', 0)
|
| 610 |
+
self._shown = True
|
| 611 |
+
|
| 612 |
+
def destroy(self, *args):
|
| 613 |
+
if self.canvas._idle_draw_id:
|
| 614 |
+
self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)
|
| 615 |
+
if self.canvas._event_loop_id:
|
| 616 |
+
self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id)
|
| 617 |
+
if self._window_dpi_cbname:
|
| 618 |
+
self._window_dpi.trace_remove('write', self._window_dpi_cbname)
|
| 619 |
+
|
| 620 |
+
# NOTE: events need to be flushed before issuing destroy (GH #9956),
|
| 621 |
+
# however, self.window.update() can break user code. An async callback
|
| 622 |
+
# is the safest way to achieve a complete draining of the event queue,
|
| 623 |
+
# but it leaks if no tk event loop is running. Therefore we explicitly
|
| 624 |
+
# check for an event loop and choose our best guess.
|
| 625 |
+
def delayed_destroy():
|
| 626 |
+
self.window.destroy()
|
| 627 |
+
|
| 628 |
+
if self._owns_mainloop and not Gcf.get_num_fig_managers():
|
| 629 |
+
self.window.quit()
|
| 630 |
+
|
| 631 |
+
if cbook._get_running_interactive_framework() == "tk":
|
| 632 |
+
# "after idle after 0" avoids Tcl error/race (GH #19940)
|
| 633 |
+
self.window.after_idle(self.window.after, 0, delayed_destroy)
|
| 634 |
+
else:
|
| 635 |
+
self.window.update()
|
| 636 |
+
delayed_destroy()
|
| 637 |
+
|
| 638 |
+
def get_window_title(self):
|
| 639 |
+
return self.window.wm_title()
|
| 640 |
+
|
| 641 |
+
def set_window_title(self, title):
|
| 642 |
+
self.window.wm_title(title)
|
| 643 |
+
|
| 644 |
+
def full_screen_toggle(self):
|
| 645 |
+
is_fullscreen = bool(self.window.attributes('-fullscreen'))
|
| 646 |
+
self.window.attributes('-fullscreen', not is_fullscreen)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
class NavigationToolbar2Tk(NavigationToolbar2, tk.Frame):
|
| 650 |
+
def __init__(self, canvas, window=None, *, pack_toolbar=True):
|
| 651 |
+
"""
|
| 652 |
+
Parameters
|
| 653 |
+
----------
|
| 654 |
+
canvas : `FigureCanvas`
|
| 655 |
+
The figure canvas on which to operate.
|
| 656 |
+
window : tk.Window
|
| 657 |
+
The tk.Window which owns this toolbar.
|
| 658 |
+
pack_toolbar : bool, default: True
|
| 659 |
+
If True, add the toolbar to the parent's pack manager's packing
|
| 660 |
+
list during initialization with ``side="bottom"`` and ``fill="x"``.
|
| 661 |
+
If you want to use the toolbar with a different layout manager, use
|
| 662 |
+
``pack_toolbar=False``.
|
| 663 |
+
"""
|
| 664 |
+
|
| 665 |
+
if window is None:
|
| 666 |
+
window = canvas.get_tk_widget().master
|
| 667 |
+
tk.Frame.__init__(self, master=window, borderwidth=2,
|
| 668 |
+
width=int(canvas.figure.bbox.width), height=50)
|
| 669 |
+
|
| 670 |
+
self._buttons = {}
|
| 671 |
+
for text, tooltip_text, image_file, callback in self.toolitems:
|
| 672 |
+
if text is None:
|
| 673 |
+
# Add a spacer; return value is unused.
|
| 674 |
+
self._Spacer()
|
| 675 |
+
else:
|
| 676 |
+
self._buttons[text] = button = self._Button(
|
| 677 |
+
text,
|
| 678 |
+
str(cbook._get_data_path(f"images/{image_file}.png")),
|
| 679 |
+
toggle=callback in ["zoom", "pan"],
|
| 680 |
+
command=getattr(self, callback),
|
| 681 |
+
)
|
| 682 |
+
if tooltip_text is not None:
|
| 683 |
+
add_tooltip(button, tooltip_text)
|
| 684 |
+
|
| 685 |
+
self._label_font = tkinter.font.Font(root=window, size=10)
|
| 686 |
+
|
| 687 |
+
# This filler item ensures the toolbar is always at least two text
|
| 688 |
+
# lines high. Otherwise the canvas gets redrawn as the mouse hovers
|
| 689 |
+
# over images because those use two-line messages which resize the
|
| 690 |
+
# toolbar.
|
| 691 |
+
label = tk.Label(master=self, font=self._label_font,
|
| 692 |
+
text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
|
| 693 |
+
label.pack(side=tk.RIGHT)
|
| 694 |
+
|
| 695 |
+
self.message = tk.StringVar(master=self)
|
| 696 |
+
self._message_label = tk.Label(master=self, font=self._label_font,
|
| 697 |
+
textvariable=self.message,
|
| 698 |
+
justify=tk.RIGHT)
|
| 699 |
+
self._message_label.pack(side=tk.RIGHT)
|
| 700 |
+
|
| 701 |
+
NavigationToolbar2.__init__(self, canvas)
|
| 702 |
+
if pack_toolbar:
|
| 703 |
+
self.pack(side=tk.BOTTOM, fill=tk.X)
|
| 704 |
+
|
| 705 |
+
def _rescale(self):
|
| 706 |
+
"""
|
| 707 |
+
Scale all children of the toolbar to current DPI setting.
|
| 708 |
+
|
| 709 |
+
Before this is called, the Tk scaling setting will have been updated to
|
| 710 |
+
match the new DPI. Tk widgets do not update for changes to scaling, but
|
| 711 |
+
all measurements made after the change will match the new scaling. Thus
|
| 712 |
+
this function re-applies all the same sizes in points, which Tk will
|
| 713 |
+
scale correctly to pixels.
|
| 714 |
+
"""
|
| 715 |
+
for widget in self.winfo_children():
|
| 716 |
+
if isinstance(widget, (tk.Button, tk.Checkbutton)):
|
| 717 |
+
if hasattr(widget, '_image_file'):
|
| 718 |
+
# Explicit class because ToolbarTk calls _rescale.
|
| 719 |
+
NavigationToolbar2Tk._set_image_for_button(self, widget)
|
| 720 |
+
else:
|
| 721 |
+
# Text-only button is handled by the font setting instead.
|
| 722 |
+
pass
|
| 723 |
+
elif isinstance(widget, tk.Frame):
|
| 724 |
+
widget.configure(height='18p')
|
| 725 |
+
widget.pack_configure(padx='3p')
|
| 726 |
+
elif isinstance(widget, tk.Label):
|
| 727 |
+
pass # Text is handled by the font setting instead.
|
| 728 |
+
else:
|
| 729 |
+
_log.warning('Unknown child class %s', widget.winfo_class)
|
| 730 |
+
self._label_font.configure(size=10)
|
| 731 |
+
|
| 732 |
+
def _update_buttons_checked(self):
|
| 733 |
+
# sync button checkstates to match active mode
|
| 734 |
+
for text, mode in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]:
|
| 735 |
+
if text in self._buttons:
|
| 736 |
+
if self.mode == mode:
|
| 737 |
+
self._buttons[text].select() # NOT .invoke()
|
| 738 |
+
else:
|
| 739 |
+
self._buttons[text].deselect()
|
| 740 |
+
|
| 741 |
+
def pan(self, *args):
|
| 742 |
+
super().pan(*args)
|
| 743 |
+
self._update_buttons_checked()
|
| 744 |
+
|
| 745 |
+
def zoom(self, *args):
|
| 746 |
+
super().zoom(*args)
|
| 747 |
+
self._update_buttons_checked()
|
| 748 |
+
|
| 749 |
+
def set_message(self, s):
|
| 750 |
+
self.message.set(s)
|
| 751 |
+
|
| 752 |
+
def draw_rubberband(self, event, x0, y0, x1, y1):
|
| 753 |
+
# Block copied from remove_rubberband for backend_tools convenience.
|
| 754 |
+
if self.canvas._rubberband_rect_white:
|
| 755 |
+
self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
|
| 756 |
+
if self.canvas._rubberband_rect_black:
|
| 757 |
+
self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
|
| 758 |
+
height = self.canvas.figure.bbox.height
|
| 759 |
+
y0 = height - y0
|
| 760 |
+
y1 = height - y1
|
| 761 |
+
self.canvas._rubberband_rect_black = (
|
| 762 |
+
self.canvas._tkcanvas.create_rectangle(
|
| 763 |
+
x0, y0, x1, y1))
|
| 764 |
+
self.canvas._rubberband_rect_white = (
|
| 765 |
+
self.canvas._tkcanvas.create_rectangle(
|
| 766 |
+
x0, y0, x1, y1, outline='white', dash=(3, 3)))
|
| 767 |
+
|
| 768 |
+
def remove_rubberband(self):
|
| 769 |
+
if self.canvas._rubberband_rect_white:
|
| 770 |
+
self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
|
| 771 |
+
self.canvas._rubberband_rect_white = None
|
| 772 |
+
if self.canvas._rubberband_rect_black:
|
| 773 |
+
self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
|
| 774 |
+
self.canvas._rubberband_rect_black = None
|
| 775 |
+
|
| 776 |
+
def _set_image_for_button(self, button):
|
| 777 |
+
"""
|
| 778 |
+
Set the image for a button based on its pixel size.
|
| 779 |
+
|
| 780 |
+
The pixel size is determined by the DPI scaling of the window.
|
| 781 |
+
"""
|
| 782 |
+
if button._image_file is None:
|
| 783 |
+
return
|
| 784 |
+
|
| 785 |
+
# Allow _image_file to be relative to Matplotlib's "images" data
|
| 786 |
+
# directory.
|
| 787 |
+
path_regular = cbook._get_data_path('images', button._image_file)
|
| 788 |
+
path_large = path_regular.with_name(
|
| 789 |
+
path_regular.name.replace('.png', '_large.png'))
|
| 790 |
+
size = button.winfo_pixels('18p')
|
| 791 |
+
|
| 792 |
+
# Nested functions because ToolbarTk calls _Button.
|
| 793 |
+
def _get_color(color_name):
|
| 794 |
+
# `winfo_rgb` returns an (r, g, b) tuple in the range 0-65535
|
| 795 |
+
return button.winfo_rgb(button.cget(color_name))
|
| 796 |
+
|
| 797 |
+
def _is_dark(color):
|
| 798 |
+
if isinstance(color, str):
|
| 799 |
+
color = _get_color(color)
|
| 800 |
+
return max(color) < 65535 / 2
|
| 801 |
+
|
| 802 |
+
def _recolor_icon(image, color):
|
| 803 |
+
image_data = np.asarray(image).copy()
|
| 804 |
+
black_mask = (image_data[..., :3] == 0).all(axis=-1)
|
| 805 |
+
image_data[black_mask, :3] = color
|
| 806 |
+
return Image.fromarray(image_data)
|
| 807 |
+
|
| 808 |
+
# Use the high-resolution (48x48 px) icon if it exists and is needed
|
| 809 |
+
with Image.open(path_large if (size > 24 and path_large.exists())
|
| 810 |
+
else path_regular) as im:
|
| 811 |
+
# assure a RGBA image as foreground color is RGB
|
| 812 |
+
im = im.convert("RGBA")
|
| 813 |
+
image = ImageTk.PhotoImage(im.resize((size, size)), master=self)
|
| 814 |
+
button._ntimage = image
|
| 815 |
+
|
| 816 |
+
# create a version of the icon with the button's text color
|
| 817 |
+
foreground = (255 / 65535) * np.array(
|
| 818 |
+
button.winfo_rgb(button.cget("foreground")))
|
| 819 |
+
im_alt = _recolor_icon(im, foreground)
|
| 820 |
+
image_alt = ImageTk.PhotoImage(
|
| 821 |
+
im_alt.resize((size, size)), master=self)
|
| 822 |
+
button._ntimage_alt = image_alt
|
| 823 |
+
|
| 824 |
+
if _is_dark("background"):
|
| 825 |
+
# For Checkbuttons, we need to set `image` and `selectimage` at
|
| 826 |
+
# the same time. Otherwise, when updating the `image` option
|
| 827 |
+
# (such as when changing DPI), if the old `selectimage` has
|
| 828 |
+
# just been overwritten, Tk will throw an error.
|
| 829 |
+
image_kwargs = {"image": image_alt}
|
| 830 |
+
else:
|
| 831 |
+
image_kwargs = {"image": image}
|
| 832 |
+
# Checkbuttons may switch the background to `selectcolor` in the
|
| 833 |
+
# checked state, so check separately which image it needs to use in
|
| 834 |
+
# that state to still ensure enough contrast with the background.
|
| 835 |
+
if (
|
| 836 |
+
isinstance(button, tk.Checkbutton)
|
| 837 |
+
and button.cget("selectcolor") != ""
|
| 838 |
+
):
|
| 839 |
+
if self._windowingsystem != "x11":
|
| 840 |
+
selectcolor = "selectcolor"
|
| 841 |
+
else:
|
| 842 |
+
# On X11, selectcolor isn't used directly for indicator-less
|
| 843 |
+
# buttons. See `::tk::CheckEnter` in the Tk button.tcl source
|
| 844 |
+
# code for details.
|
| 845 |
+
r1, g1, b1 = _get_color("selectcolor")
|
| 846 |
+
r2, g2, b2 = _get_color("activebackground")
|
| 847 |
+
selectcolor = ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2)
|
| 848 |
+
if _is_dark(selectcolor):
|
| 849 |
+
image_kwargs["selectimage"] = image_alt
|
| 850 |
+
else:
|
| 851 |
+
image_kwargs["selectimage"] = image
|
| 852 |
+
|
| 853 |
+
button.configure(**image_kwargs, height='18p', width='18p')
|
| 854 |
+
|
| 855 |
+
def _Button(self, text, image_file, toggle, command):
|
| 856 |
+
if not toggle:
|
| 857 |
+
b = tk.Button(
|
| 858 |
+
master=self, text=text, command=command,
|
| 859 |
+
relief="flat", overrelief="groove", borderwidth=1,
|
| 860 |
+
)
|
| 861 |
+
else:
|
| 862 |
+
# There is a bug in tkinter included in some python 3.6 versions
|
| 863 |
+
# that without this variable, produces a "visual" toggling of
|
| 864 |
+
# other near checkbuttons
|
| 865 |
+
# https://bugs.python.org/issue29402
|
| 866 |
+
# https://bugs.python.org/issue25684
|
| 867 |
+
var = tk.IntVar(master=self)
|
| 868 |
+
b = tk.Checkbutton(
|
| 869 |
+
master=self, text=text, command=command, indicatoron=False,
|
| 870 |
+
variable=var, offrelief="flat", overrelief="groove",
|
| 871 |
+
borderwidth=1
|
| 872 |
+
)
|
| 873 |
+
b.var = var
|
| 874 |
+
b._image_file = image_file
|
| 875 |
+
if image_file is not None:
|
| 876 |
+
# Explicit class because ToolbarTk calls _Button.
|
| 877 |
+
NavigationToolbar2Tk._set_image_for_button(self, b)
|
| 878 |
+
else:
|
| 879 |
+
b.configure(font=self._label_font)
|
| 880 |
+
b.pack(side=tk.LEFT)
|
| 881 |
+
return b
|
| 882 |
+
|
| 883 |
+
def _Spacer(self):
|
| 884 |
+
# Buttons are also 18pt high.
|
| 885 |
+
s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray')
|
| 886 |
+
s.pack(side=tk.LEFT, padx='3p')
|
| 887 |
+
return s
|
| 888 |
+
|
| 889 |
+
def save_figure(self, *args):
|
| 890 |
+
filetypes = self.canvas.get_supported_filetypes_grouped()
|
| 891 |
+
tk_filetypes = [
|
| 892 |
+
(name, " ".join(f"*.{ext}" for ext in exts))
|
| 893 |
+
for name, exts in sorted(filetypes.items())
|
| 894 |
+
]
|
| 895 |
+
|
| 896 |
+
default_extension = self.canvas.get_default_filetype()
|
| 897 |
+
default_filetype = self.canvas.get_supported_filetypes()[default_extension]
|
| 898 |
+
filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype)
|
| 899 |
+
|
| 900 |
+
# adding a default extension seems to break the
|
| 901 |
+
# asksaveasfilename dialog when you choose various save types
|
| 902 |
+
# from the dropdown. Passing in the empty string seems to
|
| 903 |
+
# work - JDH!
|
| 904 |
+
# defaultextension = self.canvas.get_default_filetype()
|
| 905 |
+
defaultextension = ''
|
| 906 |
+
initialdir = os.path.expanduser(mpl.rcParams['savefig.directory'])
|
| 907 |
+
# get_default_filename() contains the default extension. On some platforms,
|
| 908 |
+
# choosing a different extension from the dropdown does not overwrite it,
|
| 909 |
+
# so we need to remove it to make the dropdown functional.
|
| 910 |
+
initialfile = pathlib.Path(self.canvas.get_default_filename()).stem
|
| 911 |
+
fname = tkinter.filedialog.asksaveasfilename(
|
| 912 |
+
master=self.canvas.get_tk_widget().master,
|
| 913 |
+
title='Save the figure',
|
| 914 |
+
filetypes=tk_filetypes,
|
| 915 |
+
defaultextension=defaultextension,
|
| 916 |
+
initialdir=initialdir,
|
| 917 |
+
initialfile=initialfile,
|
| 918 |
+
typevariable=filetype_variable
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
if fname in ["", ()]:
|
| 922 |
+
return None
|
| 923 |
+
# Save dir for next time, unless empty str (i.e., use cwd).
|
| 924 |
+
if initialdir != "":
|
| 925 |
+
mpl.rcParams['savefig.directory'] = (
|
| 926 |
+
os.path.dirname(str(fname)))
|
| 927 |
+
|
| 928 |
+
# If the filename contains an extension, let savefig() infer the file
|
| 929 |
+
# format from that. If it does not, use the selected dropdown option.
|
| 930 |
+
if pathlib.Path(fname).suffix[1:] != "":
|
| 931 |
+
extension = None
|
| 932 |
+
else:
|
| 933 |
+
extension = filetypes[filetype_variable.get()][0]
|
| 934 |
+
|
| 935 |
+
try:
|
| 936 |
+
self.canvas.figure.savefig(fname, format=extension)
|
| 937 |
+
return fname
|
| 938 |
+
except Exception as e:
|
| 939 |
+
tkinter.messagebox.showerror("Error saving file", str(e))
|
| 940 |
+
|
| 941 |
+
def set_history_buttons(self):
|
| 942 |
+
state_map = {True: tk.NORMAL, False: tk.DISABLED}
|
| 943 |
+
can_back = self._nav_stack._pos > 0
|
| 944 |
+
can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
|
| 945 |
+
if "Back" in self._buttons:
|
| 946 |
+
self._buttons['Back']['state'] = state_map[can_back]
|
| 947 |
+
if "Forward" in self._buttons:
|
| 948 |
+
self._buttons['Forward']['state'] = state_map[can_forward]
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def add_tooltip(widget, text):
|
| 952 |
+
tipwindow = None
|
| 953 |
+
|
| 954 |
+
def showtip(event):
|
| 955 |
+
"""Display text in tooltip window."""
|
| 956 |
+
nonlocal tipwindow
|
| 957 |
+
if tipwindow or not text:
|
| 958 |
+
return
|
| 959 |
+
x, y, _, _ = widget.bbox("insert")
|
| 960 |
+
x = x + widget.winfo_rootx() + widget.winfo_width()
|
| 961 |
+
y = y + widget.winfo_rooty()
|
| 962 |
+
tipwindow = tk.Toplevel(widget)
|
| 963 |
+
tipwindow.overrideredirect(1)
|
| 964 |
+
tipwindow.geometry(f"+{x}+{y}")
|
| 965 |
+
try: # For Mac OS
|
| 966 |
+
tipwindow.tk.call("::tk::unsupported::MacWindowStyle",
|
| 967 |
+
"style", tipwindow._w,
|
| 968 |
+
"help", "noActivates")
|
| 969 |
+
except tk.TclError:
|
| 970 |
+
pass
|
| 971 |
+
label = tk.Label(tipwindow, text=text, justify=tk.LEFT,
|
| 972 |
+
relief=tk.SOLID, borderwidth=1)
|
| 973 |
+
label.pack(ipadx=1)
|
| 974 |
+
|
| 975 |
+
def hidetip(event):
|
| 976 |
+
nonlocal tipwindow
|
| 977 |
+
if tipwindow:
|
| 978 |
+
tipwindow.destroy()
|
| 979 |
+
tipwindow = None
|
| 980 |
+
|
| 981 |
+
widget.bind("<Enter>", showtip)
|
| 982 |
+
widget.bind("<Leave>", hidetip)
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
@backend_tools._register_tool_class(FigureCanvasTk)
|
| 986 |
+
class RubberbandTk(backend_tools.RubberbandBase):
|
| 987 |
+
def draw_rubberband(self, x0, y0, x1, y1):
|
| 988 |
+
NavigationToolbar2Tk.draw_rubberband(
|
| 989 |
+
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
|
| 990 |
+
|
| 991 |
+
def remove_rubberband(self):
|
| 992 |
+
NavigationToolbar2Tk.remove_rubberband(
|
| 993 |
+
self._make_classic_style_pseudo_toolbar())
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
class ToolbarTk(ToolContainerBase, tk.Frame):
|
| 997 |
+
def __init__(self, toolmanager, window=None):
|
| 998 |
+
ToolContainerBase.__init__(self, toolmanager)
|
| 999 |
+
if window is None:
|
| 1000 |
+
window = self.toolmanager.canvas.get_tk_widget().master
|
| 1001 |
+
xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx
|
| 1002 |
+
height, width = 50, xmax - xmin
|
| 1003 |
+
tk.Frame.__init__(self, master=window,
|
| 1004 |
+
width=int(width), height=int(height),
|
| 1005 |
+
borderwidth=2)
|
| 1006 |
+
self._label_font = tkinter.font.Font(size=10)
|
| 1007 |
+
# This filler item ensures the toolbar is always at least two text
|
| 1008 |
+
# lines high. Otherwise the canvas gets redrawn as the mouse hovers
|
| 1009 |
+
# over images because those use two-line messages which resize the
|
| 1010 |
+
# toolbar.
|
| 1011 |
+
label = tk.Label(master=self, font=self._label_font,
|
| 1012 |
+
text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
|
| 1013 |
+
label.pack(side=tk.RIGHT)
|
| 1014 |
+
self._message = tk.StringVar(master=self)
|
| 1015 |
+
self._message_label = tk.Label(master=self, font=self._label_font,
|
| 1016 |
+
textvariable=self._message)
|
| 1017 |
+
self._message_label.pack(side=tk.RIGHT)
|
| 1018 |
+
self._toolitems = {}
|
| 1019 |
+
self.pack(side=tk.TOP, fill=tk.X)
|
| 1020 |
+
self._groups = {}
|
| 1021 |
+
|
| 1022 |
+
def _rescale(self):
|
| 1023 |
+
return NavigationToolbar2Tk._rescale(self)
|
| 1024 |
+
|
| 1025 |
+
def add_toolitem(
|
| 1026 |
+
self, name, group, position, image_file, description, toggle):
|
| 1027 |
+
frame = self._get_groupframe(group)
|
| 1028 |
+
buttons = frame.pack_slaves()
|
| 1029 |
+
if position >= len(buttons) or position < 0:
|
| 1030 |
+
before = None
|
| 1031 |
+
else:
|
| 1032 |
+
before = buttons[position]
|
| 1033 |
+
button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle,
|
| 1034 |
+
lambda: self._button_click(name))
|
| 1035 |
+
button.pack_configure(before=before)
|
| 1036 |
+
if description is not None:
|
| 1037 |
+
add_tooltip(button, description)
|
| 1038 |
+
self._toolitems.setdefault(name, [])
|
| 1039 |
+
self._toolitems[name].append(button)
|
| 1040 |
+
|
| 1041 |
+
def _get_groupframe(self, group):
|
| 1042 |
+
if group not in self._groups:
|
| 1043 |
+
if self._groups:
|
| 1044 |
+
self._add_separator()
|
| 1045 |
+
frame = tk.Frame(master=self, borderwidth=0)
|
| 1046 |
+
frame.pack(side=tk.LEFT, fill=tk.Y)
|
| 1047 |
+
frame._label_font = self._label_font
|
| 1048 |
+
self._groups[group] = frame
|
| 1049 |
+
return self._groups[group]
|
| 1050 |
+
|
| 1051 |
+
def _add_separator(self):
|
| 1052 |
+
return NavigationToolbar2Tk._Spacer(self)
|
| 1053 |
+
|
| 1054 |
+
def _button_click(self, name):
|
| 1055 |
+
self.trigger_tool(name)
|
| 1056 |
+
|
| 1057 |
+
def toggle_toolitem(self, name, toggled):
|
| 1058 |
+
if name not in self._toolitems:
|
| 1059 |
+
return
|
| 1060 |
+
for toolitem in self._toolitems[name]:
|
| 1061 |
+
if toggled:
|
| 1062 |
+
toolitem.select()
|
| 1063 |
+
else:
|
| 1064 |
+
toolitem.deselect()
|
| 1065 |
+
|
| 1066 |
+
def remove_toolitem(self, name):
|
| 1067 |
+
for toolitem in self._toolitems.pop(name, []):
|
| 1068 |
+
toolitem.pack_forget()
|
| 1069 |
+
|
| 1070 |
+
def set_message(self, s):
|
| 1071 |
+
self._message.set(s)
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
@backend_tools._register_tool_class(FigureCanvasTk)
|
| 1075 |
+
class SaveFigureTk(backend_tools.SaveFigureBase):
|
| 1076 |
+
def trigger(self, *args):
|
| 1077 |
+
NavigationToolbar2Tk.save_figure(
|
| 1078 |
+
self._make_classic_style_pseudo_toolbar())
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
@backend_tools._register_tool_class(FigureCanvasTk)
|
| 1082 |
+
class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase):
|
| 1083 |
+
def trigger(self, *args):
|
| 1084 |
+
NavigationToolbar2Tk.configure_subplots(self)
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
@backend_tools._register_tool_class(FigureCanvasTk)
|
| 1088 |
+
class HelpTk(backend_tools.ToolHelpBase):
|
| 1089 |
+
def trigger(self, *args):
|
| 1090 |
+
dialog = SimpleDialog(
|
| 1091 |
+
self.figure.canvas._tkcanvas, self._get_help_text(), ["OK"])
|
| 1092 |
+
dialog.done = lambda num: dialog.frame.master.withdraw()
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
Toolbar = ToolbarTk
|
| 1096 |
+
FigureManagerTk._toolbar2_class = NavigationToolbar2Tk
|
| 1097 |
+
FigureManagerTk._toolmanager_toolbar_class = ToolbarTk
|
| 1098 |
+
|
| 1099 |
+
|
| 1100 |
+
@_Backend.export
|
| 1101 |
+
class _BackendTk(_Backend):
|
| 1102 |
+
backend_version = tk.TkVersion
|
| 1103 |
+
FigureCanvas = FigureCanvasTk
|
| 1104 |
+
FigureManager = FigureManagerTk
|
| 1105 |
+
mainloop = FigureManagerTk.start_main_loop
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_macosx.pyi
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:059dc0870fdf25012b1752b58c2b81ff3a632b1f27531113fcef9c9d42333aa2
|
| 3 |
+
size 302640
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/_tkagg.pyi
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numpy.typing import NDArray
|
| 3 |
+
|
| 4 |
+
TK_PHOTO_COMPOSITE_OVERLAY: int
|
| 5 |
+
TK_PHOTO_COMPOSITE_SET: int
|
| 6 |
+
|
| 7 |
+
def blit(
|
| 8 |
+
interp: int,
|
| 9 |
+
photo_name: str,
|
| 10 |
+
data: NDArray[np.uint8],
|
| 11 |
+
comp_rule: int,
|
| 12 |
+
offset: tuple[int, int, int, int],
|
| 13 |
+
bbox: tuple[int, int, int, int],
|
| 14 |
+
) -> None: ...
|
| 15 |
+
def enable_dpi_awareness(frame_handle: int, interp: int) -> bool | None: ...
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
An `Anti-Grain Geometry`_ (AGG) backend.
|
| 3 |
+
|
| 4 |
+
Features that are implemented:
|
| 5 |
+
|
| 6 |
+
* capstyles and join styles
|
| 7 |
+
* dashes
|
| 8 |
+
* linewidth
|
| 9 |
+
* lines, rectangles, ellipses
|
| 10 |
+
* clipping to a rectangle
|
| 11 |
+
* output to RGBA and Pillow-supported image formats
|
| 12 |
+
* alpha blending
|
| 13 |
+
* DPI scaling properly - everything scales properly (dashes, linewidths, etc)
|
| 14 |
+
* draw polygon
|
| 15 |
+
* freetype2 w/ ft2font
|
| 16 |
+
|
| 17 |
+
Still TODO:
|
| 18 |
+
|
| 19 |
+
* integrate screen dpi w/ ppi and text
|
| 20 |
+
|
| 21 |
+
.. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from contextlib import nullcontext
|
| 25 |
+
from math import radians, cos, sin
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
import matplotlib as mpl
|
| 30 |
+
from matplotlib import _api, cbook
|
| 31 |
+
from matplotlib.backend_bases import (
|
| 32 |
+
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
|
| 33 |
+
from matplotlib.font_manager import fontManager as _fontManager, get_font
|
| 34 |
+
from matplotlib.ft2font import LoadFlags
|
| 35 |
+
from matplotlib.mathtext import MathTextParser
|
| 36 |
+
from matplotlib.path import Path
|
| 37 |
+
from matplotlib.transforms import Bbox, BboxBase
|
| 38 |
+
from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_hinting_flag():
|
| 42 |
+
mapping = {
|
| 43 |
+
'default': LoadFlags.DEFAULT,
|
| 44 |
+
'no_autohint': LoadFlags.NO_AUTOHINT,
|
| 45 |
+
'force_autohint': LoadFlags.FORCE_AUTOHINT,
|
| 46 |
+
'no_hinting': LoadFlags.NO_HINTING,
|
| 47 |
+
True: LoadFlags.FORCE_AUTOHINT,
|
| 48 |
+
False: LoadFlags.NO_HINTING,
|
| 49 |
+
'either': LoadFlags.DEFAULT,
|
| 50 |
+
'native': LoadFlags.NO_AUTOHINT,
|
| 51 |
+
'auto': LoadFlags.FORCE_AUTOHINT,
|
| 52 |
+
'none': LoadFlags.NO_HINTING,
|
| 53 |
+
}
|
| 54 |
+
return mapping[mpl.rcParams['text.hinting']]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class RendererAgg(RendererBase):
|
| 58 |
+
"""
|
| 59 |
+
The renderer handles all the drawing primitives using a graphics
|
| 60 |
+
context instance that controls the colors/styles
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, width, height, dpi):
|
| 64 |
+
super().__init__()
|
| 65 |
+
|
| 66 |
+
self.dpi = dpi
|
| 67 |
+
self.width = width
|
| 68 |
+
self.height = height
|
| 69 |
+
self._renderer = _RendererAgg(int(width), int(height), dpi)
|
| 70 |
+
self._filter_renderers = []
|
| 71 |
+
|
| 72 |
+
self._update_methods()
|
| 73 |
+
self.mathtext_parser = MathTextParser('agg')
|
| 74 |
+
|
| 75 |
+
self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
|
| 76 |
+
|
| 77 |
+
def __getstate__(self):
|
| 78 |
+
# We only want to preserve the init keywords of the Renderer.
|
| 79 |
+
# Anything else can be re-created.
|
| 80 |
+
return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
|
| 81 |
+
|
| 82 |
+
def __setstate__(self, state):
|
| 83 |
+
self.__init__(state['width'], state['height'], state['dpi'])
|
| 84 |
+
|
| 85 |
+
def _update_methods(self):
|
| 86 |
+
self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
|
| 87 |
+
self.draw_image = self._renderer.draw_image
|
| 88 |
+
self.draw_markers = self._renderer.draw_markers
|
| 89 |
+
self.draw_path_collection = self._renderer.draw_path_collection
|
| 90 |
+
self.draw_quad_mesh = self._renderer.draw_quad_mesh
|
| 91 |
+
self.copy_from_bbox = self._renderer.copy_from_bbox
|
| 92 |
+
|
| 93 |
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
| 94 |
+
# docstring inherited
|
| 95 |
+
nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing
|
| 96 |
+
npts = path.vertices.shape[0]
|
| 97 |
+
|
| 98 |
+
if (npts > nmax > 100 and path.should_simplify and
|
| 99 |
+
rgbFace is None and gc.get_hatch() is None):
|
| 100 |
+
nch = np.ceil(npts / nmax)
|
| 101 |
+
chsize = int(np.ceil(npts / nch))
|
| 102 |
+
i0 = np.arange(0, npts, chsize)
|
| 103 |
+
i1 = np.zeros_like(i0)
|
| 104 |
+
i1[:-1] = i0[1:] - 1
|
| 105 |
+
i1[-1] = npts
|
| 106 |
+
for ii0, ii1 in zip(i0, i1):
|
| 107 |
+
v = path.vertices[ii0:ii1, :]
|
| 108 |
+
c = path.codes
|
| 109 |
+
if c is not None:
|
| 110 |
+
c = c[ii0:ii1]
|
| 111 |
+
c[0] = Path.MOVETO # move to end of last chunk
|
| 112 |
+
p = Path(v, c)
|
| 113 |
+
p.simplify_threshold = path.simplify_threshold
|
| 114 |
+
try:
|
| 115 |
+
self._renderer.draw_path(gc, p, transform, rgbFace)
|
| 116 |
+
except OverflowError:
|
| 117 |
+
msg = (
|
| 118 |
+
"Exceeded cell block limit in Agg.\n\n"
|
| 119 |
+
"Please reduce the value of "
|
| 120 |
+
f"rcParams['agg.path.chunksize'] (currently {nmax}) "
|
| 121 |
+
"or increase the path simplification threshold"
|
| 122 |
+
"(rcParams['path.simplify_threshold'] = "
|
| 123 |
+
f"{mpl.rcParams['path.simplify_threshold']:.2f} by "
|
| 124 |
+
"default and path.simplify_threshold = "
|
| 125 |
+
f"{path.simplify_threshold:.2f} on the input)."
|
| 126 |
+
)
|
| 127 |
+
raise OverflowError(msg) from None
|
| 128 |
+
else:
|
| 129 |
+
try:
|
| 130 |
+
self._renderer.draw_path(gc, path, transform, rgbFace)
|
| 131 |
+
except OverflowError:
|
| 132 |
+
cant_chunk = ''
|
| 133 |
+
if rgbFace is not None:
|
| 134 |
+
cant_chunk += "- cannot split filled path\n"
|
| 135 |
+
if gc.get_hatch() is not None:
|
| 136 |
+
cant_chunk += "- cannot split hatched path\n"
|
| 137 |
+
if not path.should_simplify:
|
| 138 |
+
cant_chunk += "- path.should_simplify is False\n"
|
| 139 |
+
if len(cant_chunk):
|
| 140 |
+
msg = (
|
| 141 |
+
"Exceeded cell block limit in Agg, however for the "
|
| 142 |
+
"following reasons:\n\n"
|
| 143 |
+
f"{cant_chunk}\n"
|
| 144 |
+
"we cannot automatically split up this path to draw."
|
| 145 |
+
"\n\nPlease manually simplify your path."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
else:
|
| 149 |
+
inc_threshold = (
|
| 150 |
+
"or increase the path simplification threshold"
|
| 151 |
+
"(rcParams['path.simplify_threshold'] = "
|
| 152 |
+
f"{mpl.rcParams['path.simplify_threshold']} "
|
| 153 |
+
"by default and path.simplify_threshold "
|
| 154 |
+
f"= {path.simplify_threshold} "
|
| 155 |
+
"on the input)."
|
| 156 |
+
)
|
| 157 |
+
if nmax > 100:
|
| 158 |
+
msg = (
|
| 159 |
+
"Exceeded cell block limit in Agg. Please reduce "
|
| 160 |
+
"the value of rcParams['agg.path.chunksize'] "
|
| 161 |
+
f"(currently {nmax}) {inc_threshold}"
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
msg = (
|
| 165 |
+
"Exceeded cell block limit in Agg. Please set "
|
| 166 |
+
"the value of rcParams['agg.path.chunksize'], "
|
| 167 |
+
f"(currently {nmax}) to be greater than 100 "
|
| 168 |
+
+ inc_threshold
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
raise OverflowError(msg) from None
|
| 172 |
+
|
| 173 |
+
def draw_mathtext(self, gc, x, y, s, prop, angle):
|
| 174 |
+
"""Draw mathtext using :mod:`matplotlib.mathtext`."""
|
| 175 |
+
ox, oy, width, height, descent, font_image = \
|
| 176 |
+
self.mathtext_parser.parse(s, self.dpi, prop,
|
| 177 |
+
antialiased=gc.get_antialiased())
|
| 178 |
+
|
| 179 |
+
xd = descent * sin(radians(angle))
|
| 180 |
+
yd = descent * cos(radians(angle))
|
| 181 |
+
x = round(x + ox + xd)
|
| 182 |
+
y = round(y - oy + yd)
|
| 183 |
+
self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
|
| 184 |
+
|
| 185 |
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
| 186 |
+
# docstring inherited
|
| 187 |
+
if ismath:
|
| 188 |
+
return self.draw_mathtext(gc, x, y, s, prop, angle)
|
| 189 |
+
font = self._prepare_font(prop)
|
| 190 |
+
# We pass '0' for angle here, since it will be rotated (in raster
|
| 191 |
+
# space) in the following call to draw_text_image).
|
| 192 |
+
font.set_text(s, 0, flags=get_hinting_flag())
|
| 193 |
+
font.draw_glyphs_to_bitmap(
|
| 194 |
+
antialiased=gc.get_antialiased())
|
| 195 |
+
d = font.get_descent() / 64.0
|
| 196 |
+
# The descent needs to be adjusted for the angle.
|
| 197 |
+
xo, yo = font.get_bitmap_offset()
|
| 198 |
+
xo /= 64.0
|
| 199 |
+
yo /= 64.0
|
| 200 |
+
xd = d * sin(radians(angle))
|
| 201 |
+
yd = d * cos(radians(angle))
|
| 202 |
+
x = round(x + xo + xd)
|
| 203 |
+
y = round(y + yo + yd)
|
| 204 |
+
self._renderer.draw_text_image(font, x, y + 1, angle, gc)
|
| 205 |
+
|
| 206 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 207 |
+
# docstring inherited
|
| 208 |
+
|
| 209 |
+
_api.check_in_list(["TeX", True, False], ismath=ismath)
|
| 210 |
+
if ismath == "TeX":
|
| 211 |
+
return super().get_text_width_height_descent(s, prop, ismath)
|
| 212 |
+
|
| 213 |
+
if ismath:
|
| 214 |
+
ox, oy, width, height, descent, font_image = \
|
| 215 |
+
self.mathtext_parser.parse(s, self.dpi, prop)
|
| 216 |
+
return width, height, descent
|
| 217 |
+
|
| 218 |
+
font = self._prepare_font(prop)
|
| 219 |
+
font.set_text(s, 0.0, flags=get_hinting_flag())
|
| 220 |
+
w, h = font.get_width_height() # width and height of unrotated string
|
| 221 |
+
d = font.get_descent()
|
| 222 |
+
w /= 64.0 # convert from subpixels
|
| 223 |
+
h /= 64.0
|
| 224 |
+
d /= 64.0
|
| 225 |
+
return w, h, d
|
| 226 |
+
|
| 227 |
+
def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
|
| 228 |
+
# docstring inherited
|
| 229 |
+
# todo, handle props, angle, origins
|
| 230 |
+
size = prop.get_size_in_points()
|
| 231 |
+
|
| 232 |
+
texmanager = self.get_texmanager()
|
| 233 |
+
|
| 234 |
+
Z = texmanager.get_grey(s, size, self.dpi)
|
| 235 |
+
Z = np.array(Z * 255.0, np.uint8)
|
| 236 |
+
|
| 237 |
+
w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX")
|
| 238 |
+
xd = d * sin(radians(angle))
|
| 239 |
+
yd = d * cos(radians(angle))
|
| 240 |
+
x = round(x + xd)
|
| 241 |
+
y = round(y + yd)
|
| 242 |
+
self._renderer.draw_text_image(Z, x, y, angle, gc)
|
| 243 |
+
|
| 244 |
+
def get_canvas_width_height(self):
|
| 245 |
+
# docstring inherited
|
| 246 |
+
return self.width, self.height
|
| 247 |
+
|
| 248 |
+
def _prepare_font(self, font_prop):
|
| 249 |
+
"""
|
| 250 |
+
Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size.
|
| 251 |
+
"""
|
| 252 |
+
font = get_font(_fontManager._find_fonts_by_props(font_prop))
|
| 253 |
+
font.clear()
|
| 254 |
+
size = font_prop.get_size_in_points()
|
| 255 |
+
font.set_size(size, self.dpi)
|
| 256 |
+
return font
|
| 257 |
+
|
| 258 |
+
def points_to_pixels(self, points):
|
| 259 |
+
# docstring inherited
|
| 260 |
+
return points * self.dpi / 72
|
| 261 |
+
|
| 262 |
+
def buffer_rgba(self):
|
| 263 |
+
return memoryview(self._renderer)
|
| 264 |
+
|
| 265 |
+
def tostring_argb(self):
|
| 266 |
+
return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
|
| 267 |
+
|
| 268 |
+
def clear(self):
|
| 269 |
+
self._renderer.clear()
|
| 270 |
+
|
| 271 |
+
def option_image_nocomposite(self):
|
| 272 |
+
# docstring inherited
|
| 273 |
+
|
| 274 |
+
# It is generally faster to composite each image directly to
|
| 275 |
+
# the Figure, and there's no file size benefit to compositing
|
| 276 |
+
# with the Agg backend
|
| 277 |
+
return True
|
| 278 |
+
|
| 279 |
+
def option_scale_image(self):
|
| 280 |
+
# docstring inherited
|
| 281 |
+
return False
|
| 282 |
+
|
| 283 |
+
def restore_region(self, region, bbox=None, xy=None):
|
| 284 |
+
"""
|
| 285 |
+
Restore the saved region. If bbox (instance of BboxBase, or
|
| 286 |
+
its extents) is given, only the region specified by the bbox
|
| 287 |
+
will be restored. *xy* (a pair of floats) optionally
|
| 288 |
+
specifies the new position (the LLC of the original region,
|
| 289 |
+
not the LLC of the bbox) where the region will be restored.
|
| 290 |
+
|
| 291 |
+
>>> region = renderer.copy_from_bbox()
|
| 292 |
+
>>> x1, y1, x2, y2 = region.get_extents()
|
| 293 |
+
>>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
|
| 294 |
+
... xy=(x1-dx, y1))
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
if bbox is not None or xy is not None:
|
| 298 |
+
if bbox is None:
|
| 299 |
+
x1, y1, x2, y2 = region.get_extents()
|
| 300 |
+
elif isinstance(bbox, BboxBase):
|
| 301 |
+
x1, y1, x2, y2 = bbox.extents
|
| 302 |
+
else:
|
| 303 |
+
x1, y1, x2, y2 = bbox
|
| 304 |
+
|
| 305 |
+
if xy is None:
|
| 306 |
+
ox, oy = x1, y1
|
| 307 |
+
else:
|
| 308 |
+
ox, oy = xy
|
| 309 |
+
|
| 310 |
+
# The incoming data is float, but the _renderer type-checking wants
|
| 311 |
+
# to see integers.
|
| 312 |
+
self._renderer.restore_region(region, int(x1), int(y1),
|
| 313 |
+
int(x2), int(y2), int(ox), int(oy))
|
| 314 |
+
|
| 315 |
+
else:
|
| 316 |
+
self._renderer.restore_region(region)
|
| 317 |
+
|
| 318 |
+
def start_filter(self):
|
| 319 |
+
"""
|
| 320 |
+
Start filtering. It simply creates a new canvas (the old one is saved).
|
| 321 |
+
"""
|
| 322 |
+
self._filter_renderers.append(self._renderer)
|
| 323 |
+
self._renderer = _RendererAgg(int(self.width), int(self.height),
|
| 324 |
+
self.dpi)
|
| 325 |
+
self._update_methods()
|
| 326 |
+
|
| 327 |
+
def stop_filter(self, post_processing):
|
| 328 |
+
"""
|
| 329 |
+
Save the current canvas as an image and apply post processing.
|
| 330 |
+
|
| 331 |
+
The *post_processing* function::
|
| 332 |
+
|
| 333 |
+
def post_processing(image, dpi):
|
| 334 |
+
# ny, nx, depth = image.shape
|
| 335 |
+
# image (numpy array) has RGBA channels and has a depth of 4.
|
| 336 |
+
...
|
| 337 |
+
# create a new_image (numpy array of 4 channels, size can be
|
| 338 |
+
# different). The resulting image may have offsets from
|
| 339 |
+
# lower-left corner of the original image
|
| 340 |
+
return new_image, offset_x, offset_y
|
| 341 |
+
|
| 342 |
+
The saved renderer is restored and the returned image from
|
| 343 |
+
post_processing is plotted (using draw_image) on it.
|
| 344 |
+
"""
|
| 345 |
+
orig_img = np.asarray(self.buffer_rgba())
|
| 346 |
+
slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3])
|
| 347 |
+
cropped_img = orig_img[slice_y, slice_x]
|
| 348 |
+
|
| 349 |
+
self._renderer = self._filter_renderers.pop()
|
| 350 |
+
self._update_methods()
|
| 351 |
+
|
| 352 |
+
if cropped_img.size:
|
| 353 |
+
img, ox, oy = post_processing(cropped_img / 255, self.dpi)
|
| 354 |
+
gc = self.new_gc()
|
| 355 |
+
if img.dtype.kind == 'f':
|
| 356 |
+
img = np.asarray(img * 255., np.uint8)
|
| 357 |
+
self._renderer.draw_image(
|
| 358 |
+
gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy,
|
| 359 |
+
img[::-1])
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class FigureCanvasAgg(FigureCanvasBase):
|
| 363 |
+
# docstring inherited
|
| 364 |
+
|
| 365 |
+
_lastKey = None # Overwritten per-instance on the first draw.
|
| 366 |
+
|
| 367 |
+
def copy_from_bbox(self, bbox):
|
| 368 |
+
renderer = self.get_renderer()
|
| 369 |
+
return renderer.copy_from_bbox(bbox)
|
| 370 |
+
|
| 371 |
+
def restore_region(self, region, bbox=None, xy=None):
|
| 372 |
+
renderer = self.get_renderer()
|
| 373 |
+
return renderer.restore_region(region, bbox, xy)
|
| 374 |
+
|
| 375 |
+
def draw(self):
|
| 376 |
+
# docstring inherited
|
| 377 |
+
self.renderer = self.get_renderer()
|
| 378 |
+
self.renderer.clear()
|
| 379 |
+
# Acquire a lock on the shared font cache.
|
| 380 |
+
with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
|
| 381 |
+
else nullcontext()):
|
| 382 |
+
self.figure.draw(self.renderer)
|
| 383 |
+
# A GUI class may be need to update a window using this draw, so
|
| 384 |
+
# don't forget to call the superclass.
|
| 385 |
+
super().draw()
|
| 386 |
+
|
| 387 |
+
def get_renderer(self):
|
| 388 |
+
w, h = self.figure.bbox.size
|
| 389 |
+
key = w, h, self.figure.dpi
|
| 390 |
+
reuse_renderer = (self._lastKey == key)
|
| 391 |
+
if not reuse_renderer:
|
| 392 |
+
self.renderer = RendererAgg(w, h, self.figure.dpi)
|
| 393 |
+
self._lastKey = key
|
| 394 |
+
return self.renderer
|
| 395 |
+
|
| 396 |
+
def tostring_argb(self):
|
| 397 |
+
"""
|
| 398 |
+
Get the image as ARGB `bytes`.
|
| 399 |
+
|
| 400 |
+
`draw` must be called at least once before this function will work and
|
| 401 |
+
to update the renderer for any subsequent changes to the Figure.
|
| 402 |
+
"""
|
| 403 |
+
return self.renderer.tostring_argb()
|
| 404 |
+
|
| 405 |
+
def buffer_rgba(self):
|
| 406 |
+
"""
|
| 407 |
+
Get the image as a `memoryview` to the renderer's buffer.
|
| 408 |
+
|
| 409 |
+
`draw` must be called at least once before this function will work and
|
| 410 |
+
to update the renderer for any subsequent changes to the Figure.
|
| 411 |
+
"""
|
| 412 |
+
return self.renderer.buffer_rgba()
|
| 413 |
+
|
| 414 |
+
def print_raw(self, filename_or_obj, *, metadata=None):
|
| 415 |
+
if metadata is not None:
|
| 416 |
+
raise ValueError("metadata not supported for raw/rgba")
|
| 417 |
+
FigureCanvasAgg.draw(self)
|
| 418 |
+
renderer = self.get_renderer()
|
| 419 |
+
with cbook.open_file_cm(filename_or_obj, "wb") as fh:
|
| 420 |
+
fh.write(renderer.buffer_rgba())
|
| 421 |
+
|
| 422 |
+
print_rgba = print_raw
|
| 423 |
+
|
| 424 |
+
def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
|
| 425 |
+
"""
|
| 426 |
+
Draw the canvas, then save it using `.image.imsave` (to which
|
| 427 |
+
*pil_kwargs* and *metadata* are forwarded).
|
| 428 |
+
"""
|
| 429 |
+
FigureCanvasAgg.draw(self)
|
| 430 |
+
mpl.image.imsave(
|
| 431 |
+
filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
|
| 432 |
+
dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)
|
| 433 |
+
|
| 434 |
+
def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
|
| 435 |
+
"""
|
| 436 |
+
Write the figure to a PNG file.
|
| 437 |
+
|
| 438 |
+
Parameters
|
| 439 |
+
----------
|
| 440 |
+
filename_or_obj : str or path-like or file-like
|
| 441 |
+
The file to write to.
|
| 442 |
+
|
| 443 |
+
metadata : dict, optional
|
| 444 |
+
Metadata in the PNG file as key-value pairs of bytes or latin-1
|
| 445 |
+
encodable strings.
|
| 446 |
+
According to the PNG specification, keys must be shorter than 79
|
| 447 |
+
chars.
|
| 448 |
+
|
| 449 |
+
The `PNG specification`_ defines some common keywords that may be
|
| 450 |
+
used as appropriate:
|
| 451 |
+
|
| 452 |
+
- Title: Short (one line) title or caption for image.
|
| 453 |
+
- Author: Name of image's creator.
|
| 454 |
+
- Description: Description of image (possibly long).
|
| 455 |
+
- Copyright: Copyright notice.
|
| 456 |
+
- Creation Time: Time of original image creation
|
| 457 |
+
(usually RFC 1123 format).
|
| 458 |
+
- Software: Software used to create the image.
|
| 459 |
+
- Disclaimer: Legal disclaimer.
|
| 460 |
+
- Warning: Warning of nature of content.
|
| 461 |
+
- Source: Device used to create the image.
|
| 462 |
+
- Comment: Miscellaneous comment;
|
| 463 |
+
conversion from other image format.
|
| 464 |
+
|
| 465 |
+
Other keywords may be invented for other purposes.
|
| 466 |
+
|
| 467 |
+
If 'Software' is not given, an autogenerated value for Matplotlib
|
| 468 |
+
will be used. This can be removed by setting it to *None*.
|
| 469 |
+
|
| 470 |
+
For more details see the `PNG specification`_.
|
| 471 |
+
|
| 472 |
+
.. _PNG specification: \
|
| 473 |
+
https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
|
| 474 |
+
|
| 475 |
+
pil_kwargs : dict, optional
|
| 476 |
+
Keyword arguments passed to `PIL.Image.Image.save`.
|
| 477 |
+
|
| 478 |
+
If the 'pnginfo' key is present, it completely overrides
|
| 479 |
+
*metadata*, including the default 'Software' key.
|
| 480 |
+
"""
|
| 481 |
+
self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)
|
| 482 |
+
|
| 483 |
+
def print_to_buffer(self):
|
| 484 |
+
FigureCanvasAgg.draw(self)
|
| 485 |
+
renderer = self.get_renderer()
|
| 486 |
+
return (bytes(renderer.buffer_rgba()),
|
| 487 |
+
(int(renderer.width), int(renderer.height)))
|
| 488 |
+
|
| 489 |
+
# Note that these methods should typically be called via savefig() and
|
| 490 |
+
# print_figure(), and the latter ensures that `self.figure.dpi` already
|
| 491 |
+
# matches the dpi kwarg (if any).
|
| 492 |
+
|
| 493 |
+
def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
|
| 494 |
+
# savefig() has already applied savefig.facecolor; we now set it to
|
| 495 |
+
# white to make imsave() blend semi-transparent figures against an
|
| 496 |
+
# assumed white background.
|
| 497 |
+
with mpl.rc_context({"savefig.facecolor": "white"}):
|
| 498 |
+
self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)
|
| 499 |
+
|
| 500 |
+
print_jpeg = print_jpg
|
| 501 |
+
|
| 502 |
+
def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
|
| 503 |
+
self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)
|
| 504 |
+
|
| 505 |
+
print_tiff = print_tif
|
| 506 |
+
|
| 507 |
+
def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
|
| 508 |
+
self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)
|
| 509 |
+
|
| 510 |
+
print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(
|
| 511 |
+
"""
|
| 512 |
+
Write the figure to a {} file.
|
| 513 |
+
|
| 514 |
+
Parameters
|
| 515 |
+
----------
|
| 516 |
+
filename_or_obj : str or path-like or file-like
|
| 517 |
+
The file to write to.
|
| 518 |
+
pil_kwargs : dict, optional
|
| 519 |
+
Additional keyword arguments that are passed to
|
| 520 |
+
`PIL.Image.Image.save` when saving the figure.
|
| 521 |
+
""".format, ["JPEG", "TIFF", "WebP"])
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
@_Backend.export
|
| 525 |
+
class _BackendAgg(_Backend):
|
| 526 |
+
backend_version = 'v2.2'
|
| 527 |
+
FigureCanvas = FigureCanvasAgg
|
| 528 |
+
FigureManager = FigureManagerBase
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_cairo.py
ADDED
|
@@ -0,0 +1,529 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A Cairo backend for Matplotlib
|
| 3 |
+
==============================
|
| 4 |
+
:Author: Steve Chaplin and others
|
| 5 |
+
|
| 6 |
+
This backend depends on cairocffi or pycairo.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import functools
|
| 10 |
+
import gzip
|
| 11 |
+
import math
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import cairo
|
| 17 |
+
if cairo.version_info < (1, 14, 0): # Introduced set_device_scale.
|
| 18 |
+
raise ImportError(f"Cairo backend requires cairo>=1.14.0, "
|
| 19 |
+
f"but only {cairo.version_info} is available")
|
| 20 |
+
except ImportError:
|
| 21 |
+
try:
|
| 22 |
+
import cairocffi as cairo
|
| 23 |
+
except ImportError as err:
|
| 24 |
+
raise ImportError(
|
| 25 |
+
"cairo backend requires that pycairo>=1.14.0 or cairocffi "
|
| 26 |
+
"is installed") from err
|
| 27 |
+
|
| 28 |
+
from .. import _api, cbook, font_manager
|
| 29 |
+
from matplotlib.backend_bases import (
|
| 30 |
+
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
|
| 31 |
+
RendererBase)
|
| 32 |
+
from matplotlib.font_manager import ttfFontProperty
|
| 33 |
+
from matplotlib.path import Path
|
| 34 |
+
from matplotlib.transforms import Affine2D
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _set_rgba(ctx, color, alpha, forced_alpha):
|
| 38 |
+
if len(color) == 3 or forced_alpha:
|
| 39 |
+
ctx.set_source_rgba(*color[:3], alpha)
|
| 40 |
+
else:
|
| 41 |
+
ctx.set_source_rgba(*color)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _append_path(ctx, path, transform, clip=None):
|
| 45 |
+
for points, code in path.iter_segments(
|
| 46 |
+
transform, remove_nans=True, clip=clip):
|
| 47 |
+
if code == Path.MOVETO:
|
| 48 |
+
ctx.move_to(*points)
|
| 49 |
+
elif code == Path.CLOSEPOLY:
|
| 50 |
+
ctx.close_path()
|
| 51 |
+
elif code == Path.LINETO:
|
| 52 |
+
ctx.line_to(*points)
|
| 53 |
+
elif code == Path.CURVE3:
|
| 54 |
+
cur = np.asarray(ctx.get_current_point())
|
| 55 |
+
a = points[:2]
|
| 56 |
+
b = points[-2:]
|
| 57 |
+
ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
|
| 58 |
+
elif code == Path.CURVE4:
|
| 59 |
+
ctx.curve_to(*points)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _cairo_font_args_from_font_prop(prop):
|
| 63 |
+
"""
|
| 64 |
+
Convert a `.FontProperties` or a `.FontEntry` to arguments that can be
|
| 65 |
+
passed to `.Context.select_font_face`.
|
| 66 |
+
"""
|
| 67 |
+
def attr(field):
|
| 68 |
+
try:
|
| 69 |
+
return getattr(prop, f"get_{field}")()
|
| 70 |
+
except AttributeError:
|
| 71 |
+
return getattr(prop, field)
|
| 72 |
+
|
| 73 |
+
name = attr("name")
|
| 74 |
+
slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}")
|
| 75 |
+
weight = attr("weight")
|
| 76 |
+
weight = (cairo.FONT_WEIGHT_NORMAL
|
| 77 |
+
if font_manager.weight_dict.get(weight, weight) < 550
|
| 78 |
+
else cairo.FONT_WEIGHT_BOLD)
|
| 79 |
+
return name, slant, weight
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class RendererCairo(RendererBase):
|
| 83 |
+
def __init__(self, dpi):
|
| 84 |
+
self.dpi = dpi
|
| 85 |
+
self.gc = GraphicsContextCairo(renderer=self)
|
| 86 |
+
self.width = None
|
| 87 |
+
self.height = None
|
| 88 |
+
self.text_ctx = cairo.Context(
|
| 89 |
+
cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
|
| 90 |
+
super().__init__()
|
| 91 |
+
|
| 92 |
+
def set_context(self, ctx):
|
| 93 |
+
surface = ctx.get_target()
|
| 94 |
+
if hasattr(surface, "get_width") and hasattr(surface, "get_height"):
|
| 95 |
+
size = surface.get_width(), surface.get_height()
|
| 96 |
+
elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface.
|
| 97 |
+
ext = surface.get_extents()
|
| 98 |
+
size = ext.width, ext.height
|
| 99 |
+
else: # vector surfaces.
|
| 100 |
+
ctx.save()
|
| 101 |
+
ctx.reset_clip()
|
| 102 |
+
rect, *rest = ctx.copy_clip_rectangle_list()
|
| 103 |
+
if rest:
|
| 104 |
+
raise TypeError("Cannot infer surface size")
|
| 105 |
+
_, _, *size = rect
|
| 106 |
+
ctx.restore()
|
| 107 |
+
self.gc.ctx = ctx
|
| 108 |
+
self.width, self.height = size
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides):
|
| 112 |
+
if fill_c is not None:
|
| 113 |
+
ctx.save()
|
| 114 |
+
_set_rgba(ctx, fill_c, alpha, alpha_overrides)
|
| 115 |
+
ctx.fill_preserve()
|
| 116 |
+
ctx.restore()
|
| 117 |
+
ctx.stroke()
|
| 118 |
+
|
| 119 |
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
| 120 |
+
# docstring inherited
|
| 121 |
+
ctx = gc.ctx
|
| 122 |
+
# Clip the path to the actual rendering extents if it isn't filled.
|
| 123 |
+
clip = (ctx.clip_extents()
|
| 124 |
+
if rgbFace is None and gc.get_hatch() is None
|
| 125 |
+
else None)
|
| 126 |
+
transform = (transform
|
| 127 |
+
+ Affine2D().scale(1, -1).translate(0, self.height))
|
| 128 |
+
ctx.new_path()
|
| 129 |
+
_append_path(ctx, path, transform, clip)
|
| 130 |
+
if rgbFace is not None:
|
| 131 |
+
ctx.save()
|
| 132 |
+
_set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
|
| 133 |
+
ctx.fill_preserve()
|
| 134 |
+
ctx.restore()
|
| 135 |
+
hatch_path = gc.get_hatch_path()
|
| 136 |
+
if hatch_path:
|
| 137 |
+
dpi = int(self.dpi)
|
| 138 |
+
hatch_surface = ctx.get_target().create_similar(
|
| 139 |
+
cairo.Content.COLOR_ALPHA, dpi, dpi)
|
| 140 |
+
hatch_ctx = cairo.Context(hatch_surface)
|
| 141 |
+
_append_path(hatch_ctx, hatch_path,
|
| 142 |
+
Affine2D().scale(dpi, -dpi).translate(0, dpi),
|
| 143 |
+
None)
|
| 144 |
+
hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth()))
|
| 145 |
+
hatch_ctx.set_source_rgba(*gc.get_hatch_color())
|
| 146 |
+
hatch_ctx.fill_preserve()
|
| 147 |
+
hatch_ctx.stroke()
|
| 148 |
+
hatch_pattern = cairo.SurfacePattern(hatch_surface)
|
| 149 |
+
hatch_pattern.set_extend(cairo.Extend.REPEAT)
|
| 150 |
+
ctx.save()
|
| 151 |
+
ctx.set_source(hatch_pattern)
|
| 152 |
+
ctx.fill_preserve()
|
| 153 |
+
ctx.restore()
|
| 154 |
+
ctx.stroke()
|
| 155 |
+
|
| 156 |
+
def draw_markers(self, gc, marker_path, marker_trans, path, transform,
|
| 157 |
+
rgbFace=None):
|
| 158 |
+
# docstring inherited
|
| 159 |
+
|
| 160 |
+
ctx = gc.ctx
|
| 161 |
+
ctx.new_path()
|
| 162 |
+
# Create the path for the marker; it needs to be flipped here already!
|
| 163 |
+
_append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1))
|
| 164 |
+
marker_path = ctx.copy_path_flat()
|
| 165 |
+
|
| 166 |
+
# Figure out whether the path has a fill
|
| 167 |
+
x1, y1, x2, y2 = ctx.fill_extents()
|
| 168 |
+
if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0:
|
| 169 |
+
filled = False
|
| 170 |
+
# No fill, just unset this (so we don't try to fill it later on)
|
| 171 |
+
rgbFace = None
|
| 172 |
+
else:
|
| 173 |
+
filled = True
|
| 174 |
+
|
| 175 |
+
transform = (transform
|
| 176 |
+
+ Affine2D().scale(1, -1).translate(0, self.height))
|
| 177 |
+
|
| 178 |
+
ctx.new_path()
|
| 179 |
+
for i, (vertices, codes) in enumerate(
|
| 180 |
+
path.iter_segments(transform, simplify=False)):
|
| 181 |
+
if len(vertices):
|
| 182 |
+
x, y = vertices[-2:]
|
| 183 |
+
ctx.save()
|
| 184 |
+
|
| 185 |
+
# Translate and apply path
|
| 186 |
+
ctx.translate(x, y)
|
| 187 |
+
ctx.append_path(marker_path)
|
| 188 |
+
|
| 189 |
+
ctx.restore()
|
| 190 |
+
|
| 191 |
+
# Slower code path if there is a fill; we need to draw
|
| 192 |
+
# the fill and stroke for each marker at the same time.
|
| 193 |
+
# Also flush out the drawing every once in a while to
|
| 194 |
+
# prevent the paths from getting way too long.
|
| 195 |
+
if filled or i % 1000 == 0:
|
| 196 |
+
self._fill_and_stroke(
|
| 197 |
+
ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
|
| 198 |
+
|
| 199 |
+
# Fast path, if there is no fill, draw everything in one step
|
| 200 |
+
if not filled:
|
| 201 |
+
self._fill_and_stroke(
|
| 202 |
+
ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
|
| 203 |
+
|
| 204 |
+
def draw_image(self, gc, x, y, im):
|
| 205 |
+
im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
|
| 206 |
+
surface = cairo.ImageSurface.create_for_data(
|
| 207 |
+
im.ravel().data, cairo.FORMAT_ARGB32,
|
| 208 |
+
im.shape[1], im.shape[0], im.shape[1] * 4)
|
| 209 |
+
ctx = gc.ctx
|
| 210 |
+
y = self.height - y - im.shape[0]
|
| 211 |
+
|
| 212 |
+
ctx.save()
|
| 213 |
+
ctx.set_source_surface(surface, float(x), float(y))
|
| 214 |
+
ctx.paint()
|
| 215 |
+
ctx.restore()
|
| 216 |
+
|
| 217 |
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
| 218 |
+
# docstring inherited
|
| 219 |
+
|
| 220 |
+
# Note: (x, y) are device/display coords, not user-coords, unlike other
|
| 221 |
+
# draw_* methods
|
| 222 |
+
if ismath:
|
| 223 |
+
self._draw_mathtext(gc, x, y, s, prop, angle)
|
| 224 |
+
|
| 225 |
+
else:
|
| 226 |
+
ctx = gc.ctx
|
| 227 |
+
ctx.new_path()
|
| 228 |
+
ctx.move_to(x, y)
|
| 229 |
+
|
| 230 |
+
ctx.save()
|
| 231 |
+
ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
|
| 232 |
+
ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
|
| 233 |
+
opts = cairo.FontOptions()
|
| 234 |
+
opts.set_antialias(gc.get_antialiased())
|
| 235 |
+
ctx.set_font_options(opts)
|
| 236 |
+
if angle:
|
| 237 |
+
ctx.rotate(np.deg2rad(-angle))
|
| 238 |
+
ctx.show_text(s)
|
| 239 |
+
ctx.restore()
|
| 240 |
+
|
| 241 |
+
def _draw_mathtext(self, gc, x, y, s, prop, angle):
|
| 242 |
+
ctx = gc.ctx
|
| 243 |
+
width, height, descent, glyphs, rects = \
|
| 244 |
+
self._text2path.mathtext_parser.parse(s, self.dpi, prop)
|
| 245 |
+
|
| 246 |
+
ctx.save()
|
| 247 |
+
ctx.translate(x, y)
|
| 248 |
+
if angle:
|
| 249 |
+
ctx.rotate(np.deg2rad(-angle))
|
| 250 |
+
|
| 251 |
+
for font, fontsize, idx, ox, oy in glyphs:
|
| 252 |
+
ctx.new_path()
|
| 253 |
+
ctx.move_to(ox, -oy)
|
| 254 |
+
ctx.select_font_face(
|
| 255 |
+
*_cairo_font_args_from_font_prop(ttfFontProperty(font)))
|
| 256 |
+
ctx.set_font_size(self.points_to_pixels(fontsize))
|
| 257 |
+
ctx.show_text(chr(idx))
|
| 258 |
+
|
| 259 |
+
for ox, oy, w, h in rects:
|
| 260 |
+
ctx.new_path()
|
| 261 |
+
ctx.rectangle(ox, -oy, w, -h)
|
| 262 |
+
ctx.set_source_rgb(0, 0, 0)
|
| 263 |
+
ctx.fill_preserve()
|
| 264 |
+
|
| 265 |
+
ctx.restore()
|
| 266 |
+
|
| 267 |
+
def get_canvas_width_height(self):
|
| 268 |
+
# docstring inherited
|
| 269 |
+
return self.width, self.height
|
| 270 |
+
|
| 271 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 272 |
+
# docstring inherited
|
| 273 |
+
|
| 274 |
+
if ismath == 'TeX':
|
| 275 |
+
return super().get_text_width_height_descent(s, prop, ismath)
|
| 276 |
+
|
| 277 |
+
if ismath:
|
| 278 |
+
width, height, descent, *_ = \
|
| 279 |
+
self._text2path.mathtext_parser.parse(s, self.dpi, prop)
|
| 280 |
+
return width, height, descent
|
| 281 |
+
|
| 282 |
+
ctx = self.text_ctx
|
| 283 |
+
# problem - scale remembers last setting and font can become
|
| 284 |
+
# enormous causing program to crash
|
| 285 |
+
# save/restore prevents the problem
|
| 286 |
+
ctx.save()
|
| 287 |
+
ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
|
| 288 |
+
ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
|
| 289 |
+
|
| 290 |
+
y_bearing, w, h = ctx.text_extents(s)[1:4]
|
| 291 |
+
ctx.restore()
|
| 292 |
+
|
| 293 |
+
return w, h, h + y_bearing
|
| 294 |
+
|
| 295 |
+
def new_gc(self):
|
| 296 |
+
# docstring inherited
|
| 297 |
+
self.gc.ctx.save()
|
| 298 |
+
# FIXME: The following doesn't properly implement a stack-like behavior
|
| 299 |
+
# and relies instead on the (non-guaranteed) fact that artists never
|
| 300 |
+
# rely on nesting gc states, so directly resetting the attributes (IOW
|
| 301 |
+
# a single-level stack) is enough.
|
| 302 |
+
self.gc._alpha = 1
|
| 303 |
+
self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA
|
| 304 |
+
self.gc._hatch = None
|
| 305 |
+
return self.gc
|
| 306 |
+
|
| 307 |
+
def points_to_pixels(self, points):
|
| 308 |
+
# docstring inherited
|
| 309 |
+
return points / 72 * self.dpi
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class GraphicsContextCairo(GraphicsContextBase):
|
| 313 |
+
_joind = {
|
| 314 |
+
'bevel': cairo.LINE_JOIN_BEVEL,
|
| 315 |
+
'miter': cairo.LINE_JOIN_MITER,
|
| 316 |
+
'round': cairo.LINE_JOIN_ROUND,
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
_capd = {
|
| 320 |
+
'butt': cairo.LINE_CAP_BUTT,
|
| 321 |
+
'projecting': cairo.LINE_CAP_SQUARE,
|
| 322 |
+
'round': cairo.LINE_CAP_ROUND,
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
def __init__(self, renderer):
|
| 326 |
+
super().__init__()
|
| 327 |
+
self.renderer = renderer
|
| 328 |
+
|
| 329 |
+
def restore(self):
|
| 330 |
+
self.ctx.restore()
|
| 331 |
+
|
| 332 |
+
def set_alpha(self, alpha):
|
| 333 |
+
super().set_alpha(alpha)
|
| 334 |
+
_set_rgba(
|
| 335 |
+
self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha())
|
| 336 |
+
|
| 337 |
+
def set_antialiased(self, b):
|
| 338 |
+
self.ctx.set_antialias(
|
| 339 |
+
cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE)
|
| 340 |
+
|
| 341 |
+
def get_antialiased(self):
|
| 342 |
+
return self.ctx.get_antialias()
|
| 343 |
+
|
| 344 |
+
def set_capstyle(self, cs):
|
| 345 |
+
self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))
|
| 346 |
+
self._capstyle = cs
|
| 347 |
+
|
| 348 |
+
def set_clip_rectangle(self, rectangle):
|
| 349 |
+
if not rectangle:
|
| 350 |
+
return
|
| 351 |
+
x, y, w, h = np.round(rectangle.bounds)
|
| 352 |
+
ctx = self.ctx
|
| 353 |
+
ctx.new_path()
|
| 354 |
+
ctx.rectangle(x, self.renderer.height - h - y, w, h)
|
| 355 |
+
ctx.clip()
|
| 356 |
+
|
| 357 |
+
def set_clip_path(self, path):
|
| 358 |
+
if not path:
|
| 359 |
+
return
|
| 360 |
+
tpath, affine = path.get_transformed_path_and_affine()
|
| 361 |
+
ctx = self.ctx
|
| 362 |
+
ctx.new_path()
|
| 363 |
+
affine = (affine
|
| 364 |
+
+ Affine2D().scale(1, -1).translate(0, self.renderer.height))
|
| 365 |
+
_append_path(ctx, tpath, affine)
|
| 366 |
+
ctx.clip()
|
| 367 |
+
|
| 368 |
+
def set_dashes(self, offset, dashes):
|
| 369 |
+
self._dashes = offset, dashes
|
| 370 |
+
if dashes is None:
|
| 371 |
+
self.ctx.set_dash([], 0) # switch dashes off
|
| 372 |
+
else:
|
| 373 |
+
self.ctx.set_dash(
|
| 374 |
+
list(self.renderer.points_to_pixels(np.asarray(dashes))),
|
| 375 |
+
offset)
|
| 376 |
+
|
| 377 |
+
def set_foreground(self, fg, isRGBA=None):
|
| 378 |
+
super().set_foreground(fg, isRGBA)
|
| 379 |
+
if len(self._rgb) == 3:
|
| 380 |
+
self.ctx.set_source_rgb(*self._rgb)
|
| 381 |
+
else:
|
| 382 |
+
self.ctx.set_source_rgba(*self._rgb)
|
| 383 |
+
|
| 384 |
+
def get_rgb(self):
|
| 385 |
+
return self.ctx.get_source().get_rgba()[:3]
|
| 386 |
+
|
| 387 |
+
def set_joinstyle(self, js):
|
| 388 |
+
self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))
|
| 389 |
+
self._joinstyle = js
|
| 390 |
+
|
| 391 |
+
def set_linewidth(self, w):
|
| 392 |
+
self._linewidth = float(w)
|
| 393 |
+
self.ctx.set_line_width(self.renderer.points_to_pixels(w))
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class _CairoRegion:
|
| 397 |
+
def __init__(self, slices, data):
|
| 398 |
+
self._slices = slices
|
| 399 |
+
self._data = data
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class FigureCanvasCairo(FigureCanvasBase):
|
| 403 |
+
@property
|
| 404 |
+
def _renderer(self):
|
| 405 |
+
# In theory, _renderer should be set in __init__, but GUI canvas
|
| 406 |
+
# subclasses (FigureCanvasFooCairo) don't always interact well with
|
| 407 |
+
# multiple inheritance (FigureCanvasFoo inits but doesn't super-init
|
| 408 |
+
# FigureCanvasCairo), so initialize it in the getter instead.
|
| 409 |
+
if not hasattr(self, "_cached_renderer"):
|
| 410 |
+
self._cached_renderer = RendererCairo(self.figure.dpi)
|
| 411 |
+
return self._cached_renderer
|
| 412 |
+
|
| 413 |
+
def get_renderer(self):
|
| 414 |
+
return self._renderer
|
| 415 |
+
|
| 416 |
+
def copy_from_bbox(self, bbox):
|
| 417 |
+
surface = self._renderer.gc.ctx.get_target()
|
| 418 |
+
if not isinstance(surface, cairo.ImageSurface):
|
| 419 |
+
raise RuntimeError(
|
| 420 |
+
"copy_from_bbox only works when rendering to an ImageSurface")
|
| 421 |
+
sw = surface.get_width()
|
| 422 |
+
sh = surface.get_height()
|
| 423 |
+
x0 = math.ceil(bbox.x0)
|
| 424 |
+
x1 = math.floor(bbox.x1)
|
| 425 |
+
y0 = math.ceil(sh - bbox.y1)
|
| 426 |
+
y1 = math.floor(sh - bbox.y0)
|
| 427 |
+
if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1
|
| 428 |
+
and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1):
|
| 429 |
+
raise ValueError("Invalid bbox")
|
| 430 |
+
sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0))
|
| 431 |
+
data = (np.frombuffer(surface.get_data(), np.uint32)
|
| 432 |
+
.reshape((sh, sw))[sls].copy())
|
| 433 |
+
return _CairoRegion(sls, data)
|
| 434 |
+
|
| 435 |
+
def restore_region(self, region):
|
| 436 |
+
surface = self._renderer.gc.ctx.get_target()
|
| 437 |
+
if not isinstance(surface, cairo.ImageSurface):
|
| 438 |
+
raise RuntimeError(
|
| 439 |
+
"restore_region only works when rendering to an ImageSurface")
|
| 440 |
+
surface.flush()
|
| 441 |
+
sw = surface.get_width()
|
| 442 |
+
sh = surface.get_height()
|
| 443 |
+
sly, slx = region._slices
|
| 444 |
+
(np.frombuffer(surface.get_data(), np.uint32)
|
| 445 |
+
.reshape((sh, sw))[sly, slx]) = region._data
|
| 446 |
+
surface.mark_dirty_rectangle(
|
| 447 |
+
slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start)
|
| 448 |
+
|
| 449 |
+
def print_png(self, fobj):
|
| 450 |
+
self._get_printed_image_surface().write_to_png(fobj)
|
| 451 |
+
|
| 452 |
+
def print_rgba(self, fobj):
|
| 453 |
+
width, height = self.get_width_height()
|
| 454 |
+
buf = self._get_printed_image_surface().get_data()
|
| 455 |
+
fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888(
|
| 456 |
+
np.asarray(buf).reshape((width, height, 4))))
|
| 457 |
+
|
| 458 |
+
print_raw = print_rgba
|
| 459 |
+
|
| 460 |
+
def _get_printed_image_surface(self):
|
| 461 |
+
self._renderer.dpi = self.figure.dpi
|
| 462 |
+
width, height = self.get_width_height()
|
| 463 |
+
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
|
| 464 |
+
self._renderer.set_context(cairo.Context(surface))
|
| 465 |
+
self.figure.draw(self._renderer)
|
| 466 |
+
return surface
|
| 467 |
+
|
| 468 |
+
def _save(self, fmt, fobj, *, orientation='portrait'):
|
| 469 |
+
# save PDF/PS/SVG
|
| 470 |
+
|
| 471 |
+
dpi = 72
|
| 472 |
+
self.figure.dpi = dpi
|
| 473 |
+
w_in, h_in = self.figure.get_size_inches()
|
| 474 |
+
width_in_points, height_in_points = w_in * dpi, h_in * dpi
|
| 475 |
+
|
| 476 |
+
if orientation == 'landscape':
|
| 477 |
+
width_in_points, height_in_points = (
|
| 478 |
+
height_in_points, width_in_points)
|
| 479 |
+
|
| 480 |
+
if fmt == 'ps':
|
| 481 |
+
if not hasattr(cairo, 'PSSurface'):
|
| 482 |
+
raise RuntimeError('cairo has not been compiled with PS '
|
| 483 |
+
'support enabled')
|
| 484 |
+
surface = cairo.PSSurface(fobj, width_in_points, height_in_points)
|
| 485 |
+
elif fmt == 'pdf':
|
| 486 |
+
if not hasattr(cairo, 'PDFSurface'):
|
| 487 |
+
raise RuntimeError('cairo has not been compiled with PDF '
|
| 488 |
+
'support enabled')
|
| 489 |
+
surface = cairo.PDFSurface(fobj, width_in_points, height_in_points)
|
| 490 |
+
elif fmt in ('svg', 'svgz'):
|
| 491 |
+
if not hasattr(cairo, 'SVGSurface'):
|
| 492 |
+
raise RuntimeError('cairo has not been compiled with SVG '
|
| 493 |
+
'support enabled')
|
| 494 |
+
if fmt == 'svgz':
|
| 495 |
+
if isinstance(fobj, str):
|
| 496 |
+
fobj = gzip.GzipFile(fobj, 'wb')
|
| 497 |
+
else:
|
| 498 |
+
fobj = gzip.GzipFile(None, 'wb', fileobj=fobj)
|
| 499 |
+
surface = cairo.SVGSurface(fobj, width_in_points, height_in_points)
|
| 500 |
+
else:
|
| 501 |
+
raise ValueError(f"Unknown format: {fmt!r}")
|
| 502 |
+
|
| 503 |
+
self._renderer.dpi = self.figure.dpi
|
| 504 |
+
self._renderer.set_context(cairo.Context(surface))
|
| 505 |
+
ctx = self._renderer.gc.ctx
|
| 506 |
+
|
| 507 |
+
if orientation == 'landscape':
|
| 508 |
+
ctx.rotate(np.pi / 2)
|
| 509 |
+
ctx.translate(0, -height_in_points)
|
| 510 |
+
# Perhaps add an '%%Orientation: Landscape' comment?
|
| 511 |
+
|
| 512 |
+
self.figure.draw(self._renderer)
|
| 513 |
+
|
| 514 |
+
ctx.show_page()
|
| 515 |
+
surface.finish()
|
| 516 |
+
if fmt == 'svgz':
|
| 517 |
+
fobj.close()
|
| 518 |
+
|
| 519 |
+
print_pdf = functools.partialmethod(_save, "pdf")
|
| 520 |
+
print_ps = functools.partialmethod(_save, "ps")
|
| 521 |
+
print_svg = functools.partialmethod(_save, "svg")
|
| 522 |
+
print_svgz = functools.partialmethod(_save, "svgz")
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@_Backend.export
|
| 526 |
+
class _BackendCairo(_Backend):
|
| 527 |
+
backend_version = cairo.version
|
| 528 |
+
FigureCanvas = FigureCanvasCairo
|
| 529 |
+
FigureManager = FigureManagerBase
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3.py
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import matplotlib as mpl
|
| 7 |
+
from matplotlib import _api, backend_tools, cbook
|
| 8 |
+
from matplotlib.backend_bases import (
|
| 9 |
+
ToolContainerBase, MouseButton,
|
| 10 |
+
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from gi import require_version as gi_require_version
|
| 14 |
+
except ImportError as err:
|
| 15 |
+
raise ImportError("The GTK3 backends require PyGObject") from err
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
# :raises ValueError: If module/version is already loaded, already
|
| 19 |
+
# required, or unavailable.
|
| 20 |
+
gi_require_version("Gtk", "3.0")
|
| 21 |
+
except ValueError as e:
|
| 22 |
+
# in this case we want to re-raise as ImportError so the
|
| 23 |
+
# auto-backend selection logic correctly skips.
|
| 24 |
+
raise ImportError(e) from e
|
| 25 |
+
|
| 26 |
+
from gi.repository import Gio, GLib, GObject, Gtk, Gdk
|
| 27 |
+
from . import _backend_gtk
|
| 28 |
+
from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
|
| 29 |
+
_BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
|
| 30 |
+
TimerGTK as TimerGTK3,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_log = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@functools.cache
|
| 38 |
+
def _mpl_to_gtk_cursor(mpl_cursor):
|
| 39 |
+
return Gdk.Cursor.new_from_name(
|
| 40 |
+
Gdk.Display.get_default(),
|
| 41 |
+
_backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea):
|
| 45 |
+
required_interactive_framework = "gtk3"
|
| 46 |
+
manager_class = _api.classproperty(lambda cls: FigureManagerGTK3)
|
| 47 |
+
# Setting this as a static constant prevents
|
| 48 |
+
# this resulting expression from leaking
|
| 49 |
+
event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK
|
| 50 |
+
| Gdk.EventMask.BUTTON_RELEASE_MASK
|
| 51 |
+
| Gdk.EventMask.EXPOSURE_MASK
|
| 52 |
+
| Gdk.EventMask.KEY_PRESS_MASK
|
| 53 |
+
| Gdk.EventMask.KEY_RELEASE_MASK
|
| 54 |
+
| Gdk.EventMask.ENTER_NOTIFY_MASK
|
| 55 |
+
| Gdk.EventMask.LEAVE_NOTIFY_MASK
|
| 56 |
+
| Gdk.EventMask.POINTER_MOTION_MASK
|
| 57 |
+
| Gdk.EventMask.SCROLL_MASK)
|
| 58 |
+
|
| 59 |
+
def __init__(self, figure=None):
|
| 60 |
+
super().__init__(figure=figure)
|
| 61 |
+
|
| 62 |
+
self._idle_draw_id = 0
|
| 63 |
+
self._rubberband_rect = None
|
| 64 |
+
|
| 65 |
+
self.connect('scroll_event', self.scroll_event)
|
| 66 |
+
self.connect('button_press_event', self.button_press_event)
|
| 67 |
+
self.connect('button_release_event', self.button_release_event)
|
| 68 |
+
self.connect('configure_event', self.configure_event)
|
| 69 |
+
self.connect('screen-changed', self._update_device_pixel_ratio)
|
| 70 |
+
self.connect('notify::scale-factor', self._update_device_pixel_ratio)
|
| 71 |
+
self.connect('draw', self.on_draw_event)
|
| 72 |
+
self.connect('draw', self._post_draw)
|
| 73 |
+
self.connect('key_press_event', self.key_press_event)
|
| 74 |
+
self.connect('key_release_event', self.key_release_event)
|
| 75 |
+
self.connect('motion_notify_event', self.motion_notify_event)
|
| 76 |
+
self.connect('enter_notify_event', self.enter_notify_event)
|
| 77 |
+
self.connect('leave_notify_event', self.leave_notify_event)
|
| 78 |
+
self.connect('size_allocate', self.size_allocate)
|
| 79 |
+
|
| 80 |
+
self.set_events(self.__class__.event_mask)
|
| 81 |
+
|
| 82 |
+
self.set_can_focus(True)
|
| 83 |
+
|
| 84 |
+
css = Gtk.CssProvider()
|
| 85 |
+
css.load_from_data(b".matplotlib-canvas { background-color: white; }")
|
| 86 |
+
style_ctx = self.get_style_context()
|
| 87 |
+
style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
|
| 88 |
+
style_ctx.add_class("matplotlib-canvas")
|
| 89 |
+
|
| 90 |
+
def destroy(self):
|
| 91 |
+
CloseEvent("close_event", self)._process()
|
| 92 |
+
|
| 93 |
+
def set_cursor(self, cursor):
|
| 94 |
+
# docstring inherited
|
| 95 |
+
window = self.get_property("window")
|
| 96 |
+
if window is not None:
|
| 97 |
+
window.set_cursor(_mpl_to_gtk_cursor(cursor))
|
| 98 |
+
context = GLib.MainContext.default()
|
| 99 |
+
context.iteration(True)
|
| 100 |
+
|
| 101 |
+
def _mpl_coords(self, event=None):
|
| 102 |
+
"""
|
| 103 |
+
Convert the position of a GTK event, or of the current cursor position
|
| 104 |
+
if *event* is None, to Matplotlib coordinates.
|
| 105 |
+
|
| 106 |
+
GTK use logical pixels, but the figure is scaled to physical pixels for
|
| 107 |
+
rendering. Transform to physical pixels so that all of the down-stream
|
| 108 |
+
transforms work as expected.
|
| 109 |
+
|
| 110 |
+
Also, the origin is different and needs to be corrected.
|
| 111 |
+
"""
|
| 112 |
+
if event is None:
|
| 113 |
+
window = self.get_window()
|
| 114 |
+
t, x, y, state = window.get_device_position(
|
| 115 |
+
window.get_display().get_device_manager().get_client_pointer())
|
| 116 |
+
else:
|
| 117 |
+
x, y = event.x, event.y
|
| 118 |
+
x = x * self.device_pixel_ratio
|
| 119 |
+
# flip y so y=0 is bottom of canvas
|
| 120 |
+
y = self.figure.bbox.height - y * self.device_pixel_ratio
|
| 121 |
+
return x, y
|
| 122 |
+
|
| 123 |
+
def scroll_event(self, widget, event):
|
| 124 |
+
step = 1 if event.direction == Gdk.ScrollDirection.UP else -1
|
| 125 |
+
MouseEvent("scroll_event", self,
|
| 126 |
+
*self._mpl_coords(event), step=step,
|
| 127 |
+
modifiers=self._mpl_modifiers(event.state),
|
| 128 |
+
guiEvent=event)._process()
|
| 129 |
+
return False # finish event propagation?
|
| 130 |
+
|
| 131 |
+
def button_press_event(self, widget, event):
|
| 132 |
+
MouseEvent("button_press_event", self,
|
| 133 |
+
*self._mpl_coords(event), event.button,
|
| 134 |
+
modifiers=self._mpl_modifiers(event.state),
|
| 135 |
+
guiEvent=event)._process()
|
| 136 |
+
return False # finish event propagation?
|
| 137 |
+
|
| 138 |
+
def button_release_event(self, widget, event):
|
| 139 |
+
MouseEvent("button_release_event", self,
|
| 140 |
+
*self._mpl_coords(event), event.button,
|
| 141 |
+
modifiers=self._mpl_modifiers(event.state),
|
| 142 |
+
guiEvent=event)._process()
|
| 143 |
+
return False # finish event propagation?
|
| 144 |
+
|
| 145 |
+
def key_press_event(self, widget, event):
|
| 146 |
+
KeyEvent("key_press_event", self,
|
| 147 |
+
self._get_key(event), *self._mpl_coords(),
|
| 148 |
+
guiEvent=event)._process()
|
| 149 |
+
return True # stop event propagation
|
| 150 |
+
|
| 151 |
+
def key_release_event(self, widget, event):
|
| 152 |
+
KeyEvent("key_release_event", self,
|
| 153 |
+
self._get_key(event), *self._mpl_coords(),
|
| 154 |
+
guiEvent=event)._process()
|
| 155 |
+
return True # stop event propagation
|
| 156 |
+
|
| 157 |
+
def motion_notify_event(self, widget, event):
|
| 158 |
+
MouseEvent("motion_notify_event", self, *self._mpl_coords(event),
|
| 159 |
+
buttons=self._mpl_buttons(event.state),
|
| 160 |
+
modifiers=self._mpl_modifiers(event.state),
|
| 161 |
+
guiEvent=event)._process()
|
| 162 |
+
return False # finish event propagation?
|
| 163 |
+
|
| 164 |
+
def enter_notify_event(self, widget, event):
|
| 165 |
+
gtk_mods = Gdk.Keymap.get_for_display(
|
| 166 |
+
self.get_display()).get_modifier_state()
|
| 167 |
+
LocationEvent("figure_enter_event", self, *self._mpl_coords(event),
|
| 168 |
+
modifiers=self._mpl_modifiers(gtk_mods),
|
| 169 |
+
guiEvent=event)._process()
|
| 170 |
+
|
| 171 |
+
def leave_notify_event(self, widget, event):
|
| 172 |
+
gtk_mods = Gdk.Keymap.get_for_display(
|
| 173 |
+
self.get_display()).get_modifier_state()
|
| 174 |
+
LocationEvent("figure_leave_event", self, *self._mpl_coords(event),
|
| 175 |
+
modifiers=self._mpl_modifiers(gtk_mods),
|
| 176 |
+
guiEvent=event)._process()
|
| 177 |
+
|
| 178 |
+
def size_allocate(self, widget, allocation):
|
| 179 |
+
dpival = self.figure.dpi
|
| 180 |
+
winch = allocation.width * self.device_pixel_ratio / dpival
|
| 181 |
+
hinch = allocation.height * self.device_pixel_ratio / dpival
|
| 182 |
+
self.figure.set_size_inches(winch, hinch, forward=False)
|
| 183 |
+
ResizeEvent("resize_event", self)._process()
|
| 184 |
+
self.draw_idle()
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def _mpl_buttons(event_state):
|
| 188 |
+
modifiers = [
|
| 189 |
+
(MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),
|
| 190 |
+
(MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),
|
| 191 |
+
(MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),
|
| 192 |
+
(MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),
|
| 193 |
+
(MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),
|
| 194 |
+
]
|
| 195 |
+
# State *before* press/release.
|
| 196 |
+
return [name for name, mask in modifiers if event_state & mask]
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def _mpl_modifiers(event_state, *, exclude=None):
|
| 200 |
+
modifiers = [
|
| 201 |
+
("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
|
| 202 |
+
("alt", Gdk.ModifierType.MOD1_MASK, "alt"),
|
| 203 |
+
("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
|
| 204 |
+
("super", Gdk.ModifierType.MOD4_MASK, "super"),
|
| 205 |
+
]
|
| 206 |
+
return [name for name, mask, key in modifiers
|
| 207 |
+
if exclude != key and event_state & mask]
|
| 208 |
+
|
| 209 |
+
def _get_key(self, event):
|
| 210 |
+
unikey = chr(Gdk.keyval_to_unicode(event.keyval))
|
| 211 |
+
key = cbook._unikey_or_keysym_to_mplkey(
|
| 212 |
+
unikey, Gdk.keyval_name(event.keyval))
|
| 213 |
+
mods = self._mpl_modifiers(event.state, exclude=key)
|
| 214 |
+
if "shift" in mods and unikey.isprintable():
|
| 215 |
+
mods.remove("shift")
|
| 216 |
+
return "+".join([*mods, key])
|
| 217 |
+
|
| 218 |
+
def _update_device_pixel_ratio(self, *args, **kwargs):
|
| 219 |
+
# We need to be careful in cases with mixed resolution displays if
|
| 220 |
+
# device_pixel_ratio changes.
|
| 221 |
+
if self._set_device_pixel_ratio(self.get_scale_factor()):
|
| 222 |
+
# The easiest way to resize the canvas is to emit a resize event
|
| 223 |
+
# since we implement all the logic for resizing the canvas for that
|
| 224 |
+
# event.
|
| 225 |
+
self.queue_resize()
|
| 226 |
+
self.queue_draw()
|
| 227 |
+
|
| 228 |
+
def configure_event(self, widget, event):
|
| 229 |
+
if widget.get_property("window") is None:
|
| 230 |
+
return
|
| 231 |
+
w = event.width * self.device_pixel_ratio
|
| 232 |
+
h = event.height * self.device_pixel_ratio
|
| 233 |
+
if w < 3 or h < 3:
|
| 234 |
+
return # empty fig
|
| 235 |
+
# resize the figure (in inches)
|
| 236 |
+
dpi = self.figure.dpi
|
| 237 |
+
self.figure.set_size_inches(w / dpi, h / dpi, forward=False)
|
| 238 |
+
return False # finish event propagation?
|
| 239 |
+
|
| 240 |
+
def _draw_rubberband(self, rect):
|
| 241 |
+
self._rubberband_rect = rect
|
| 242 |
+
# TODO: Only update the rubberband area.
|
| 243 |
+
self.queue_draw()
|
| 244 |
+
|
| 245 |
+
def _post_draw(self, widget, ctx):
|
| 246 |
+
if self._rubberband_rect is None:
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
x0, y0, w, h = (dim / self.device_pixel_ratio
|
| 250 |
+
for dim in self._rubberband_rect)
|
| 251 |
+
x1 = x0 + w
|
| 252 |
+
y1 = y0 + h
|
| 253 |
+
|
| 254 |
+
# Draw the lines from x0, y0 towards x1, y1 so that the
|
| 255 |
+
# dashes don't "jump" when moving the zoom box.
|
| 256 |
+
ctx.move_to(x0, y0)
|
| 257 |
+
ctx.line_to(x0, y1)
|
| 258 |
+
ctx.move_to(x0, y0)
|
| 259 |
+
ctx.line_to(x1, y0)
|
| 260 |
+
ctx.move_to(x0, y1)
|
| 261 |
+
ctx.line_to(x1, y1)
|
| 262 |
+
ctx.move_to(x1, y0)
|
| 263 |
+
ctx.line_to(x1, y1)
|
| 264 |
+
|
| 265 |
+
ctx.set_antialias(1)
|
| 266 |
+
ctx.set_line_width(1)
|
| 267 |
+
ctx.set_dash((3, 3), 0)
|
| 268 |
+
ctx.set_source_rgb(0, 0, 0)
|
| 269 |
+
ctx.stroke_preserve()
|
| 270 |
+
|
| 271 |
+
ctx.set_dash((3, 3), 3)
|
| 272 |
+
ctx.set_source_rgb(1, 1, 1)
|
| 273 |
+
ctx.stroke()
|
| 274 |
+
|
| 275 |
+
def on_draw_event(self, widget, ctx):
|
| 276 |
+
# to be overwritten by GTK3Agg or GTK3Cairo
|
| 277 |
+
pass
|
| 278 |
+
|
| 279 |
+
def draw(self):
|
| 280 |
+
# docstring inherited
|
| 281 |
+
if self.is_drawable():
|
| 282 |
+
self.queue_draw()
|
| 283 |
+
|
| 284 |
+
def draw_idle(self):
|
| 285 |
+
# docstring inherited
|
| 286 |
+
if self._idle_draw_id != 0:
|
| 287 |
+
return
|
| 288 |
+
def idle_draw(*args):
|
| 289 |
+
try:
|
| 290 |
+
self.draw()
|
| 291 |
+
finally:
|
| 292 |
+
self._idle_draw_id = 0
|
| 293 |
+
return False
|
| 294 |
+
self._idle_draw_id = GLib.idle_add(idle_draw)
|
| 295 |
+
|
| 296 |
+
def flush_events(self):
|
| 297 |
+
# docstring inherited
|
| 298 |
+
context = GLib.MainContext.default()
|
| 299 |
+
while context.pending():
|
| 300 |
+
context.iteration(True)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar):
|
| 304 |
+
def __init__(self, canvas):
|
| 305 |
+
GObject.GObject.__init__(self)
|
| 306 |
+
|
| 307 |
+
self.set_style(Gtk.ToolbarStyle.ICONS)
|
| 308 |
+
|
| 309 |
+
self._gtk_ids = {}
|
| 310 |
+
for text, tooltip_text, image_file, callback in self.toolitems:
|
| 311 |
+
if text is None:
|
| 312 |
+
self.insert(Gtk.SeparatorToolItem(), -1)
|
| 313 |
+
continue
|
| 314 |
+
image = Gtk.Image.new_from_gicon(
|
| 315 |
+
Gio.Icon.new_for_string(
|
| 316 |
+
str(cbook._get_data_path('images',
|
| 317 |
+
f'{image_file}-symbolic.svg'))),
|
| 318 |
+
Gtk.IconSize.LARGE_TOOLBAR)
|
| 319 |
+
self._gtk_ids[text] = button = (
|
| 320 |
+
Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else
|
| 321 |
+
Gtk.ToolButton())
|
| 322 |
+
button.set_label(text)
|
| 323 |
+
button.set_icon_widget(image)
|
| 324 |
+
# Save the handler id, so that we can block it as needed.
|
| 325 |
+
button._signal_handler = button.connect(
|
| 326 |
+
'clicked', getattr(self, callback))
|
| 327 |
+
button.set_tooltip_text(tooltip_text)
|
| 328 |
+
self.insert(button, -1)
|
| 329 |
+
|
| 330 |
+
# This filler item ensures the toolbar is always at least two text
|
| 331 |
+
# lines high. Otherwise the canvas gets redrawn as the mouse hovers
|
| 332 |
+
# over images because those use two-line messages which resize the
|
| 333 |
+
# toolbar.
|
| 334 |
+
toolitem = Gtk.ToolItem()
|
| 335 |
+
self.insert(toolitem, -1)
|
| 336 |
+
label = Gtk.Label()
|
| 337 |
+
label.set_markup(
|
| 338 |
+
'<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
|
| 339 |
+
toolitem.set_expand(True) # Push real message to the right.
|
| 340 |
+
toolitem.add(label)
|
| 341 |
+
|
| 342 |
+
toolitem = Gtk.ToolItem()
|
| 343 |
+
self.insert(toolitem, -1)
|
| 344 |
+
self.message = Gtk.Label()
|
| 345 |
+
self.message.set_justify(Gtk.Justification.RIGHT)
|
| 346 |
+
toolitem.add(self.message)
|
| 347 |
+
|
| 348 |
+
self.show_all()
|
| 349 |
+
|
| 350 |
+
_NavigationToolbar2GTK.__init__(self, canvas)
|
| 351 |
+
|
| 352 |
+
def save_figure(self, *args):
|
| 353 |
+
dialog = Gtk.FileChooserDialog(
|
| 354 |
+
title="Save the figure",
|
| 355 |
+
transient_for=self.canvas.get_toplevel(),
|
| 356 |
+
action=Gtk.FileChooserAction.SAVE,
|
| 357 |
+
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
|
| 358 |
+
Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
|
| 359 |
+
)
|
| 360 |
+
for name, fmts \
|
| 361 |
+
in self.canvas.get_supported_filetypes_grouped().items():
|
| 362 |
+
ff = Gtk.FileFilter()
|
| 363 |
+
ff.set_name(name)
|
| 364 |
+
for fmt in fmts:
|
| 365 |
+
ff.add_pattern(f'*.{fmt}')
|
| 366 |
+
dialog.add_filter(ff)
|
| 367 |
+
if self.canvas.get_default_filetype() in fmts:
|
| 368 |
+
dialog.set_filter(ff)
|
| 369 |
+
|
| 370 |
+
@functools.partial(dialog.connect, "notify::filter")
|
| 371 |
+
def on_notify_filter(*args):
|
| 372 |
+
name = dialog.get_filter().get_name()
|
| 373 |
+
fmt = self.canvas.get_supported_filetypes_grouped()[name][0]
|
| 374 |
+
dialog.set_current_name(
|
| 375 |
+
str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}')))
|
| 376 |
+
|
| 377 |
+
dialog.set_current_folder(mpl.rcParams["savefig.directory"])
|
| 378 |
+
dialog.set_current_name(self.canvas.get_default_filename())
|
| 379 |
+
dialog.set_do_overwrite_confirmation(True)
|
| 380 |
+
|
| 381 |
+
response = dialog.run()
|
| 382 |
+
fname = dialog.get_filename()
|
| 383 |
+
ff = dialog.get_filter() # Doesn't autoadjust to filename :/
|
| 384 |
+
fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0]
|
| 385 |
+
dialog.destroy()
|
| 386 |
+
if response != Gtk.ResponseType.OK:
|
| 387 |
+
return None
|
| 388 |
+
# Save dir for next time, unless empty str (which means use cwd).
|
| 389 |
+
if mpl.rcParams['savefig.directory']:
|
| 390 |
+
mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
|
| 391 |
+
try:
|
| 392 |
+
self.canvas.figure.savefig(fname, format=fmt)
|
| 393 |
+
return fname
|
| 394 |
+
except Exception as e:
|
| 395 |
+
dialog = Gtk.MessageDialog(
|
| 396 |
+
transient_for=self.canvas.get_toplevel(), text=str(e),
|
| 397 |
+
message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
|
| 398 |
+
dialog.run()
|
| 399 |
+
dialog.destroy()
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class ToolbarGTK3(ToolContainerBase, Gtk.Box):
|
| 403 |
+
_icon_extension = '-symbolic.svg'
|
| 404 |
+
|
| 405 |
+
def __init__(self, toolmanager):
|
| 406 |
+
ToolContainerBase.__init__(self, toolmanager)
|
| 407 |
+
Gtk.Box.__init__(self)
|
| 408 |
+
self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
|
| 409 |
+
self._message = Gtk.Label()
|
| 410 |
+
self._message.set_justify(Gtk.Justification.RIGHT)
|
| 411 |
+
self.pack_end(self._message, False, False, 0)
|
| 412 |
+
self.show_all()
|
| 413 |
+
self._groups = {}
|
| 414 |
+
self._toolitems = {}
|
| 415 |
+
|
| 416 |
+
def add_toolitem(self, name, group, position, image_file, description,
|
| 417 |
+
toggle):
|
| 418 |
+
if toggle:
|
| 419 |
+
button = Gtk.ToggleToolButton()
|
| 420 |
+
else:
|
| 421 |
+
button = Gtk.ToolButton()
|
| 422 |
+
button.set_label(name)
|
| 423 |
+
|
| 424 |
+
if image_file is not None:
|
| 425 |
+
image = Gtk.Image.new_from_gicon(
|
| 426 |
+
Gio.Icon.new_for_string(image_file),
|
| 427 |
+
Gtk.IconSize.LARGE_TOOLBAR)
|
| 428 |
+
button.set_icon_widget(image)
|
| 429 |
+
|
| 430 |
+
if position is None:
|
| 431 |
+
position = -1
|
| 432 |
+
|
| 433 |
+
self._add_button(button, group, position)
|
| 434 |
+
signal = button.connect('clicked', self._call_tool, name)
|
| 435 |
+
button.set_tooltip_text(description)
|
| 436 |
+
button.show_all()
|
| 437 |
+
self._toolitems.setdefault(name, [])
|
| 438 |
+
self._toolitems[name].append((button, signal))
|
| 439 |
+
|
| 440 |
+
def _add_button(self, button, group, position):
|
| 441 |
+
if group not in self._groups:
|
| 442 |
+
if self._groups:
|
| 443 |
+
self._add_separator()
|
| 444 |
+
toolbar = Gtk.Toolbar()
|
| 445 |
+
toolbar.set_style(Gtk.ToolbarStyle.ICONS)
|
| 446 |
+
self.pack_start(toolbar, False, False, 0)
|
| 447 |
+
toolbar.show_all()
|
| 448 |
+
self._groups[group] = toolbar
|
| 449 |
+
self._groups[group].insert(button, position)
|
| 450 |
+
|
| 451 |
+
def _call_tool(self, btn, name):
|
| 452 |
+
self.trigger_tool(name)
|
| 453 |
+
|
| 454 |
+
def toggle_toolitem(self, name, toggled):
|
| 455 |
+
if name not in self._toolitems:
|
| 456 |
+
return
|
| 457 |
+
for toolitem, signal in self._toolitems[name]:
|
| 458 |
+
toolitem.handler_block(signal)
|
| 459 |
+
toolitem.set_active(toggled)
|
| 460 |
+
toolitem.handler_unblock(signal)
|
| 461 |
+
|
| 462 |
+
def remove_toolitem(self, name):
|
| 463 |
+
for toolitem, _signal in self._toolitems.pop(name, []):
|
| 464 |
+
for group in self._groups:
|
| 465 |
+
if toolitem in self._groups[group]:
|
| 466 |
+
self._groups[group].remove(toolitem)
|
| 467 |
+
|
| 468 |
+
def _add_separator(self):
|
| 469 |
+
sep = Gtk.Separator()
|
| 470 |
+
sep.set_property("orientation", Gtk.Orientation.VERTICAL)
|
| 471 |
+
self.pack_start(sep, False, True, 0)
|
| 472 |
+
sep.show_all()
|
| 473 |
+
|
| 474 |
+
def set_message(self, s):
|
| 475 |
+
self._message.set_label(s)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@backend_tools._register_tool_class(FigureCanvasGTK3)
|
| 479 |
+
class SaveFigureGTK3(backend_tools.SaveFigureBase):
|
| 480 |
+
def trigger(self, *args, **kwargs):
|
| 481 |
+
NavigationToolbar2GTK3.save_figure(
|
| 482 |
+
self._make_classic_style_pseudo_toolbar())
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
@backend_tools._register_tool_class(FigureCanvasGTK3)
|
| 486 |
+
class HelpGTK3(backend_tools.ToolHelpBase):
|
| 487 |
+
def _normalize_shortcut(self, key):
|
| 488 |
+
"""
|
| 489 |
+
Convert Matplotlib key presses to GTK+ accelerator identifiers.
|
| 490 |
+
|
| 491 |
+
Related to `FigureCanvasGTK3._get_key`.
|
| 492 |
+
"""
|
| 493 |
+
special = {
|
| 494 |
+
'backspace': 'BackSpace',
|
| 495 |
+
'pagedown': 'Page_Down',
|
| 496 |
+
'pageup': 'Page_Up',
|
| 497 |
+
'scroll_lock': 'Scroll_Lock',
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
parts = key.split('+')
|
| 501 |
+
mods = ['<' + mod + '>' for mod in parts[:-1]]
|
| 502 |
+
key = parts[-1]
|
| 503 |
+
|
| 504 |
+
if key in special:
|
| 505 |
+
key = special[key]
|
| 506 |
+
elif len(key) > 1:
|
| 507 |
+
key = key.capitalize()
|
| 508 |
+
elif key.isupper():
|
| 509 |
+
mods += ['<shift>']
|
| 510 |
+
|
| 511 |
+
return ''.join(mods) + key
|
| 512 |
+
|
| 513 |
+
def _is_valid_shortcut(self, key):
|
| 514 |
+
"""
|
| 515 |
+
Check for a valid shortcut to be displayed.
|
| 516 |
+
|
| 517 |
+
- GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`).
|
| 518 |
+
- The shortcut window only shows keyboard shortcuts, not mouse buttons.
|
| 519 |
+
"""
|
| 520 |
+
return 'cmd+' not in key and not key.startswith('MouseButton.')
|
| 521 |
+
|
| 522 |
+
def _show_shortcuts_window(self):
|
| 523 |
+
section = Gtk.ShortcutsSection()
|
| 524 |
+
|
| 525 |
+
for name, tool in sorted(self.toolmanager.tools.items()):
|
| 526 |
+
if not tool.description:
|
| 527 |
+
continue
|
| 528 |
+
|
| 529 |
+
# Putting everything in a separate group allows GTK to
|
| 530 |
+
# automatically split them into separate columns/pages, which is
|
| 531 |
+
# useful because we have lots of shortcuts, some with many keys
|
| 532 |
+
# that are very wide.
|
| 533 |
+
group = Gtk.ShortcutsGroup()
|
| 534 |
+
section.add(group)
|
| 535 |
+
# A hack to remove the title since we have no group naming.
|
| 536 |
+
group.forall(lambda widget, data: widget.set_visible(False), None)
|
| 537 |
+
|
| 538 |
+
shortcut = Gtk.ShortcutsShortcut(
|
| 539 |
+
accelerator=' '.join(
|
| 540 |
+
self._normalize_shortcut(key)
|
| 541 |
+
for key in self.toolmanager.get_tool_keymap(name)
|
| 542 |
+
if self._is_valid_shortcut(key)),
|
| 543 |
+
title=tool.name,
|
| 544 |
+
subtitle=tool.description)
|
| 545 |
+
group.add(shortcut)
|
| 546 |
+
|
| 547 |
+
window = Gtk.ShortcutsWindow(
|
| 548 |
+
title='Help',
|
| 549 |
+
modal=True,
|
| 550 |
+
transient_for=self._figure.canvas.get_toplevel())
|
| 551 |
+
section.show() # Must be done explicitly before add!
|
| 552 |
+
window.add(section)
|
| 553 |
+
|
| 554 |
+
window.show_all()
|
| 555 |
+
|
| 556 |
+
def _show_shortcuts_dialog(self):
|
| 557 |
+
dialog = Gtk.MessageDialog(
|
| 558 |
+
self._figure.canvas.get_toplevel(),
|
| 559 |
+
0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(),
|
| 560 |
+
title="Help")
|
| 561 |
+
dialog.run()
|
| 562 |
+
dialog.destroy()
|
| 563 |
+
|
| 564 |
+
def trigger(self, *args):
|
| 565 |
+
if Gtk.check_version(3, 20, 0) is None:
|
| 566 |
+
self._show_shortcuts_window()
|
| 567 |
+
else:
|
| 568 |
+
self._show_shortcuts_dialog()
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
@backend_tools._register_tool_class(FigureCanvasGTK3)
|
| 572 |
+
class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase):
|
| 573 |
+
def trigger(self, *args, **kwargs):
|
| 574 |
+
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
|
| 575 |
+
window = self.canvas.get_window()
|
| 576 |
+
x, y, width, height = window.get_geometry()
|
| 577 |
+
pb = Gdk.pixbuf_get_from_window(window, x, y, width, height)
|
| 578 |
+
clipboard.set_image(pb)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
Toolbar = ToolbarGTK3
|
| 582 |
+
backend_tools._register_tool_class(
|
| 583 |
+
FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK)
|
| 584 |
+
backend_tools._register_tool_class(
|
| 585 |
+
FigureCanvasGTK3, _backend_gtk.RubberbandGTK)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
class FigureManagerGTK3(_FigureManagerGTK):
|
| 589 |
+
_toolbar2_class = NavigationToolbar2GTK3
|
| 590 |
+
_toolmanager_toolbar_class = ToolbarGTK3
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
@_BackendGTK.export
|
| 594 |
+
class _BackendGTK3(_BackendGTK):
|
| 595 |
+
FigureCanvas = FigureCanvasGTK3
|
| 596 |
+
FigureManager = FigureManagerGTK3
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3agg.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from .. import cbook, transforms
|
| 4 |
+
from . import backend_agg, backend_gtk3
|
| 5 |
+
from .backend_gtk3 import GLib, Gtk, _BackendGTK3
|
| 6 |
+
|
| 7 |
+
import cairo # Presence of cairo is already checked by _backend_gtk.
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg,
|
| 11 |
+
backend_gtk3.FigureCanvasGTK3):
|
| 12 |
+
def __init__(self, figure):
|
| 13 |
+
super().__init__(figure=figure)
|
| 14 |
+
self._bbox_queue = []
|
| 15 |
+
|
| 16 |
+
def on_draw_event(self, widget, ctx):
|
| 17 |
+
if self._idle_draw_id:
|
| 18 |
+
GLib.source_remove(self._idle_draw_id)
|
| 19 |
+
self._idle_draw_id = 0
|
| 20 |
+
self.draw()
|
| 21 |
+
|
| 22 |
+
scale = self.device_pixel_ratio
|
| 23 |
+
allocation = self.get_allocation()
|
| 24 |
+
w = allocation.width * scale
|
| 25 |
+
h = allocation.height * scale
|
| 26 |
+
|
| 27 |
+
if not len(self._bbox_queue):
|
| 28 |
+
Gtk.render_background(
|
| 29 |
+
self.get_style_context(), ctx,
|
| 30 |
+
allocation.x, allocation.y,
|
| 31 |
+
allocation.width, allocation.height)
|
| 32 |
+
bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]
|
| 33 |
+
else:
|
| 34 |
+
bbox_queue = self._bbox_queue
|
| 35 |
+
|
| 36 |
+
for bbox in bbox_queue:
|
| 37 |
+
x = int(bbox.x0)
|
| 38 |
+
y = h - int(bbox.y1)
|
| 39 |
+
width = int(bbox.x1) - int(bbox.x0)
|
| 40 |
+
height = int(bbox.y1) - int(bbox.y0)
|
| 41 |
+
|
| 42 |
+
buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(
|
| 43 |
+
np.asarray(self.copy_from_bbox(bbox)))
|
| 44 |
+
image = cairo.ImageSurface.create_for_data(
|
| 45 |
+
buf.ravel().data, cairo.FORMAT_ARGB32, width, height)
|
| 46 |
+
image.set_device_scale(scale, scale)
|
| 47 |
+
ctx.set_source_surface(image, x / scale, y / scale)
|
| 48 |
+
ctx.paint()
|
| 49 |
+
|
| 50 |
+
if len(self._bbox_queue):
|
| 51 |
+
self._bbox_queue = []
|
| 52 |
+
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
def blit(self, bbox=None):
|
| 56 |
+
# If bbox is None, blit the entire canvas to gtk. Otherwise
|
| 57 |
+
# blit only the area defined by the bbox.
|
| 58 |
+
if bbox is None:
|
| 59 |
+
bbox = self.figure.bbox
|
| 60 |
+
|
| 61 |
+
scale = self.device_pixel_ratio
|
| 62 |
+
allocation = self.get_allocation()
|
| 63 |
+
x = int(bbox.x0 / scale)
|
| 64 |
+
y = allocation.height - int(bbox.y1 / scale)
|
| 65 |
+
width = (int(bbox.x1) - int(bbox.x0)) // scale
|
| 66 |
+
height = (int(bbox.y1) - int(bbox.y0)) // scale
|
| 67 |
+
|
| 68 |
+
self._bbox_queue.append(bbox)
|
| 69 |
+
self.queue_draw_area(x, y, width, height)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@_BackendGTK3.export
|
| 73 |
+
class _BackendGTK3Agg(_BackendGTK3):
|
| 74 |
+
FigureCanvas = FigureCanvasGTK3Agg
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3cairo.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import nullcontext
|
| 2 |
+
|
| 3 |
+
from .backend_cairo import FigureCanvasCairo
|
| 4 |
+
from .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3):
|
| 8 |
+
def on_draw_event(self, widget, ctx):
|
| 9 |
+
if self._idle_draw_id:
|
| 10 |
+
GLib.source_remove(self._idle_draw_id)
|
| 11 |
+
self._idle_draw_id = 0
|
| 12 |
+
self.draw()
|
| 13 |
+
|
| 14 |
+
with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
|
| 15 |
+
else nullcontext()):
|
| 16 |
+
allocation = self.get_allocation()
|
| 17 |
+
# Render the background before scaling, as the allocated size here is in
|
| 18 |
+
# logical pixels.
|
| 19 |
+
Gtk.render_background(
|
| 20 |
+
self.get_style_context(), ctx,
|
| 21 |
+
0, 0, allocation.width, allocation.height)
|
| 22 |
+
scale = self.device_pixel_ratio
|
| 23 |
+
# Scale physical drawing to logical size.
|
| 24 |
+
ctx.scale(1 / scale, 1 / scale)
|
| 25 |
+
self._renderer.set_context(ctx)
|
| 26 |
+
# Set renderer to physical size so it renders in full resolution.
|
| 27 |
+
self._renderer.width = allocation.width * scale
|
| 28 |
+
self._renderer.height = allocation.height * scale
|
| 29 |
+
self._renderer.dpi = self.figure.dpi
|
| 30 |
+
self.figure.draw(self._renderer)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@_BackendGTK3.export
|
| 34 |
+
class _BackendGTK3Cairo(_BackendGTK3):
|
| 35 |
+
FigureCanvas = FigureCanvas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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import matplotlib as mpl
|
| 6 |
+
from matplotlib import _api, backend_tools, cbook
|
| 7 |
+
from matplotlib.backend_bases import (
|
| 8 |
+
ToolContainerBase, MouseButton,
|
| 9 |
+
KeyEvent, LocationEvent, MouseEvent, ResizeEvent, CloseEvent)
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from gi import require_version as gi_require_version
|
| 13 |
+
except ImportError as err:
|
| 14 |
+
raise ImportError("The GTK4 backends require PyGObject") from err
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# :raises ValueError: If module/version is already loaded, already
|
| 18 |
+
# required, or unavailable.
|
| 19 |
+
gi_require_version("Gtk", "4.0")
|
| 20 |
+
except ValueError as e:
|
| 21 |
+
# in this case we want to re-raise as ImportError so the
|
| 22 |
+
# auto-backend selection logic correctly skips.
|
| 23 |
+
raise ImportError(e) from e
|
| 24 |
+
|
| 25 |
+
import gi
|
| 26 |
+
from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf
|
| 27 |
+
from . import _backend_gtk
|
| 28 |
+
from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
|
| 29 |
+
_BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
|
| 30 |
+
TimerGTK as TimerGTK4,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
_GOBJECT_GE_3_47 = gi.version_info >= (3, 47, 0)
|
| 34 |
+
_GTK_GE_4_12 = Gtk.check_version(4, 12, 0) is None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea):
|
| 38 |
+
required_interactive_framework = "gtk4"
|
| 39 |
+
supports_blit = False
|
| 40 |
+
manager_class = _api.classproperty(lambda cls: FigureManagerGTK4)
|
| 41 |
+
|
| 42 |
+
def __init__(self, figure=None):
|
| 43 |
+
super().__init__(figure=figure)
|
| 44 |
+
|
| 45 |
+
self.set_hexpand(True)
|
| 46 |
+
self.set_vexpand(True)
|
| 47 |
+
|
| 48 |
+
self._idle_draw_id = 0
|
| 49 |
+
self._rubberband_rect = None
|
| 50 |
+
|
| 51 |
+
self.set_draw_func(self._draw_func)
|
| 52 |
+
self.connect('resize', self.resize_event)
|
| 53 |
+
if _GTK_GE_4_12:
|
| 54 |
+
self.connect('realize', self._realize_event)
|
| 55 |
+
else:
|
| 56 |
+
self.connect('notify::scale-factor', self._update_device_pixel_ratio)
|
| 57 |
+
|
| 58 |
+
click = Gtk.GestureClick()
|
| 59 |
+
click.set_button(0) # All buttons.
|
| 60 |
+
click.connect('pressed', self.button_press_event)
|
| 61 |
+
click.connect('released', self.button_release_event)
|
| 62 |
+
self.add_controller(click)
|
| 63 |
+
|
| 64 |
+
key = Gtk.EventControllerKey()
|
| 65 |
+
key.connect('key-pressed', self.key_press_event)
|
| 66 |
+
key.connect('key-released', self.key_release_event)
|
| 67 |
+
self.add_controller(key)
|
| 68 |
+
|
| 69 |
+
motion = Gtk.EventControllerMotion()
|
| 70 |
+
motion.connect('motion', self.motion_notify_event)
|
| 71 |
+
motion.connect('enter', self.enter_notify_event)
|
| 72 |
+
motion.connect('leave', self.leave_notify_event)
|
| 73 |
+
self.add_controller(motion)
|
| 74 |
+
|
| 75 |
+
scroll = Gtk.EventControllerScroll.new(
|
| 76 |
+
Gtk.EventControllerScrollFlags.VERTICAL)
|
| 77 |
+
scroll.connect('scroll', self.scroll_event)
|
| 78 |
+
self.add_controller(scroll)
|
| 79 |
+
|
| 80 |
+
self.set_focusable(True)
|
| 81 |
+
|
| 82 |
+
css = Gtk.CssProvider()
|
| 83 |
+
style = '.matplotlib-canvas { background-color: white; }'
|
| 84 |
+
if Gtk.check_version(4, 9, 3) is None:
|
| 85 |
+
css.load_from_data(style, -1)
|
| 86 |
+
else:
|
| 87 |
+
css.load_from_data(style.encode('utf-8'))
|
| 88 |
+
style_ctx = self.get_style_context()
|
| 89 |
+
style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
|
| 90 |
+
style_ctx.add_class("matplotlib-canvas")
|
| 91 |
+
|
| 92 |
+
def destroy(self):
|
| 93 |
+
CloseEvent("close_event", self)._process()
|
| 94 |
+
|
| 95 |
+
def set_cursor(self, cursor):
|
| 96 |
+
# docstring inherited
|
| 97 |
+
self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor))
|
| 98 |
+
|
| 99 |
+
def _mpl_coords(self, xy=None):
|
| 100 |
+
"""
|
| 101 |
+
Convert the *xy* position of a GTK event, or of the current cursor
|
| 102 |
+
position if *xy* is None, to Matplotlib coordinates.
|
| 103 |
+
|
| 104 |
+
GTK use logical pixels, but the figure is scaled to physical pixels for
|
| 105 |
+
rendering. Transform to physical pixels so that all of the down-stream
|
| 106 |
+
transforms work as expected.
|
| 107 |
+
|
| 108 |
+
Also, the origin is different and needs to be corrected.
|
| 109 |
+
"""
|
| 110 |
+
if xy is None:
|
| 111 |
+
surface = self.get_native().get_surface()
|
| 112 |
+
is_over, x, y, mask = surface.get_device_position(
|
| 113 |
+
self.get_display().get_default_seat().get_pointer())
|
| 114 |
+
else:
|
| 115 |
+
x, y = xy
|
| 116 |
+
x = x * self.device_pixel_ratio
|
| 117 |
+
# flip y so y=0 is bottom of canvas
|
| 118 |
+
y = self.figure.bbox.height - y * self.device_pixel_ratio
|
| 119 |
+
return x, y
|
| 120 |
+
|
| 121 |
+
def scroll_event(self, controller, dx, dy):
|
| 122 |
+
MouseEvent(
|
| 123 |
+
"scroll_event", self, *self._mpl_coords(), step=dy,
|
| 124 |
+
modifiers=self._mpl_modifiers(controller),
|
| 125 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 126 |
+
)._process()
|
| 127 |
+
return True
|
| 128 |
+
|
| 129 |
+
def button_press_event(self, controller, n_press, x, y):
|
| 130 |
+
MouseEvent(
|
| 131 |
+
"button_press_event", self, *self._mpl_coords((x, y)),
|
| 132 |
+
controller.get_current_button(),
|
| 133 |
+
modifiers=self._mpl_modifiers(controller),
|
| 134 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 135 |
+
)._process()
|
| 136 |
+
self.grab_focus()
|
| 137 |
+
|
| 138 |
+
def button_release_event(self, controller, n_press, x, y):
|
| 139 |
+
MouseEvent(
|
| 140 |
+
"button_release_event", self, *self._mpl_coords((x, y)),
|
| 141 |
+
controller.get_current_button(),
|
| 142 |
+
modifiers=self._mpl_modifiers(controller),
|
| 143 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 144 |
+
)._process()
|
| 145 |
+
|
| 146 |
+
def key_press_event(self, controller, keyval, keycode, state):
|
| 147 |
+
KeyEvent(
|
| 148 |
+
"key_press_event", self, self._get_key(keyval, keycode, state),
|
| 149 |
+
*self._mpl_coords(),
|
| 150 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 151 |
+
)._process()
|
| 152 |
+
return True
|
| 153 |
+
|
| 154 |
+
def key_release_event(self, controller, keyval, keycode, state):
|
| 155 |
+
KeyEvent(
|
| 156 |
+
"key_release_event", self, self._get_key(keyval, keycode, state),
|
| 157 |
+
*self._mpl_coords(),
|
| 158 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 159 |
+
)._process()
|
| 160 |
+
return True
|
| 161 |
+
|
| 162 |
+
def motion_notify_event(self, controller, x, y):
|
| 163 |
+
MouseEvent(
|
| 164 |
+
"motion_notify_event", self, *self._mpl_coords((x, y)),
|
| 165 |
+
buttons=self._mpl_buttons(controller),
|
| 166 |
+
modifiers=self._mpl_modifiers(controller),
|
| 167 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 168 |
+
)._process()
|
| 169 |
+
|
| 170 |
+
def enter_notify_event(self, controller, x, y):
|
| 171 |
+
LocationEvent(
|
| 172 |
+
"figure_enter_event", self, *self._mpl_coords((x, y)),
|
| 173 |
+
modifiers=self._mpl_modifiers(),
|
| 174 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 175 |
+
)._process()
|
| 176 |
+
|
| 177 |
+
def leave_notify_event(self, controller):
|
| 178 |
+
LocationEvent(
|
| 179 |
+
"figure_leave_event", self, *self._mpl_coords(),
|
| 180 |
+
modifiers=self._mpl_modifiers(),
|
| 181 |
+
guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
|
| 182 |
+
)._process()
|
| 183 |
+
|
| 184 |
+
def resize_event(self, area, width, height):
|
| 185 |
+
self._update_device_pixel_ratio()
|
| 186 |
+
dpi = self.figure.dpi
|
| 187 |
+
winch = width * self.device_pixel_ratio / dpi
|
| 188 |
+
hinch = height * self.device_pixel_ratio / dpi
|
| 189 |
+
self.figure.set_size_inches(winch, hinch, forward=False)
|
| 190 |
+
ResizeEvent("resize_event", self)._process()
|
| 191 |
+
self.draw_idle()
|
| 192 |
+
|
| 193 |
+
def _mpl_buttons(self, controller):
|
| 194 |
+
# NOTE: This spews "Broken accounting of active state" warnings on
|
| 195 |
+
# right click on macOS.
|
| 196 |
+
surface = self.get_native().get_surface()
|
| 197 |
+
is_over, x, y, event_state = surface.get_device_position(
|
| 198 |
+
self.get_display().get_default_seat().get_pointer())
|
| 199 |
+
# NOTE: alternatively we could use
|
| 200 |
+
# event_state = controller.get_current_event_state()
|
| 201 |
+
# but for button_press/button_release this would report the state
|
| 202 |
+
# *prior* to the event rather than after it; the above reports the
|
| 203 |
+
# state *after* it.
|
| 204 |
+
mod_table = [
|
| 205 |
+
(MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),
|
| 206 |
+
(MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),
|
| 207 |
+
(MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),
|
| 208 |
+
(MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),
|
| 209 |
+
(MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),
|
| 210 |
+
]
|
| 211 |
+
return {name for name, mask in mod_table if event_state & mask}
|
| 212 |
+
|
| 213 |
+
def _mpl_modifiers(self, controller=None):
|
| 214 |
+
if controller is None:
|
| 215 |
+
surface = self.get_native().get_surface()
|
| 216 |
+
is_over, x, y, event_state = surface.get_device_position(
|
| 217 |
+
self.get_display().get_default_seat().get_pointer())
|
| 218 |
+
else:
|
| 219 |
+
event_state = controller.get_current_event_state()
|
| 220 |
+
mod_table = [
|
| 221 |
+
("ctrl", Gdk.ModifierType.CONTROL_MASK),
|
| 222 |
+
("alt", Gdk.ModifierType.ALT_MASK),
|
| 223 |
+
("shift", Gdk.ModifierType.SHIFT_MASK),
|
| 224 |
+
("super", Gdk.ModifierType.SUPER_MASK),
|
| 225 |
+
]
|
| 226 |
+
return [name for name, mask in mod_table if event_state & mask]
|
| 227 |
+
|
| 228 |
+
def _get_key(self, keyval, keycode, state):
|
| 229 |
+
unikey = chr(Gdk.keyval_to_unicode(keyval))
|
| 230 |
+
key = cbook._unikey_or_keysym_to_mplkey(
|
| 231 |
+
unikey,
|
| 232 |
+
Gdk.keyval_name(keyval))
|
| 233 |
+
modifiers = [
|
| 234 |
+
("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
|
| 235 |
+
("alt", Gdk.ModifierType.ALT_MASK, "alt"),
|
| 236 |
+
("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
|
| 237 |
+
("super", Gdk.ModifierType.SUPER_MASK, "super"),
|
| 238 |
+
]
|
| 239 |
+
mods = [
|
| 240 |
+
mod for mod, mask, mod_key in modifiers
|
| 241 |
+
if (mod_key != key and state & mask
|
| 242 |
+
and not (mod == "shift" and unikey.isprintable()))]
|
| 243 |
+
return "+".join([*mods, key])
|
| 244 |
+
|
| 245 |
+
def _realize_event(self, obj):
|
| 246 |
+
surface = self.get_native().get_surface()
|
| 247 |
+
surface.connect('notify::scale', self._update_device_pixel_ratio)
|
| 248 |
+
self._update_device_pixel_ratio()
|
| 249 |
+
|
| 250 |
+
def _update_device_pixel_ratio(self, *args, **kwargs):
|
| 251 |
+
# We need to be careful in cases with mixed resolution displays if
|
| 252 |
+
# device_pixel_ratio changes.
|
| 253 |
+
if _GTK_GE_4_12:
|
| 254 |
+
scale = self.get_native().get_surface().get_scale()
|
| 255 |
+
else:
|
| 256 |
+
scale = self.get_scale_factor()
|
| 257 |
+
assert scale is not None
|
| 258 |
+
if self._set_device_pixel_ratio(scale):
|
| 259 |
+
self.draw()
|
| 260 |
+
|
| 261 |
+
def _draw_rubberband(self, rect):
|
| 262 |
+
self._rubberband_rect = rect
|
| 263 |
+
# TODO: Only update the rubberband area.
|
| 264 |
+
self.queue_draw()
|
| 265 |
+
|
| 266 |
+
def _draw_func(self, drawing_area, ctx, width, height):
|
| 267 |
+
self.on_draw_event(self, ctx)
|
| 268 |
+
self._post_draw(self, ctx)
|
| 269 |
+
|
| 270 |
+
def _post_draw(self, widget, ctx):
|
| 271 |
+
if self._rubberband_rect is None:
|
| 272 |
+
return
|
| 273 |
+
|
| 274 |
+
lw = 1
|
| 275 |
+
dash = 3
|
| 276 |
+
x0, y0, w, h = (dim / self.device_pixel_ratio
|
| 277 |
+
for dim in self._rubberband_rect)
|
| 278 |
+
x1 = x0 + w
|
| 279 |
+
y1 = y0 + h
|
| 280 |
+
|
| 281 |
+
# Draw the lines from x0, y0 towards x1, y1 so that the
|
| 282 |
+
# dashes don't "jump" when moving the zoom box.
|
| 283 |
+
ctx.move_to(x0, y0)
|
| 284 |
+
ctx.line_to(x0, y1)
|
| 285 |
+
ctx.move_to(x0, y0)
|
| 286 |
+
ctx.line_to(x1, y0)
|
| 287 |
+
ctx.move_to(x0, y1)
|
| 288 |
+
ctx.line_to(x1, y1)
|
| 289 |
+
ctx.move_to(x1, y0)
|
| 290 |
+
ctx.line_to(x1, y1)
|
| 291 |
+
|
| 292 |
+
ctx.set_antialias(1)
|
| 293 |
+
ctx.set_line_width(lw)
|
| 294 |
+
ctx.set_dash((dash, dash), 0)
|
| 295 |
+
ctx.set_source_rgb(0, 0, 0)
|
| 296 |
+
ctx.stroke_preserve()
|
| 297 |
+
|
| 298 |
+
ctx.set_dash((dash, dash), dash)
|
| 299 |
+
ctx.set_source_rgb(1, 1, 1)
|
| 300 |
+
ctx.stroke()
|
| 301 |
+
|
| 302 |
+
def on_draw_event(self, widget, ctx):
|
| 303 |
+
# to be overwritten by GTK4Agg or GTK4Cairo
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
def draw(self):
|
| 307 |
+
# docstring inherited
|
| 308 |
+
if self.is_drawable():
|
| 309 |
+
self.queue_draw()
|
| 310 |
+
|
| 311 |
+
def draw_idle(self):
|
| 312 |
+
# docstring inherited
|
| 313 |
+
if self._idle_draw_id != 0:
|
| 314 |
+
return
|
| 315 |
+
def idle_draw(*args):
|
| 316 |
+
try:
|
| 317 |
+
self.draw()
|
| 318 |
+
finally:
|
| 319 |
+
self._idle_draw_id = 0
|
| 320 |
+
return False
|
| 321 |
+
self._idle_draw_id = GLib.idle_add(idle_draw)
|
| 322 |
+
|
| 323 |
+
def flush_events(self):
|
| 324 |
+
# docstring inherited
|
| 325 |
+
context = GLib.MainContext.default()
|
| 326 |
+
while context.pending():
|
| 327 |
+
context.iteration(True)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box):
|
| 331 |
+
def __init__(self, canvas):
|
| 332 |
+
Gtk.Box.__init__(self)
|
| 333 |
+
|
| 334 |
+
self.add_css_class('toolbar')
|
| 335 |
+
|
| 336 |
+
self._gtk_ids = {}
|
| 337 |
+
for text, tooltip_text, image_file, callback in self.toolitems:
|
| 338 |
+
if text is None:
|
| 339 |
+
self.append(Gtk.Separator())
|
| 340 |
+
continue
|
| 341 |
+
image = Gtk.Image.new_from_gicon(
|
| 342 |
+
Gio.Icon.new_for_string(
|
| 343 |
+
str(cbook._get_data_path('images',
|
| 344 |
+
f'{image_file}-symbolic.svg'))))
|
| 345 |
+
self._gtk_ids[text] = button = (
|
| 346 |
+
Gtk.ToggleButton() if callback in ['zoom', 'pan'] else
|
| 347 |
+
Gtk.Button())
|
| 348 |
+
button.set_child(image)
|
| 349 |
+
button.add_css_class('flat')
|
| 350 |
+
button.add_css_class('image-button')
|
| 351 |
+
# Save the handler id, so that we can block it as needed.
|
| 352 |
+
button._signal_handler = button.connect(
|
| 353 |
+
'clicked', getattr(self, callback))
|
| 354 |
+
button.set_tooltip_text(tooltip_text)
|
| 355 |
+
self.append(button)
|
| 356 |
+
|
| 357 |
+
# This filler item ensures the toolbar is always at least two text
|
| 358 |
+
# lines high. Otherwise the canvas gets redrawn as the mouse hovers
|
| 359 |
+
# over images because those use two-line messages which resize the
|
| 360 |
+
# toolbar.
|
| 361 |
+
label = Gtk.Label()
|
| 362 |
+
label.set_markup(
|
| 363 |
+
'<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
|
| 364 |
+
label.set_hexpand(True) # Push real message to the right.
|
| 365 |
+
self.append(label)
|
| 366 |
+
|
| 367 |
+
self.message = Gtk.Label()
|
| 368 |
+
self.message.set_justify(Gtk.Justification.RIGHT)
|
| 369 |
+
self.append(self.message)
|
| 370 |
+
|
| 371 |
+
_NavigationToolbar2GTK.__init__(self, canvas)
|
| 372 |
+
|
| 373 |
+
def save_figure(self, *args):
|
| 374 |
+
dialog = Gtk.FileChooserNative(
|
| 375 |
+
title='Save the figure',
|
| 376 |
+
transient_for=self.canvas.get_root(),
|
| 377 |
+
action=Gtk.FileChooserAction.SAVE,
|
| 378 |
+
modal=True)
|
| 379 |
+
self._save_dialog = dialog # Must keep a reference.
|
| 380 |
+
|
| 381 |
+
ff = Gtk.FileFilter()
|
| 382 |
+
ff.set_name('All files')
|
| 383 |
+
ff.add_pattern('*')
|
| 384 |
+
dialog.add_filter(ff)
|
| 385 |
+
dialog.set_filter(ff)
|
| 386 |
+
|
| 387 |
+
formats = []
|
| 388 |
+
default_format = None
|
| 389 |
+
for i, (name, fmts) in enumerate(
|
| 390 |
+
self.canvas.get_supported_filetypes_grouped().items()):
|
| 391 |
+
ff = Gtk.FileFilter()
|
| 392 |
+
ff.set_name(name)
|
| 393 |
+
for fmt in fmts:
|
| 394 |
+
ff.add_pattern(f'*.{fmt}')
|
| 395 |
+
dialog.add_filter(ff)
|
| 396 |
+
formats.append(name)
|
| 397 |
+
if self.canvas.get_default_filetype() in fmts:
|
| 398 |
+
default_format = i
|
| 399 |
+
# Setting the choice doesn't always work, so make sure the default
|
| 400 |
+
# format is first.
|
| 401 |
+
formats = [formats[default_format], *formats[:default_format],
|
| 402 |
+
*formats[default_format+1:]]
|
| 403 |
+
dialog.add_choice('format', 'File format', formats, formats)
|
| 404 |
+
dialog.set_choice('format', formats[0])
|
| 405 |
+
|
| 406 |
+
dialog.set_current_folder(Gio.File.new_for_path(
|
| 407 |
+
os.path.expanduser(mpl.rcParams['savefig.directory'])))
|
| 408 |
+
dialog.set_current_name(self.canvas.get_default_filename())
|
| 409 |
+
|
| 410 |
+
@functools.partial(dialog.connect, 'response')
|
| 411 |
+
def on_response(dialog, response):
|
| 412 |
+
file = dialog.get_file()
|
| 413 |
+
fmt = dialog.get_choice('format')
|
| 414 |
+
fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0]
|
| 415 |
+
dialog.destroy()
|
| 416 |
+
self._save_dialog = None
|
| 417 |
+
if response != Gtk.ResponseType.ACCEPT:
|
| 418 |
+
return
|
| 419 |
+
# Save dir for next time, unless empty str (which means use cwd).
|
| 420 |
+
if mpl.rcParams['savefig.directory']:
|
| 421 |
+
parent = file.get_parent()
|
| 422 |
+
mpl.rcParams['savefig.directory'] = parent.get_path()
|
| 423 |
+
try:
|
| 424 |
+
self.canvas.figure.savefig(file.get_path(), format=fmt)
|
| 425 |
+
except Exception as e:
|
| 426 |
+
msg = Gtk.MessageDialog(
|
| 427 |
+
transient_for=self.canvas.get_root(),
|
| 428 |
+
message_type=Gtk.MessageType.ERROR,
|
| 429 |
+
buttons=Gtk.ButtonsType.OK, modal=True,
|
| 430 |
+
text=str(e))
|
| 431 |
+
msg.show()
|
| 432 |
+
|
| 433 |
+
dialog.show()
|
| 434 |
+
return self.UNKNOWN_SAVED_STATUS
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class ToolbarGTK4(ToolContainerBase, Gtk.Box):
|
| 438 |
+
_icon_extension = '-symbolic.svg'
|
| 439 |
+
|
| 440 |
+
def __init__(self, toolmanager):
|
| 441 |
+
ToolContainerBase.__init__(self, toolmanager)
|
| 442 |
+
Gtk.Box.__init__(self)
|
| 443 |
+
self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
|
| 444 |
+
|
| 445 |
+
# Tool items are created later, but must appear before the message.
|
| 446 |
+
self._tool_box = Gtk.Box()
|
| 447 |
+
self.append(self._tool_box)
|
| 448 |
+
self._groups = {}
|
| 449 |
+
self._toolitems = {}
|
| 450 |
+
|
| 451 |
+
# This filler item ensures the toolbar is always at least two text
|
| 452 |
+
# lines high. Otherwise the canvas gets redrawn as the mouse hovers
|
| 453 |
+
# over images because those use two-line messages which resize the
|
| 454 |
+
# toolbar.
|
| 455 |
+
label = Gtk.Label()
|
| 456 |
+
label.set_markup(
|
| 457 |
+
'<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
|
| 458 |
+
label.set_hexpand(True) # Push real message to the right.
|
| 459 |
+
self.append(label)
|
| 460 |
+
|
| 461 |
+
self._message = Gtk.Label()
|
| 462 |
+
self._message.set_justify(Gtk.Justification.RIGHT)
|
| 463 |
+
self.append(self._message)
|
| 464 |
+
|
| 465 |
+
def add_toolitem(self, name, group, position, image_file, description,
|
| 466 |
+
toggle):
|
| 467 |
+
if toggle:
|
| 468 |
+
button = Gtk.ToggleButton()
|
| 469 |
+
else:
|
| 470 |
+
button = Gtk.Button()
|
| 471 |
+
button.set_label(name)
|
| 472 |
+
button.add_css_class('flat')
|
| 473 |
+
|
| 474 |
+
if image_file is not None:
|
| 475 |
+
image = Gtk.Image.new_from_gicon(
|
| 476 |
+
Gio.Icon.new_for_string(image_file))
|
| 477 |
+
button.set_child(image)
|
| 478 |
+
button.add_css_class('image-button')
|
| 479 |
+
|
| 480 |
+
if position is None:
|
| 481 |
+
position = -1
|
| 482 |
+
|
| 483 |
+
self._add_button(button, group, position)
|
| 484 |
+
signal = button.connect('clicked', self._call_tool, name)
|
| 485 |
+
button.set_tooltip_text(description)
|
| 486 |
+
self._toolitems.setdefault(name, [])
|
| 487 |
+
self._toolitems[name].append((button, signal))
|
| 488 |
+
|
| 489 |
+
def _find_child_at_position(self, group, position):
|
| 490 |
+
children = [None]
|
| 491 |
+
child = self._groups[group].get_first_child()
|
| 492 |
+
while child is not None:
|
| 493 |
+
children.append(child)
|
| 494 |
+
child = child.get_next_sibling()
|
| 495 |
+
return children[position]
|
| 496 |
+
|
| 497 |
+
def _add_button(self, button, group, position):
|
| 498 |
+
if group not in self._groups:
|
| 499 |
+
if self._groups:
|
| 500 |
+
self._add_separator()
|
| 501 |
+
group_box = Gtk.Box()
|
| 502 |
+
self._tool_box.append(group_box)
|
| 503 |
+
self._groups[group] = group_box
|
| 504 |
+
self._groups[group].insert_child_after(
|
| 505 |
+
button, self._find_child_at_position(group, position))
|
| 506 |
+
|
| 507 |
+
def _call_tool(self, btn, name):
|
| 508 |
+
self.trigger_tool(name)
|
| 509 |
+
|
| 510 |
+
def toggle_toolitem(self, name, toggled):
|
| 511 |
+
if name not in self._toolitems:
|
| 512 |
+
return
|
| 513 |
+
for toolitem, signal in self._toolitems[name]:
|
| 514 |
+
toolitem.handler_block(signal)
|
| 515 |
+
toolitem.set_active(toggled)
|
| 516 |
+
toolitem.handler_unblock(signal)
|
| 517 |
+
|
| 518 |
+
def remove_toolitem(self, name):
|
| 519 |
+
for toolitem, _signal in self._toolitems.pop(name, []):
|
| 520 |
+
for group in self._groups:
|
| 521 |
+
if toolitem in self._groups[group]:
|
| 522 |
+
self._groups[group].remove(toolitem)
|
| 523 |
+
|
| 524 |
+
def _add_separator(self):
|
| 525 |
+
sep = Gtk.Separator()
|
| 526 |
+
sep.set_property("orientation", Gtk.Orientation.VERTICAL)
|
| 527 |
+
self._tool_box.append(sep)
|
| 528 |
+
|
| 529 |
+
def set_message(self, s):
|
| 530 |
+
self._message.set_label(s)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@backend_tools._register_tool_class(FigureCanvasGTK4)
|
| 534 |
+
class SaveFigureGTK4(backend_tools.SaveFigureBase):
|
| 535 |
+
def trigger(self, *args, **kwargs):
|
| 536 |
+
NavigationToolbar2GTK4.save_figure(
|
| 537 |
+
self._make_classic_style_pseudo_toolbar())
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@backend_tools._register_tool_class(FigureCanvasGTK4)
|
| 541 |
+
class HelpGTK4(backend_tools.ToolHelpBase):
|
| 542 |
+
def _normalize_shortcut(self, key):
|
| 543 |
+
"""
|
| 544 |
+
Convert Matplotlib key presses to GTK+ accelerator identifiers.
|
| 545 |
+
|
| 546 |
+
Related to `FigureCanvasGTK4._get_key`.
|
| 547 |
+
"""
|
| 548 |
+
special = {
|
| 549 |
+
'backspace': 'BackSpace',
|
| 550 |
+
'pagedown': 'Page_Down',
|
| 551 |
+
'pageup': 'Page_Up',
|
| 552 |
+
'scroll_lock': 'Scroll_Lock',
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
parts = key.split('+')
|
| 556 |
+
mods = ['<' + mod + '>' for mod in parts[:-1]]
|
| 557 |
+
key = parts[-1]
|
| 558 |
+
|
| 559 |
+
if key in special:
|
| 560 |
+
key = special[key]
|
| 561 |
+
elif len(key) > 1:
|
| 562 |
+
key = key.capitalize()
|
| 563 |
+
elif key.isupper():
|
| 564 |
+
mods += ['<shift>']
|
| 565 |
+
|
| 566 |
+
return ''.join(mods) + key
|
| 567 |
+
|
| 568 |
+
def _is_valid_shortcut(self, key):
|
| 569 |
+
"""
|
| 570 |
+
Check for a valid shortcut to be displayed.
|
| 571 |
+
|
| 572 |
+
- GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`).
|
| 573 |
+
- The shortcut window only shows keyboard shortcuts, not mouse buttons.
|
| 574 |
+
"""
|
| 575 |
+
return 'cmd+' not in key and not key.startswith('MouseButton.')
|
| 576 |
+
|
| 577 |
+
def trigger(self, *args):
|
| 578 |
+
section = Gtk.ShortcutsSection()
|
| 579 |
+
|
| 580 |
+
for name, tool in sorted(self.toolmanager.tools.items()):
|
| 581 |
+
if not tool.description:
|
| 582 |
+
continue
|
| 583 |
+
|
| 584 |
+
# Putting everything in a separate group allows GTK to
|
| 585 |
+
# automatically split them into separate columns/pages, which is
|
| 586 |
+
# useful because we have lots of shortcuts, some with many keys
|
| 587 |
+
# that are very wide.
|
| 588 |
+
group = Gtk.ShortcutsGroup()
|
| 589 |
+
section.append(group)
|
| 590 |
+
# A hack to remove the title since we have no group naming.
|
| 591 |
+
child = group.get_first_child()
|
| 592 |
+
while child is not None:
|
| 593 |
+
child.set_visible(False)
|
| 594 |
+
child = child.get_next_sibling()
|
| 595 |
+
|
| 596 |
+
shortcut = Gtk.ShortcutsShortcut(
|
| 597 |
+
accelerator=' '.join(
|
| 598 |
+
self._normalize_shortcut(key)
|
| 599 |
+
for key in self.toolmanager.get_tool_keymap(name)
|
| 600 |
+
if self._is_valid_shortcut(key)),
|
| 601 |
+
title=tool.name,
|
| 602 |
+
subtitle=tool.description)
|
| 603 |
+
group.append(shortcut)
|
| 604 |
+
|
| 605 |
+
window = Gtk.ShortcutsWindow(
|
| 606 |
+
title='Help',
|
| 607 |
+
modal=True,
|
| 608 |
+
transient_for=self._figure.canvas.get_root())
|
| 609 |
+
window.set_child(section)
|
| 610 |
+
|
| 611 |
+
window.show()
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
@backend_tools._register_tool_class(FigureCanvasGTK4)
|
| 615 |
+
class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase):
|
| 616 |
+
def trigger(self, *args, **kwargs):
|
| 617 |
+
with io.BytesIO() as f:
|
| 618 |
+
self.canvas.print_rgba(f)
|
| 619 |
+
w, h = self.canvas.get_width_height()
|
| 620 |
+
pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),
|
| 621 |
+
GdkPixbuf.Colorspace.RGB, True,
|
| 622 |
+
8, w, h, w*4)
|
| 623 |
+
clipboard = self.canvas.get_clipboard()
|
| 624 |
+
clipboard.set(pb)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
backend_tools._register_tool_class(
|
| 628 |
+
FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK)
|
| 629 |
+
backend_tools._register_tool_class(
|
| 630 |
+
FigureCanvasGTK4, _backend_gtk.RubberbandGTK)
|
| 631 |
+
Toolbar = ToolbarGTK4
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class FigureManagerGTK4(_FigureManagerGTK):
|
| 635 |
+
_toolbar2_class = NavigationToolbar2GTK4
|
| 636 |
+
_toolmanager_toolbar_class = ToolbarGTK4
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
@_BackendGTK.export
|
| 640 |
+
class _BackendGTK4(_BackendGTK):
|
| 641 |
+
FigureCanvas = FigureCanvasGTK4
|
| 642 |
+
FigureManager = FigureManagerGTK4
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4agg.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from .. import cbook
|
| 4 |
+
from . import backend_agg, backend_gtk4
|
| 5 |
+
from .backend_gtk4 import GLib, Gtk, _BackendGTK4
|
| 6 |
+
|
| 7 |
+
import cairo # Presence of cairo is already checked by _backend_gtk.
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class FigureCanvasGTK4Agg(backend_agg.FigureCanvasAgg,
|
| 11 |
+
backend_gtk4.FigureCanvasGTK4):
|
| 12 |
+
|
| 13 |
+
def on_draw_event(self, widget, ctx):
|
| 14 |
+
if self._idle_draw_id:
|
| 15 |
+
GLib.source_remove(self._idle_draw_id)
|
| 16 |
+
self._idle_draw_id = 0
|
| 17 |
+
self.draw()
|
| 18 |
+
|
| 19 |
+
scale = self.device_pixel_ratio
|
| 20 |
+
allocation = self.get_allocation()
|
| 21 |
+
|
| 22 |
+
Gtk.render_background(
|
| 23 |
+
self.get_style_context(), ctx,
|
| 24 |
+
allocation.x, allocation.y,
|
| 25 |
+
allocation.width, allocation.height)
|
| 26 |
+
|
| 27 |
+
buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(
|
| 28 |
+
np.asarray(self.get_renderer().buffer_rgba()))
|
| 29 |
+
height, width, _ = buf.shape
|
| 30 |
+
image = cairo.ImageSurface.create_for_data(
|
| 31 |
+
buf.ravel().data, cairo.FORMAT_ARGB32, width, height)
|
| 32 |
+
image.set_device_scale(scale, scale)
|
| 33 |
+
ctx.set_source_surface(image, 0, 0)
|
| 34 |
+
ctx.paint()
|
| 35 |
+
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@_BackendGTK4.export
|
| 40 |
+
class _BackendGTK4Agg(_BackendGTK4):
|
| 41 |
+
FigureCanvas = FigureCanvasGTK4Agg
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4cairo.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import nullcontext
|
| 2 |
+
|
| 3 |
+
from .backend_cairo import FigureCanvasCairo
|
| 4 |
+
from .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4):
|
| 8 |
+
def _set_device_pixel_ratio(self, ratio):
|
| 9 |
+
# Cairo in GTK4 always uses logical pixels, so we don't need to do anything for
|
| 10 |
+
# changes to the device pixel ratio.
|
| 11 |
+
return False
|
| 12 |
+
|
| 13 |
+
def on_draw_event(self, widget, ctx):
|
| 14 |
+
if self._idle_draw_id:
|
| 15 |
+
GLib.source_remove(self._idle_draw_id)
|
| 16 |
+
self._idle_draw_id = 0
|
| 17 |
+
self.draw()
|
| 18 |
+
|
| 19 |
+
with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
|
| 20 |
+
else nullcontext()):
|
| 21 |
+
self._renderer.set_context(ctx)
|
| 22 |
+
allocation = self.get_allocation()
|
| 23 |
+
Gtk.render_background(
|
| 24 |
+
self.get_style_context(), ctx,
|
| 25 |
+
allocation.x, allocation.y,
|
| 26 |
+
allocation.width, allocation.height)
|
| 27 |
+
self.figure.draw(self._renderer)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@_BackendGTK4.export
|
| 31 |
+
class _BackendGTK4Cairo(_BackendGTK4):
|
| 32 |
+
FigureCanvas = FigureCanvasGTK4Cairo
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_macosx.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ib import _api, cbook
|
| 5 |
+
from matplotlib._pylab_helpers import Gcf
|
| 6 |
+
from . import _macosx
|
| 7 |
+
from .backend_agg import FigureCanvasAgg
|
| 8 |
+
from matplotlib.backend_bases import (
|
| 9 |
+
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
|
| 10 |
+
ResizeEvent, TimerBase, _allow_interrupt)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TimerMac(_macosx.Timer, TimerBase):
|
| 14 |
+
"""Subclass of `.TimerBase` using CFRunLoop timer events."""
|
| 15 |
+
# completely implemented at the C-level (in _macosx.Timer)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _allow_interrupt_macos():
|
| 19 |
+
"""A context manager that allows terminating a plot by sending a SIGINT."""
|
| 20 |
+
return _allow_interrupt(
|
| 21 |
+
lambda rsock: _macosx.wake_on_fd_write(rsock.fileno()), _macosx.stop)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class FigureCanvasMac(FigureCanvasAgg, _macosx.FigureCanvas, FigureCanvasBase):
|
| 25 |
+
# docstring inherited
|
| 26 |
+
|
| 27 |
+
# Ideally this class would be `class FCMacAgg(FCAgg, FCMac)`
|
| 28 |
+
# (FC=FigureCanvas) where FCMac would be an ObjC-implemented mac-specific
|
| 29 |
+
# class also inheriting from FCBase (this is the approach with other GUI
|
| 30 |
+
# toolkits). However, writing an extension type inheriting from a Python
|
| 31 |
+
# base class is slightly tricky (the extension type must be a heap type),
|
| 32 |
+
# and we can just as well lift the FCBase base up one level, keeping it *at
|
| 33 |
+
# the end* to have the right method resolution order.
|
| 34 |
+
|
| 35 |
+
# Events such as button presses, mouse movements, and key presses are
|
| 36 |
+
# handled in C and events (MouseEvent, etc.) are triggered from there.
|
| 37 |
+
|
| 38 |
+
required_interactive_framework = "macosx"
|
| 39 |
+
_timer_cls = TimerMac
|
| 40 |
+
manager_class = _api.classproperty(lambda cls: FigureManagerMac)
|
| 41 |
+
|
| 42 |
+
def __init__(self, figure):
|
| 43 |
+
super().__init__(figure=figure)
|
| 44 |
+
self._draw_pending = False
|
| 45 |
+
self._is_drawing = False
|
| 46 |
+
# Keep track of the timers that are alive
|
| 47 |
+
self._timers = set()
|
| 48 |
+
|
| 49 |
+
def draw(self):
|
| 50 |
+
"""Render the figure and update the macosx canvas."""
|
| 51 |
+
# The renderer draw is done here; delaying causes problems with code
|
| 52 |
+
# that uses the result of the draw() to update plot elements.
|
| 53 |
+
if self._is_drawing:
|
| 54 |
+
return
|
| 55 |
+
with cbook._setattr_cm(self, _is_drawing=True):
|
| 56 |
+
super().draw()
|
| 57 |
+
self.update()
|
| 58 |
+
|
| 59 |
+
def draw_idle(self):
|
| 60 |
+
# docstring inherited
|
| 61 |
+
if not (getattr(self, '_draw_pending', False) or
|
| 62 |
+
getattr(self, '_is_drawing', False)):
|
| 63 |
+
self._draw_pending = True
|
| 64 |
+
# Add a singleshot timer to the eventloop that will call back
|
| 65 |
+
# into the Python method _draw_idle to take care of the draw
|
| 66 |
+
self._single_shot_timer(self._draw_idle)
|
| 67 |
+
|
| 68 |
+
def _single_shot_timer(self, callback):
|
| 69 |
+
"""Add a single shot timer with the given callback"""
|
| 70 |
+
def callback_func(callback, timer):
|
| 71 |
+
callback()
|
| 72 |
+
self._timers.remove(timer)
|
| 73 |
+
timer = self.new_timer(interval=0)
|
| 74 |
+
timer.single_shot = True
|
| 75 |
+
timer.add_callback(callback_func, callback, timer)
|
| 76 |
+
self._timers.add(timer)
|
| 77 |
+
timer.start()
|
| 78 |
+
|
| 79 |
+
def _draw_idle(self):
|
| 80 |
+
"""
|
| 81 |
+
Draw method for singleshot timer
|
| 82 |
+
|
| 83 |
+
This draw method can be added to a singleshot timer, which can
|
| 84 |
+
accumulate draws while the eventloop is spinning. This method will
|
| 85 |
+
then only draw the first time and short-circuit the others.
|
| 86 |
+
"""
|
| 87 |
+
with self._idle_draw_cntx():
|
| 88 |
+
if not self._draw_pending:
|
| 89 |
+
# Short-circuit because our draw request has already been
|
| 90 |
+
# taken care of
|
| 91 |
+
return
|
| 92 |
+
self._draw_pending = False
|
| 93 |
+
self.draw()
|
| 94 |
+
|
| 95 |
+
def blit(self, bbox=None):
|
| 96 |
+
# docstring inherited
|
| 97 |
+
super().blit(bbox)
|
| 98 |
+
self.update()
|
| 99 |
+
|
| 100 |
+
def resize(self, width, height):
|
| 101 |
+
# Size from macOS is logical pixels, dpi is physical.
|
| 102 |
+
scale = self.figure.dpi / self.device_pixel_ratio
|
| 103 |
+
width /= scale
|
| 104 |
+
height /= scale
|
| 105 |
+
self.figure.set_size_inches(width, height, forward=False)
|
| 106 |
+
ResizeEvent("resize_event", self)._process()
|
| 107 |
+
self.draw_idle()
|
| 108 |
+
|
| 109 |
+
def start_event_loop(self, timeout=0):
|
| 110 |
+
# docstring inherited
|
| 111 |
+
# Set up a SIGINT handler to allow terminating a plot via CTRL-C.
|
| 112 |
+
with _allow_interrupt_macos():
|
| 113 |
+
self._start_event_loop(timeout=timeout) # Forward to ObjC implementation.
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2):
|
| 117 |
+
|
| 118 |
+
def __init__(self, canvas):
|
| 119 |
+
data_path = cbook._get_data_path('images')
|
| 120 |
+
_, tooltips, image_names, _ = zip(*NavigationToolbar2.toolitems)
|
| 121 |
+
_macosx.NavigationToolbar2.__init__(
|
| 122 |
+
self, canvas,
|
| 123 |
+
tuple(str(data_path / image_name) + ".pdf"
|
| 124 |
+
for image_name in image_names if image_name is not None),
|
| 125 |
+
tuple(tooltip for tooltip in tooltips if tooltip is not None))
|
| 126 |
+
NavigationToolbar2.__init__(self, canvas)
|
| 127 |
+
|
| 128 |
+
def draw_rubberband(self, event, x0, y0, x1, y1):
|
| 129 |
+
self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))
|
| 130 |
+
|
| 131 |
+
def remove_rubberband(self):
|
| 132 |
+
self.canvas.remove_rubberband()
|
| 133 |
+
|
| 134 |
+
def save_figure(self, *args):
|
| 135 |
+
directory = os.path.expanduser(mpl.rcParams['savefig.directory'])
|
| 136 |
+
filename = _macosx.choose_save_file('Save the figure',
|
| 137 |
+
directory,
|
| 138 |
+
self.canvas.get_default_filename())
|
| 139 |
+
if filename is None: # Cancel
|
| 140 |
+
return
|
| 141 |
+
# Save dir for next time, unless empty str (which means use cwd).
|
| 142 |
+
if mpl.rcParams['savefig.directory']:
|
| 143 |
+
mpl.rcParams['savefig.directory'] = os.path.dirname(filename)
|
| 144 |
+
self.canvas.figure.savefig(filename)
|
| 145 |
+
return filename
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class FigureManagerMac(_macosx.FigureManager, FigureManagerBase):
|
| 149 |
+
_toolbar2_class = NavigationToolbar2Mac
|
| 150 |
+
|
| 151 |
+
def __init__(self, canvas, num):
|
| 152 |
+
self._shown = False
|
| 153 |
+
_macosx.FigureManager.__init__(self, canvas)
|
| 154 |
+
icon_path = str(cbook._get_data_path('images/matplotlib.pdf'))
|
| 155 |
+
_macosx.FigureManager.set_icon(icon_path)
|
| 156 |
+
FigureManagerBase.__init__(self, canvas, num)
|
| 157 |
+
self._set_window_mode(mpl.rcParams["macosx.window_mode"])
|
| 158 |
+
if self.toolbar is not None:
|
| 159 |
+
self.toolbar.update()
|
| 160 |
+
if mpl.is_interactive():
|
| 161 |
+
self.show()
|
| 162 |
+
self.canvas.draw_idle()
|
| 163 |
+
|
| 164 |
+
def _close_button_pressed(self):
|
| 165 |
+
Gcf.destroy(self)
|
| 166 |
+
self.canvas.flush_events()
|
| 167 |
+
|
| 168 |
+
def destroy(self):
|
| 169 |
+
# We need to clear any pending timers that never fired, otherwise
|
| 170 |
+
# we get a memory leak from the timer callbacks holding a reference
|
| 171 |
+
while self.canvas._timers:
|
| 172 |
+
timer = self.canvas._timers.pop()
|
| 173 |
+
timer.stop()
|
| 174 |
+
super().destroy()
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def start_main_loop(cls):
|
| 178 |
+
# Set up a SIGINT handler to allow terminating a plot via CTRL-C.
|
| 179 |
+
with _allow_interrupt_macos():
|
| 180 |
+
_macosx.show()
|
| 181 |
+
|
| 182 |
+
def show(self):
|
| 183 |
+
if self.canvas.figure.stale:
|
| 184 |
+
self.canvas.draw_idle()
|
| 185 |
+
if not self._shown:
|
| 186 |
+
self._show()
|
| 187 |
+
self._shown = True
|
| 188 |
+
if mpl.rcParams["figure.raise_window"]:
|
| 189 |
+
self._raise()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@_Backend.export
|
| 193 |
+
class _BackendMac(_Backend):
|
| 194 |
+
FigureCanvas = FigureCanvasMac
|
| 195 |
+
FigureManager = FigureManagerMac
|
| 196 |
+
mainloop = FigureManagerMac.start_main_loop
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_mixed.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from matplotlib import cbook
|
| 4 |
+
from .backend_agg import RendererAgg
|
| 5 |
+
from matplotlib._tight_bbox import process_figure_for_rasterizing
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MixedModeRenderer:
|
| 9 |
+
"""
|
| 10 |
+
A helper class to implement a renderer that switches between
|
| 11 |
+
vector and raster drawing. An example may be a PDF writer, where
|
| 12 |
+
most things are drawn with PDF vector commands, but some very
|
| 13 |
+
complex objects, such as quad meshes, are rasterised and then
|
| 14 |
+
output as images.
|
| 15 |
+
"""
|
| 16 |
+
def __init__(self, figure, width, height, dpi, vector_renderer,
|
| 17 |
+
raster_renderer_class=None,
|
| 18 |
+
bbox_inches_restore=None):
|
| 19 |
+
"""
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
figure : `~matplotlib.figure.Figure`
|
| 23 |
+
The figure instance.
|
| 24 |
+
width : float
|
| 25 |
+
The width of the canvas in logical units
|
| 26 |
+
height : float
|
| 27 |
+
The height of the canvas in logical units
|
| 28 |
+
dpi : float
|
| 29 |
+
The dpi of the canvas
|
| 30 |
+
vector_renderer : `~matplotlib.backend_bases.RendererBase`
|
| 31 |
+
An instance of a subclass of
|
| 32 |
+
`~matplotlib.backend_bases.RendererBase` that will be used for the
|
| 33 |
+
vector drawing.
|
| 34 |
+
raster_renderer_class : `~matplotlib.backend_bases.RendererBase`
|
| 35 |
+
The renderer class to use for the raster drawing. If not provided,
|
| 36 |
+
this will use the Agg backend (which is currently the only viable
|
| 37 |
+
option anyway.)
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
if raster_renderer_class is None:
|
| 41 |
+
raster_renderer_class = RendererAgg
|
| 42 |
+
|
| 43 |
+
self._raster_renderer_class = raster_renderer_class
|
| 44 |
+
self._width = width
|
| 45 |
+
self._height = height
|
| 46 |
+
self.dpi = dpi
|
| 47 |
+
|
| 48 |
+
self._vector_renderer = vector_renderer
|
| 49 |
+
|
| 50 |
+
self._raster_renderer = None
|
| 51 |
+
|
| 52 |
+
# A reference to the figure is needed as we need to change
|
| 53 |
+
# the figure dpi before and after the rasterization. Although
|
| 54 |
+
# this looks ugly, I couldn't find a better solution. -JJL
|
| 55 |
+
self.figure = figure
|
| 56 |
+
self._figdpi = figure.dpi
|
| 57 |
+
|
| 58 |
+
self._bbox_inches_restore = bbox_inches_restore
|
| 59 |
+
|
| 60 |
+
self._renderer = vector_renderer
|
| 61 |
+
|
| 62 |
+
def __getattr__(self, attr):
|
| 63 |
+
# Proxy everything that hasn't been overridden to the base
|
| 64 |
+
# renderer. Things that *are* overridden can call methods
|
| 65 |
+
# on self._renderer directly, but must not cache/store
|
| 66 |
+
# methods (because things like RendererAgg change their
|
| 67 |
+
# methods on the fly in order to optimise proxying down
|
| 68 |
+
# to the underlying C implementation).
|
| 69 |
+
return getattr(self._renderer, attr)
|
| 70 |
+
|
| 71 |
+
def start_rasterizing(self):
|
| 72 |
+
"""
|
| 73 |
+
Enter "raster" mode. All subsequent drawing commands (until
|
| 74 |
+
`stop_rasterizing` is called) will be drawn with the raster backend.
|
| 75 |
+
"""
|
| 76 |
+
# change the dpi of the figure temporarily.
|
| 77 |
+
self.figure.dpi = self.dpi
|
| 78 |
+
if self._bbox_inches_restore: # when tight bbox is used
|
| 79 |
+
r = process_figure_for_rasterizing(self.figure,
|
| 80 |
+
self._bbox_inches_restore)
|
| 81 |
+
self._bbox_inches_restore = r
|
| 82 |
+
|
| 83 |
+
self._raster_renderer = self._raster_renderer_class(
|
| 84 |
+
self._width*self.dpi, self._height*self.dpi, self.dpi)
|
| 85 |
+
self._renderer = self._raster_renderer
|
| 86 |
+
|
| 87 |
+
def stop_rasterizing(self):
|
| 88 |
+
"""
|
| 89 |
+
Exit "raster" mode. All of the drawing that was done since
|
| 90 |
+
the last `start_rasterizing` call will be copied to the
|
| 91 |
+
vector backend by calling draw_image.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
self._renderer = self._vector_renderer
|
| 95 |
+
|
| 96 |
+
height = self._height * self.dpi
|
| 97 |
+
img = np.asarray(self._raster_renderer.buffer_rgba())
|
| 98 |
+
slice_y, slice_x = cbook._get_nonzero_slices(img[..., 3])
|
| 99 |
+
cropped_img = img[slice_y, slice_x]
|
| 100 |
+
if cropped_img.size:
|
| 101 |
+
gc = self._renderer.new_gc()
|
| 102 |
+
# TODO: If the mixedmode resolution differs from the figure's
|
| 103 |
+
# dpi, the image must be scaled (dpi->_figdpi). Not all
|
| 104 |
+
# backends support this.
|
| 105 |
+
self._renderer.draw_image(
|
| 106 |
+
gc,
|
| 107 |
+
slice_x.start * self._figdpi / self.dpi,
|
| 108 |
+
(height - slice_y.stop) * self._figdpi / self.dpi,
|
| 109 |
+
cropped_img[::-1])
|
| 110 |
+
self._raster_renderer = None
|
| 111 |
+
|
| 112 |
+
# restore the figure dpi.
|
| 113 |
+
self.figure.dpi = self._figdpi
|
| 114 |
+
|
| 115 |
+
if self._bbox_inches_restore: # when tight bbox is used
|
| 116 |
+
r = process_figure_for_rasterizing(self.figure,
|
| 117 |
+
self._bbox_inches_restore,
|
| 118 |
+
self._figdpi)
|
| 119 |
+
self._bbox_inches_restore = r
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_nbagg.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interactive figures in the IPython notebook."""
|
| 2 |
+
# Note: There is a notebook in
|
| 3 |
+
# lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify
|
| 4 |
+
# that changes made maintain expected behaviour.
|
| 5 |
+
|
| 6 |
+
from base64 import b64encode
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import pathlib
|
| 10 |
+
import uuid
|
| 11 |
+
|
| 12 |
+
from ipykernel.comm import Comm
|
| 13 |
+
from IPython.display import display, Javascript, HTML
|
| 14 |
+
|
| 15 |
+
from matplotlib import is_interactive
|
| 16 |
+
from matplotlib._pylab_helpers import Gcf
|
| 17 |
+
from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2
|
| 18 |
+
from .backend_webagg_core import (
|
| 19 |
+
FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg)
|
| 20 |
+
from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611
|
| 21 |
+
TimerTornado, TimerAsyncio)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def connection_info():
|
| 25 |
+
"""
|
| 26 |
+
Return a string showing the figure and connection status for the backend.
|
| 27 |
+
|
| 28 |
+
This is intended as a diagnostic tool, and not for general use.
|
| 29 |
+
"""
|
| 30 |
+
result = [
|
| 31 |
+
'{fig} - {socket}'.format(
|
| 32 |
+
fig=(manager.canvas.figure.get_label()
|
| 33 |
+
or f"Figure {manager.num}"),
|
| 34 |
+
socket=manager.web_sockets)
|
| 35 |
+
for manager in Gcf.get_all_fig_managers()
|
| 36 |
+
]
|
| 37 |
+
if not is_interactive():
|
| 38 |
+
result.append(f'Figures pending show: {len(Gcf.figs)}')
|
| 39 |
+
return '\n'.join(result)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
_FONT_AWESOME_CLASSES = { # font-awesome 4 names
|
| 43 |
+
'home': 'fa fa-home',
|
| 44 |
+
'back': 'fa fa-arrow-left',
|
| 45 |
+
'forward': 'fa fa-arrow-right',
|
| 46 |
+
'zoom_to_rect': 'fa fa-square-o',
|
| 47 |
+
'move': 'fa fa-arrows',
|
| 48 |
+
'download': 'fa fa-floppy-o',
|
| 49 |
+
None: None
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class NavigationIPy(NavigationToolbar2WebAgg):
|
| 54 |
+
|
| 55 |
+
# Use the standard toolbar items + download button
|
| 56 |
+
toolitems = [(text, tooltip_text,
|
| 57 |
+
_FONT_AWESOME_CLASSES[image_file], name_of_method)
|
| 58 |
+
for text, tooltip_text, image_file, name_of_method
|
| 59 |
+
in (NavigationToolbar2.toolitems +
|
| 60 |
+
(('Download', 'Download plot', 'download', 'download'),))
|
| 61 |
+
if image_file in _FONT_AWESOME_CLASSES]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class FigureManagerNbAgg(FigureManagerWebAgg):
|
| 65 |
+
_toolbar2_class = ToolbarCls = NavigationIPy
|
| 66 |
+
|
| 67 |
+
def __init__(self, canvas, num):
|
| 68 |
+
self._shown = False
|
| 69 |
+
super().__init__(canvas, num)
|
| 70 |
+
|
| 71 |
+
@classmethod
|
| 72 |
+
def create_with_canvas(cls, canvas_class, figure, num):
|
| 73 |
+
canvas = canvas_class(figure)
|
| 74 |
+
manager = cls(canvas, num)
|
| 75 |
+
if is_interactive():
|
| 76 |
+
manager.show()
|
| 77 |
+
canvas.draw_idle()
|
| 78 |
+
|
| 79 |
+
def destroy(event):
|
| 80 |
+
canvas.mpl_disconnect(cid)
|
| 81 |
+
Gcf.destroy(manager)
|
| 82 |
+
|
| 83 |
+
cid = canvas.mpl_connect('close_event', destroy)
|
| 84 |
+
return manager
|
| 85 |
+
|
| 86 |
+
def display_js(self):
|
| 87 |
+
# XXX How to do this just once? It has to deal with multiple
|
| 88 |
+
# browser instances using the same kernel (require.js - but the
|
| 89 |
+
# file isn't static?).
|
| 90 |
+
display(Javascript(FigureManagerNbAgg.get_javascript()))
|
| 91 |
+
|
| 92 |
+
def show(self):
|
| 93 |
+
if not self._shown:
|
| 94 |
+
self.display_js()
|
| 95 |
+
self._create_comm()
|
| 96 |
+
else:
|
| 97 |
+
self.canvas.draw_idle()
|
| 98 |
+
self._shown = True
|
| 99 |
+
# plt.figure adds an event which makes the figure in focus the active
|
| 100 |
+
# one. Disable this behaviour, as it results in figures being put as
|
| 101 |
+
# the active figure after they have been shown, even in non-interactive
|
| 102 |
+
# mode.
|
| 103 |
+
if hasattr(self, '_cidgcf'):
|
| 104 |
+
self.canvas.mpl_disconnect(self._cidgcf)
|
| 105 |
+
if not is_interactive():
|
| 106 |
+
from matplotlib._pylab_helpers import Gcf
|
| 107 |
+
Gcf.figs.pop(self.num, None)
|
| 108 |
+
|
| 109 |
+
def reshow(self):
|
| 110 |
+
"""
|
| 111 |
+
A special method to re-show the figure in the notebook.
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
self._shown = False
|
| 115 |
+
self.show()
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def connected(self):
|
| 119 |
+
return bool(self.web_sockets)
|
| 120 |
+
|
| 121 |
+
@classmethod
|
| 122 |
+
def get_javascript(cls, stream=None):
|
| 123 |
+
if stream is None:
|
| 124 |
+
output = io.StringIO()
|
| 125 |
+
else:
|
| 126 |
+
output = stream
|
| 127 |
+
super().get_javascript(stream=output)
|
| 128 |
+
output.write((pathlib.Path(__file__).parent
|
| 129 |
+
/ "web_backend/js/nbagg_mpl.js")
|
| 130 |
+
.read_text(encoding="utf-8"))
|
| 131 |
+
if stream is None:
|
| 132 |
+
return output.getvalue()
|
| 133 |
+
|
| 134 |
+
def _create_comm(self):
|
| 135 |
+
comm = CommSocket(self)
|
| 136 |
+
self.add_web_socket(comm)
|
| 137 |
+
return comm
|
| 138 |
+
|
| 139 |
+
def destroy(self):
|
| 140 |
+
self._send_event('close')
|
| 141 |
+
# need to copy comms as callbacks will modify this list
|
| 142 |
+
for comm in list(self.web_sockets):
|
| 143 |
+
comm.on_close()
|
| 144 |
+
self.clearup_closed()
|
| 145 |
+
|
| 146 |
+
def clearup_closed(self):
|
| 147 |
+
"""Clear up any closed Comms."""
|
| 148 |
+
self.web_sockets = {socket for socket in self.web_sockets
|
| 149 |
+
if socket.is_open()}
|
| 150 |
+
|
| 151 |
+
if len(self.web_sockets) == 0:
|
| 152 |
+
CloseEvent("close_event", self.canvas)._process()
|
| 153 |
+
|
| 154 |
+
def remove_comm(self, comm_id):
|
| 155 |
+
self.web_sockets = {socket for socket in self.web_sockets
|
| 156 |
+
if socket.comm.comm_id != comm_id}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class FigureCanvasNbAgg(FigureCanvasWebAggCore):
|
| 160 |
+
manager_class = FigureManagerNbAgg
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CommSocket:
|
| 164 |
+
"""
|
| 165 |
+
Manages the Comm connection between IPython and the browser (client).
|
| 166 |
+
|
| 167 |
+
Comms are 2 way, with the CommSocket being able to publish a message
|
| 168 |
+
via the send_json method, and handle a message with on_message. On the
|
| 169 |
+
JS side figure.send_message and figure.ws.onmessage do the sending and
|
| 170 |
+
receiving respectively.
|
| 171 |
+
|
| 172 |
+
"""
|
| 173 |
+
def __init__(self, manager):
|
| 174 |
+
self.supports_binary = None
|
| 175 |
+
self.manager = manager
|
| 176 |
+
self.uuid = str(uuid.uuid4())
|
| 177 |
+
# Publish an output area with a unique ID. The javascript can then
|
| 178 |
+
# hook into this area.
|
| 179 |
+
display(HTML("<div id=%r></div>" % self.uuid))
|
| 180 |
+
try:
|
| 181 |
+
self.comm = Comm('matplotlib', data={'id': self.uuid})
|
| 182 |
+
except AttributeError as err:
|
| 183 |
+
raise RuntimeError('Unable to create an IPython notebook Comm '
|
| 184 |
+
'instance. Are you in the IPython '
|
| 185 |
+
'notebook?') from err
|
| 186 |
+
self.comm.on_msg(self.on_message)
|
| 187 |
+
|
| 188 |
+
manager = self.manager
|
| 189 |
+
self._ext_close = False
|
| 190 |
+
|
| 191 |
+
def _on_close(close_message):
|
| 192 |
+
self._ext_close = True
|
| 193 |
+
manager.remove_comm(close_message['content']['comm_id'])
|
| 194 |
+
manager.clearup_closed()
|
| 195 |
+
|
| 196 |
+
self.comm.on_close(_on_close)
|
| 197 |
+
|
| 198 |
+
def is_open(self):
|
| 199 |
+
return not (self._ext_close or self.comm._closed)
|
| 200 |
+
|
| 201 |
+
def on_close(self):
|
| 202 |
+
# When the socket is closed, deregister the websocket with
|
| 203 |
+
# the FigureManager.
|
| 204 |
+
if self.is_open():
|
| 205 |
+
try:
|
| 206 |
+
self.comm.close()
|
| 207 |
+
except KeyError:
|
| 208 |
+
# apparently already cleaned it up?
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
def send_json(self, content):
|
| 212 |
+
self.comm.send({'data': json.dumps(content)})
|
| 213 |
+
|
| 214 |
+
def send_binary(self, blob):
|
| 215 |
+
if self.supports_binary:
|
| 216 |
+
self.comm.send({'blob': 'image/png'}, buffers=[blob])
|
| 217 |
+
else:
|
| 218 |
+
# The comm is ASCII, so we send the image in base64 encoded data
|
| 219 |
+
# URL form.
|
| 220 |
+
data = b64encode(blob).decode('ascii')
|
| 221 |
+
data_uri = f"data:image/png;base64,{data}"
|
| 222 |
+
self.comm.send({'data': data_uri})
|
| 223 |
+
|
| 224 |
+
def on_message(self, message):
|
| 225 |
+
# The 'supports_binary' message is relevant to the
|
| 226 |
+
# websocket itself. The other messages get passed along
|
| 227 |
+
# to matplotlib as-is.
|
| 228 |
+
|
| 229 |
+
# Every message has a "type" and a "figure_id".
|
| 230 |
+
message = json.loads(message['content']['data'])
|
| 231 |
+
if message['type'] == 'closing':
|
| 232 |
+
self.on_close()
|
| 233 |
+
self.manager.clearup_closed()
|
| 234 |
+
elif message['type'] == 'supports_binary':
|
| 235 |
+
self.supports_binary = message['value']
|
| 236 |
+
else:
|
| 237 |
+
self.manager.handle_json(message)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@_Backend.export
|
| 241 |
+
class _BackendNbAgg(_Backend):
|
| 242 |
+
FigureCanvas = FigureCanvasNbAgg
|
| 243 |
+
FigureManager = FigureManagerNbAgg
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_pdf.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import codecs
|
| 2 |
+
import datetime
|
| 3 |
+
import functools
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
import logging
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import pathlib
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
from tempfile import TemporaryDirectory
|
| 12 |
+
import weakref
|
| 13 |
+
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
import matplotlib as mpl
|
| 17 |
+
from matplotlib import cbook, font_manager as fm
|
| 18 |
+
from matplotlib.backend_bases import (
|
| 19 |
+
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase
|
| 20 |
+
)
|
| 21 |
+
from matplotlib.backends.backend_mixed import MixedModeRenderer
|
| 22 |
+
from matplotlib.backends.backend_pdf import (
|
| 23 |
+
_create_pdf_info_dict, _datetime_to_pdf)
|
| 24 |
+
from matplotlib.path import Path
|
| 25 |
+
from matplotlib.figure import Figure
|
| 26 |
+
from matplotlib.font_manager import FontProperties
|
| 27 |
+
from matplotlib._pylab_helpers import Gcf
|
| 28 |
+
|
| 29 |
+
_log = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
_DOCUMENTCLASS = r"\documentclass{article}"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Note: When formatting floating point values, it is important to use the
|
| 36 |
+
# %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
|
| 37 |
+
# which is not recognized by TeX.
|
| 38 |
+
|
| 39 |
+
def _get_preamble():
|
| 40 |
+
"""Prepare a LaTeX preamble based on the rcParams configuration."""
|
| 41 |
+
font_size_pt = FontProperties(
|
| 42 |
+
size=mpl.rcParams["font.size"]
|
| 43 |
+
).get_size_in_points()
|
| 44 |
+
return "\n".join([
|
| 45 |
+
# Remove Matplotlib's custom command \mathdefault. (Not using
|
| 46 |
+
# \mathnormal instead since this looks odd with Computer Modern.)
|
| 47 |
+
r"\def\mathdefault#1{#1}",
|
| 48 |
+
# Use displaystyle for all math.
|
| 49 |
+
r"\everymath=\expandafter{\the\everymath\displaystyle}",
|
| 50 |
+
# Set up font sizes to match font.size setting.
|
| 51 |
+
# If present, use the KOMA package scrextend to adjust the standard
|
| 52 |
+
# LaTeX font commands (\tiny, ..., \normalsize, ..., \Huge) accordingly.
|
| 53 |
+
# Otherwise, only set \normalsize, manually.
|
| 54 |
+
r"\IfFileExists{scrextend.sty}{",
|
| 55 |
+
r" \usepackage[fontsize=%fpt]{scrextend}" % font_size_pt,
|
| 56 |
+
r"}{",
|
| 57 |
+
r" \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}"
|
| 58 |
+
% (font_size_pt, 1.2 * font_size_pt),
|
| 59 |
+
r" \normalsize",
|
| 60 |
+
r"}",
|
| 61 |
+
# Allow pgf.preamble to override the above definitions.
|
| 62 |
+
mpl.rcParams["pgf.preamble"],
|
| 63 |
+
*([
|
| 64 |
+
r"\ifdefined\pdftexversion\else % non-pdftex case.",
|
| 65 |
+
r" \usepackage{fontspec}",
|
| 66 |
+
] + [
|
| 67 |
+
r" \%s{%s}[Path=\detokenize{%s/}]"
|
| 68 |
+
% (command, path.name, path.parent.as_posix())
|
| 69 |
+
for command, path in zip(
|
| 70 |
+
["setmainfont", "setsansfont", "setmonofont"],
|
| 71 |
+
[pathlib.Path(fm.findfont(family))
|
| 72 |
+
for family in ["serif", "sans\\-serif", "monospace"]]
|
| 73 |
+
)
|
| 74 |
+
] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
|
| 75 |
+
# Documented as "must come last".
|
| 76 |
+
mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"),
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# It's better to use only one unit for all coordinates, since the
|
| 81 |
+
# arithmetic in latex seems to produce inaccurate conversions.
|
| 82 |
+
latex_pt_to_in = 1. / 72.27
|
| 83 |
+
latex_in_to_pt = 1. / latex_pt_to_in
|
| 84 |
+
mpl_pt_to_in = 1. / 72.
|
| 85 |
+
mpl_in_to_pt = 1. / mpl_pt_to_in
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _tex_escape(text):
|
| 89 |
+
r"""
|
| 90 |
+
Do some necessary and/or useful substitutions for texts to be included in
|
| 91 |
+
LaTeX documents.
|
| 92 |
+
"""
|
| 93 |
+
return text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _writeln(fh, line):
|
| 97 |
+
# Ending lines with a % prevents TeX from inserting spurious spaces
|
| 98 |
+
# (https://tex.stackexchange.com/questions/7453).
|
| 99 |
+
fh.write(line)
|
| 100 |
+
fh.write("%\n")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _escape_and_apply_props(s, prop):
|
| 104 |
+
"""
|
| 105 |
+
Generate a TeX string that renders string *s* with font properties *prop*,
|
| 106 |
+
also applying any required escapes to *s*.
|
| 107 |
+
"""
|
| 108 |
+
commands = []
|
| 109 |
+
|
| 110 |
+
families = {"serif": r"\rmfamily", "sans": r"\sffamily",
|
| 111 |
+
"sans-serif": r"\sffamily", "monospace": r"\ttfamily"}
|
| 112 |
+
family = prop.get_family()[0]
|
| 113 |
+
if family in families:
|
| 114 |
+
commands.append(families[family])
|
| 115 |
+
elif not mpl.rcParams["pgf.rcfonts"]:
|
| 116 |
+
commands.append(r"\fontfamily{\familydefault}")
|
| 117 |
+
elif any(font.name == family for font in fm.fontManager.ttflist):
|
| 118 |
+
commands.append(
|
| 119 |
+
r"\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fi" % family)
|
| 120 |
+
else:
|
| 121 |
+
_log.warning("Ignoring unknown font: %s", family)
|
| 122 |
+
|
| 123 |
+
size = prop.get_size_in_points()
|
| 124 |
+
commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))
|
| 125 |
+
|
| 126 |
+
styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}
|
| 127 |
+
commands.append(styles[prop.get_style()])
|
| 128 |
+
|
| 129 |
+
boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",
|
| 130 |
+
"extra bold", "black"]
|
| 131 |
+
if prop.get_weight() in boldstyles:
|
| 132 |
+
commands.append(r"\bfseries")
|
| 133 |
+
|
| 134 |
+
commands.append(r"\selectfont")
|
| 135 |
+
return (
|
| 136 |
+
"{"
|
| 137 |
+
+ "".join(commands)
|
| 138 |
+
+ r"\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}"
|
| 139 |
+
# It should normally be enough to set the catcode of % to 12 ("normal
|
| 140 |
+
# character"); this works on TeXLive 2021 but not on 2018, so we just
|
| 141 |
+
# make it active too.
|
| 142 |
+
+ r"\catcode`\%=\active\def%{\%}"
|
| 143 |
+
+ _tex_escape(s)
|
| 144 |
+
+ "}"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _metadata_to_str(key, value):
|
| 149 |
+
"""Convert metadata key/value to a form that hyperref accepts."""
|
| 150 |
+
if isinstance(value, datetime.datetime):
|
| 151 |
+
value = _datetime_to_pdf(value)
|
| 152 |
+
elif key == 'Trapped':
|
| 153 |
+
value = value.name.decode('ascii')
|
| 154 |
+
else:
|
| 155 |
+
value = str(value)
|
| 156 |
+
return f'{key}={{{value}}}'
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def make_pdf_to_png_converter():
|
| 160 |
+
"""Return a function that converts a pdf file to a png file."""
|
| 161 |
+
try:
|
| 162 |
+
mpl._get_executable_info("pdftocairo")
|
| 163 |
+
except mpl.ExecutableNotFoundError:
|
| 164 |
+
pass
|
| 165 |
+
else:
|
| 166 |
+
return lambda pdffile, pngfile, dpi: subprocess.check_output(
|
| 167 |
+
["pdftocairo", "-singlefile", "-transp", "-png", "-r", "%d" % dpi,
|
| 168 |
+
pdffile, os.path.splitext(pngfile)[0]],
|
| 169 |
+
stderr=subprocess.STDOUT)
|
| 170 |
+
try:
|
| 171 |
+
gs_info = mpl._get_executable_info("gs")
|
| 172 |
+
except mpl.ExecutableNotFoundError:
|
| 173 |
+
pass
|
| 174 |
+
else:
|
| 175 |
+
return lambda pdffile, pngfile, dpi: subprocess.check_output(
|
| 176 |
+
[gs_info.executable,
|
| 177 |
+
'-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
|
| 178 |
+
'-dUseCIEColor', '-dTextAlphaBits=4',
|
| 179 |
+
'-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
|
| 180 |
+
'-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile,
|
| 181 |
+
'-r%d' % dpi, pdffile],
|
| 182 |
+
stderr=subprocess.STDOUT)
|
| 183 |
+
raise RuntimeError("No suitable pdf to png renderer found.")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class LatexError(Exception):
|
| 187 |
+
def __init__(self, message, latex_output=""):
|
| 188 |
+
super().__init__(message)
|
| 189 |
+
self.latex_output = latex_output
|
| 190 |
+
|
| 191 |
+
def __str__(self):
|
| 192 |
+
s, = self.args
|
| 193 |
+
if self.latex_output:
|
| 194 |
+
s += "\n" + self.latex_output
|
| 195 |
+
return s
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class LatexManager:
|
| 199 |
+
"""
|
| 200 |
+
The LatexManager opens an instance of the LaTeX application for
|
| 201 |
+
determining the metrics of text elements. The LaTeX environment can be
|
| 202 |
+
modified by setting fonts and/or a custom preamble in `.rcParams`.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
@staticmethod
|
| 206 |
+
def _build_latex_header():
|
| 207 |
+
latex_header = [
|
| 208 |
+
_DOCUMENTCLASS,
|
| 209 |
+
# Include TeX program name as a comment for cache invalidation.
|
| 210 |
+
# TeX does not allow this to be the first line.
|
| 211 |
+
rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",
|
| 212 |
+
# Test whether \includegraphics supports interpolate option.
|
| 213 |
+
r"\usepackage{graphicx}",
|
| 214 |
+
_get_preamble(),
|
| 215 |
+
r"\begin{document}",
|
| 216 |
+
r"\typeout{pgf_backend_query_start}",
|
| 217 |
+
]
|
| 218 |
+
return "\n".join(latex_header)
|
| 219 |
+
|
| 220 |
+
@classmethod
|
| 221 |
+
def _get_cached_or_new(cls):
|
| 222 |
+
"""
|
| 223 |
+
Return the previous LatexManager if the header and tex system did not
|
| 224 |
+
change, or a new instance otherwise.
|
| 225 |
+
"""
|
| 226 |
+
return cls._get_cached_or_new_impl(cls._build_latex_header())
|
| 227 |
+
|
| 228 |
+
@classmethod
|
| 229 |
+
@functools.lru_cache(1)
|
| 230 |
+
def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
|
| 231 |
+
return cls()
|
| 232 |
+
|
| 233 |
+
def _stdin_writeln(self, s):
|
| 234 |
+
if self.latex is None:
|
| 235 |
+
self._setup_latex_process()
|
| 236 |
+
self.latex.stdin.write(s)
|
| 237 |
+
self.latex.stdin.write("\n")
|
| 238 |
+
self.latex.stdin.flush()
|
| 239 |
+
|
| 240 |
+
def _expect(self, s):
|
| 241 |
+
s = list(s)
|
| 242 |
+
chars = []
|
| 243 |
+
while True:
|
| 244 |
+
c = self.latex.stdout.read(1)
|
| 245 |
+
chars.append(c)
|
| 246 |
+
if chars[-len(s):] == s:
|
| 247 |
+
break
|
| 248 |
+
if not c:
|
| 249 |
+
self.latex.kill()
|
| 250 |
+
self.latex = None
|
| 251 |
+
raise LatexError("LaTeX process halted", "".join(chars))
|
| 252 |
+
return "".join(chars)
|
| 253 |
+
|
| 254 |
+
def _expect_prompt(self):
|
| 255 |
+
return self._expect("\n*")
|
| 256 |
+
|
| 257 |
+
def __init__(self):
|
| 258 |
+
# create a tmp directory for running latex, register it for deletion
|
| 259 |
+
self._tmpdir = TemporaryDirectory()
|
| 260 |
+
self.tmpdir = self._tmpdir.name
|
| 261 |
+
self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup)
|
| 262 |
+
|
| 263 |
+
# test the LaTeX setup to ensure a clean startup of the subprocess
|
| 264 |
+
self._setup_latex_process(expect_reply=False)
|
| 265 |
+
stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n")
|
| 266 |
+
if self.latex.returncode != 0:
|
| 267 |
+
raise LatexError(
|
| 268 |
+
f"LaTeX errored (probably missing font or error in preamble) "
|
| 269 |
+
f"while processing the following input:\n"
|
| 270 |
+
f"{self._build_latex_header()}",
|
| 271 |
+
stdout)
|
| 272 |
+
self.latex = None # Will be set up on first use.
|
| 273 |
+
# Per-instance cache.
|
| 274 |
+
self._get_box_metrics = functools.lru_cache(self._get_box_metrics)
|
| 275 |
+
|
| 276 |
+
def _setup_latex_process(self, *, expect_reply=True):
|
| 277 |
+
# Open LaTeX process for real work; register it for deletion. On
|
| 278 |
+
# Windows, we must ensure that the subprocess has quit before being
|
| 279 |
+
# able to delete the tmpdir in which it runs; in order to do so, we
|
| 280 |
+
# must first `kill()` it, and then `communicate()` with or `wait()` on
|
| 281 |
+
# it.
|
| 282 |
+
try:
|
| 283 |
+
self.latex = subprocess.Popen(
|
| 284 |
+
[mpl.rcParams["pgf.texsystem"], "-halt-on-error"],
|
| 285 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 286 |
+
encoding="utf-8", cwd=self.tmpdir)
|
| 287 |
+
except FileNotFoundError as err:
|
| 288 |
+
raise RuntimeError(
|
| 289 |
+
f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change "
|
| 290 |
+
f"rcParams['pgf.texsystem'] to an available TeX implementation"
|
| 291 |
+
) from err
|
| 292 |
+
except OSError as err:
|
| 293 |
+
raise RuntimeError(
|
| 294 |
+
f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err
|
| 295 |
+
|
| 296 |
+
def finalize_latex(latex):
|
| 297 |
+
latex.kill()
|
| 298 |
+
try:
|
| 299 |
+
latex.communicate()
|
| 300 |
+
except RuntimeError:
|
| 301 |
+
latex.wait()
|
| 302 |
+
|
| 303 |
+
self._finalize_latex = weakref.finalize(
|
| 304 |
+
self, finalize_latex, self.latex)
|
| 305 |
+
# write header with 'pgf_backend_query_start' token
|
| 306 |
+
self._stdin_writeln(self._build_latex_header())
|
| 307 |
+
if expect_reply: # read until 'pgf_backend_query_start' token appears
|
| 308 |
+
self._expect("*pgf_backend_query_start")
|
| 309 |
+
self._expect_prompt()
|
| 310 |
+
|
| 311 |
+
def get_width_height_descent(self, text, prop):
|
| 312 |
+
"""
|
| 313 |
+
Get the width, total height, and descent (in TeX points) for a text
|
| 314 |
+
typeset by the current LaTeX environment.
|
| 315 |
+
"""
|
| 316 |
+
return self._get_box_metrics(_escape_and_apply_props(text, prop))
|
| 317 |
+
|
| 318 |
+
def _get_box_metrics(self, tex):
|
| 319 |
+
"""
|
| 320 |
+
Get the width, total height and descent (in TeX points) for a TeX
|
| 321 |
+
command's output in the current LaTeX environment.
|
| 322 |
+
"""
|
| 323 |
+
# This method gets wrapped in __init__ for per-instance caching.
|
| 324 |
+
self._stdin_writeln( # Send textbox to TeX & request metrics typeout.
|
| 325 |
+
# \sbox doesn't handle catcode assignments inside its argument,
|
| 326 |
+
# so repeat the assignment of the catcode of "^" and "%" outside.
|
| 327 |
+
r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}"
|
| 328 |
+
r"\typeout{\the\wd0,\the\ht0,\the\dp0}}"
|
| 329 |
+
% tex)
|
| 330 |
+
try:
|
| 331 |
+
answer = self._expect_prompt()
|
| 332 |
+
except LatexError as err:
|
| 333 |
+
# Here and below, use '{}' instead of {!r} to avoid doubling all
|
| 334 |
+
# backslashes.
|
| 335 |
+
raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
|
| 336 |
+
.format(tex, err.latex_output)) from err
|
| 337 |
+
try:
|
| 338 |
+
# Parse metrics from the answer string. Last line is prompt, and
|
| 339 |
+
# next-to-last-line is blank line from \typeout.
|
| 340 |
+
width, height, offset = answer.splitlines()[-3].split(",")
|
| 341 |
+
except Exception as err:
|
| 342 |
+
raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
|
| 343 |
+
.format(tex, answer)) from err
|
| 344 |
+
w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
|
| 345 |
+
# The height returned from LaTeX goes from base to top;
|
| 346 |
+
# the height Matplotlib expects goes from bottom to top.
|
| 347 |
+
return w, h + o, o
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
@functools.lru_cache(1)
|
| 351 |
+
def _get_image_inclusion_command():
|
| 352 |
+
man = LatexManager._get_cached_or_new()
|
| 353 |
+
man._stdin_writeln(
|
| 354 |
+
r"\includegraphics[interpolate=true]{%s}"
|
| 355 |
+
# Don't mess with backslashes on Windows.
|
| 356 |
+
% cbook._get_data_path("images/matplotlib.png").as_posix())
|
| 357 |
+
try:
|
| 358 |
+
man._expect_prompt()
|
| 359 |
+
return r"\includegraphics"
|
| 360 |
+
except LatexError:
|
| 361 |
+
# Discard the broken manager.
|
| 362 |
+
LatexManager._get_cached_or_new_impl.cache_clear()
|
| 363 |
+
return r"\pgfimage"
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class RendererPgf(RendererBase):
|
| 367 |
+
|
| 368 |
+
def __init__(self, figure, fh):
|
| 369 |
+
"""
|
| 370 |
+
Create a new PGF renderer that translates any drawing instruction
|
| 371 |
+
into text commands to be interpreted in a latex pgfpicture environment.
|
| 372 |
+
|
| 373 |
+
Attributes
|
| 374 |
+
----------
|
| 375 |
+
figure : `~matplotlib.figure.Figure`
|
| 376 |
+
Matplotlib figure to initialize height, width and dpi from.
|
| 377 |
+
fh : file-like
|
| 378 |
+
File handle for the output of the drawing commands.
|
| 379 |
+
"""
|
| 380 |
+
|
| 381 |
+
super().__init__()
|
| 382 |
+
self.dpi = figure.dpi
|
| 383 |
+
self.fh = fh
|
| 384 |
+
self.figure = figure
|
| 385 |
+
self.image_counter = 0
|
| 386 |
+
|
| 387 |
+
def draw_markers(self, gc, marker_path, marker_trans, path, trans,
|
| 388 |
+
rgbFace=None):
|
| 389 |
+
# docstring inherited
|
| 390 |
+
|
| 391 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 392 |
+
|
| 393 |
+
# convert from display units to in
|
| 394 |
+
f = 1. / self.dpi
|
| 395 |
+
|
| 396 |
+
# set style and clip
|
| 397 |
+
self._print_pgf_clip(gc)
|
| 398 |
+
self._print_pgf_path_styles(gc, rgbFace)
|
| 399 |
+
|
| 400 |
+
# build marker definition
|
| 401 |
+
bl, tr = marker_path.get_extents(marker_trans).get_points()
|
| 402 |
+
coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f
|
| 403 |
+
_writeln(self.fh,
|
| 404 |
+
r"\pgfsys@defobject{currentmarker}"
|
| 405 |
+
r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)
|
| 406 |
+
self._print_pgf_path(None, marker_path, marker_trans)
|
| 407 |
+
self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
|
| 408 |
+
fill=rgbFace is not None)
|
| 409 |
+
_writeln(self.fh, r"}")
|
| 410 |
+
|
| 411 |
+
maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
|
| 412 |
+
clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
|
| 413 |
+
|
| 414 |
+
# draw marker for each vertex
|
| 415 |
+
for point, code in path.iter_segments(trans, simplify=False,
|
| 416 |
+
clip=clip):
|
| 417 |
+
x, y = point[0] * f, point[1] * f
|
| 418 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 419 |
+
_writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))
|
| 420 |
+
_writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")
|
| 421 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 422 |
+
|
| 423 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 424 |
+
|
| 425 |
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
| 426 |
+
# docstring inherited
|
| 427 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 428 |
+
# draw the path
|
| 429 |
+
self._print_pgf_clip(gc)
|
| 430 |
+
self._print_pgf_path_styles(gc, rgbFace)
|
| 431 |
+
self._print_pgf_path(gc, path, transform, rgbFace)
|
| 432 |
+
self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
|
| 433 |
+
fill=rgbFace is not None)
|
| 434 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 435 |
+
|
| 436 |
+
# if present, draw pattern on top
|
| 437 |
+
if gc.get_hatch():
|
| 438 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 439 |
+
self._print_pgf_path_styles(gc, rgbFace)
|
| 440 |
+
|
| 441 |
+
# combine clip and path for clipping
|
| 442 |
+
self._print_pgf_clip(gc)
|
| 443 |
+
self._print_pgf_path(gc, path, transform, rgbFace)
|
| 444 |
+
_writeln(self.fh, r"\pgfusepath{clip}")
|
| 445 |
+
|
| 446 |
+
# build pattern definition
|
| 447 |
+
_writeln(self.fh,
|
| 448 |
+
r"\pgfsys@defobject{currentpattern}"
|
| 449 |
+
r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")
|
| 450 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 451 |
+
_writeln(self.fh,
|
| 452 |
+
r"\pgfpathrectangle"
|
| 453 |
+
r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")
|
| 454 |
+
_writeln(self.fh, r"\pgfusepath{clip}")
|
| 455 |
+
scale = mpl.transforms.Affine2D().scale(self.dpi)
|
| 456 |
+
self._print_pgf_path(None, gc.get_hatch_path(), scale)
|
| 457 |
+
self._pgf_path_draw(stroke=True)
|
| 458 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 459 |
+
_writeln(self.fh, r"}")
|
| 460 |
+
# repeat pattern, filling the bounding rect of the path
|
| 461 |
+
f = 1. / self.dpi
|
| 462 |
+
(xmin, ymin), (xmax, ymax) = \
|
| 463 |
+
path.get_extents(transform).get_points()
|
| 464 |
+
xmin, xmax = f * xmin, f * xmax
|
| 465 |
+
ymin, ymax = f * ymin, f * ymax
|
| 466 |
+
repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)
|
| 467 |
+
_writeln(self.fh,
|
| 468 |
+
r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))
|
| 469 |
+
for iy in range(repy):
|
| 470 |
+
for ix in range(repx):
|
| 471 |
+
_writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")
|
| 472 |
+
_writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")
|
| 473 |
+
_writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)
|
| 474 |
+
_writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")
|
| 475 |
+
|
| 476 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 477 |
+
|
| 478 |
+
def _print_pgf_clip(self, gc):
|
| 479 |
+
f = 1. / self.dpi
|
| 480 |
+
# check for clip box
|
| 481 |
+
bbox = gc.get_clip_rectangle()
|
| 482 |
+
if bbox:
|
| 483 |
+
p1, p2 = bbox.get_points()
|
| 484 |
+
w, h = p2 - p1
|
| 485 |
+
coords = p1[0] * f, p1[1] * f, w * f, h * f
|
| 486 |
+
_writeln(self.fh,
|
| 487 |
+
r"\pgfpathrectangle"
|
| 488 |
+
r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
|
| 489 |
+
% coords)
|
| 490 |
+
_writeln(self.fh, r"\pgfusepath{clip}")
|
| 491 |
+
|
| 492 |
+
# check for clip path
|
| 493 |
+
clippath, clippath_trans = gc.get_clip_path()
|
| 494 |
+
if clippath is not None:
|
| 495 |
+
self._print_pgf_path(gc, clippath, clippath_trans)
|
| 496 |
+
_writeln(self.fh, r"\pgfusepath{clip}")
|
| 497 |
+
|
| 498 |
+
def _print_pgf_path_styles(self, gc, rgbFace):
|
| 499 |
+
# cap style
|
| 500 |
+
capstyles = {"butt": r"\pgfsetbuttcap",
|
| 501 |
+
"round": r"\pgfsetroundcap",
|
| 502 |
+
"projecting": r"\pgfsetrectcap"}
|
| 503 |
+
_writeln(self.fh, capstyles[gc.get_capstyle()])
|
| 504 |
+
|
| 505 |
+
# join style
|
| 506 |
+
joinstyles = {"miter": r"\pgfsetmiterjoin",
|
| 507 |
+
"round": r"\pgfsetroundjoin",
|
| 508 |
+
"bevel": r"\pgfsetbeveljoin"}
|
| 509 |
+
_writeln(self.fh, joinstyles[gc.get_joinstyle()])
|
| 510 |
+
|
| 511 |
+
# filling
|
| 512 |
+
has_fill = rgbFace is not None
|
| 513 |
+
|
| 514 |
+
if gc.get_forced_alpha():
|
| 515 |
+
fillopacity = strokeopacity = gc.get_alpha()
|
| 516 |
+
else:
|
| 517 |
+
strokeopacity = gc.get_rgb()[3]
|
| 518 |
+
fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0
|
| 519 |
+
|
| 520 |
+
if has_fill:
|
| 521 |
+
_writeln(self.fh,
|
| 522 |
+
r"\definecolor{currentfill}{rgb}{%f,%f,%f}"
|
| 523 |
+
% tuple(rgbFace[:3]))
|
| 524 |
+
_writeln(self.fh, r"\pgfsetfillcolor{currentfill}")
|
| 525 |
+
if has_fill and fillopacity != 1.0:
|
| 526 |
+
_writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)
|
| 527 |
+
|
| 528 |
+
# linewidth and color
|
| 529 |
+
lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt
|
| 530 |
+
stroke_rgba = gc.get_rgb()
|
| 531 |
+
_writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)
|
| 532 |
+
_writeln(self.fh,
|
| 533 |
+
r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"
|
| 534 |
+
% stroke_rgba[:3])
|
| 535 |
+
_writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")
|
| 536 |
+
if strokeopacity != 1.0:
|
| 537 |
+
_writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)
|
| 538 |
+
|
| 539 |
+
# line style
|
| 540 |
+
dash_offset, dash_list = gc.get_dashes()
|
| 541 |
+
if dash_list is None:
|
| 542 |
+
_writeln(self.fh, r"\pgfsetdash{}{0pt}")
|
| 543 |
+
else:
|
| 544 |
+
_writeln(self.fh,
|
| 545 |
+
r"\pgfsetdash{%s}{%fpt}"
|
| 546 |
+
% ("".join(r"{%fpt}" % dash for dash in dash_list),
|
| 547 |
+
dash_offset))
|
| 548 |
+
|
| 549 |
+
def _print_pgf_path(self, gc, path, transform, rgbFace=None):
|
| 550 |
+
f = 1. / self.dpi
|
| 551 |
+
# check for clip box / ignore clip for filled paths
|
| 552 |
+
bbox = gc.get_clip_rectangle() if gc else None
|
| 553 |
+
maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
|
| 554 |
+
if bbox and (rgbFace is None):
|
| 555 |
+
p1, p2 = bbox.get_points()
|
| 556 |
+
clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord),
|
| 557 |
+
min(p2[0], maxcoord), min(p2[1], maxcoord))
|
| 558 |
+
else:
|
| 559 |
+
clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
|
| 560 |
+
# build path
|
| 561 |
+
for points, code in path.iter_segments(transform, clip=clip):
|
| 562 |
+
if code == Path.MOVETO:
|
| 563 |
+
x, y = tuple(points)
|
| 564 |
+
_writeln(self.fh,
|
| 565 |
+
r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
|
| 566 |
+
(f * x, f * y))
|
| 567 |
+
elif code == Path.CLOSEPOLY:
|
| 568 |
+
_writeln(self.fh, r"\pgfpathclose")
|
| 569 |
+
elif code == Path.LINETO:
|
| 570 |
+
x, y = tuple(points)
|
| 571 |
+
_writeln(self.fh,
|
| 572 |
+
r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
|
| 573 |
+
(f * x, f * y))
|
| 574 |
+
elif code == Path.CURVE3:
|
| 575 |
+
cx, cy, px, py = tuple(points)
|
| 576 |
+
coords = cx * f, cy * f, px * f, py * f
|
| 577 |
+
_writeln(self.fh,
|
| 578 |
+
r"\pgfpathquadraticcurveto"
|
| 579 |
+
r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
|
| 580 |
+
% coords)
|
| 581 |
+
elif code == Path.CURVE4:
|
| 582 |
+
c1x, c1y, c2x, c2y, px, py = tuple(points)
|
| 583 |
+
coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
|
| 584 |
+
_writeln(self.fh,
|
| 585 |
+
r"\pgfpathcurveto"
|
| 586 |
+
r"{\pgfqpoint{%fin}{%fin}}"
|
| 587 |
+
r"{\pgfqpoint{%fin}{%fin}}"
|
| 588 |
+
r"{\pgfqpoint{%fin}{%fin}}"
|
| 589 |
+
% coords)
|
| 590 |
+
|
| 591 |
+
# apply pgf decorators
|
| 592 |
+
sketch_params = gc.get_sketch_params() if gc else None
|
| 593 |
+
if sketch_params is not None:
|
| 594 |
+
# Only "length" directly maps to "segment length" in PGF's API.
|
| 595 |
+
# PGF uses "amplitude" to pass the combined deviation in both x-
|
| 596 |
+
# and y-direction, while matplotlib only varies the length of the
|
| 597 |
+
# wiggle along the line ("randomness" and "length" parameters)
|
| 598 |
+
# and has a separate "scale" argument for the amplitude.
|
| 599 |
+
# -> Use "randomness" as PRNG seed to allow the user to force the
|
| 600 |
+
# same shape on multiple sketched lines
|
| 601 |
+
scale, length, randomness = sketch_params
|
| 602 |
+
if scale is not None:
|
| 603 |
+
# make matplotlib and PGF rendering visually similar
|
| 604 |
+
length *= 0.5
|
| 605 |
+
scale *= 2
|
| 606 |
+
# PGF guarantees that repeated loading is a no-op
|
| 607 |
+
_writeln(self.fh, r"\usepgfmodule{decorations}")
|
| 608 |
+
_writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}")
|
| 609 |
+
_writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, "
|
| 610 |
+
f"segment length = {(length * f):f}in, "
|
| 611 |
+
f"amplitude = {(scale * f):f}in}}")
|
| 612 |
+
_writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}")
|
| 613 |
+
_writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}")
|
| 614 |
+
|
| 615 |
+
def _pgf_path_draw(self, stroke=True, fill=False):
|
| 616 |
+
actions = []
|
| 617 |
+
if stroke:
|
| 618 |
+
actions.append("stroke")
|
| 619 |
+
if fill:
|
| 620 |
+
actions.append("fill")
|
| 621 |
+
_writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))
|
| 622 |
+
|
| 623 |
+
def option_scale_image(self):
|
| 624 |
+
# docstring inherited
|
| 625 |
+
return True
|
| 626 |
+
|
| 627 |
+
def option_image_nocomposite(self):
|
| 628 |
+
# docstring inherited
|
| 629 |
+
return not mpl.rcParams['image.composite_image']
|
| 630 |
+
|
| 631 |
+
def draw_image(self, gc, x, y, im, transform=None):
|
| 632 |
+
# docstring inherited
|
| 633 |
+
|
| 634 |
+
h, w = im.shape[:2]
|
| 635 |
+
if w == 0 or h == 0:
|
| 636 |
+
return
|
| 637 |
+
|
| 638 |
+
if not os.path.exists(getattr(self.fh, "name", "")):
|
| 639 |
+
raise ValueError(
|
| 640 |
+
"streamed pgf-code does not support raster graphics, consider "
|
| 641 |
+
"using the pgf-to-pdf option")
|
| 642 |
+
|
| 643 |
+
# save the images to png files
|
| 644 |
+
path = pathlib.Path(self.fh.name)
|
| 645 |
+
fname_img = "%s-img%d.png" % (path.stem, self.image_counter)
|
| 646 |
+
Image.fromarray(im[::-1]).save(path.parent / fname_img)
|
| 647 |
+
self.image_counter += 1
|
| 648 |
+
|
| 649 |
+
# reference the image in the pgf picture
|
| 650 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 651 |
+
self._print_pgf_clip(gc)
|
| 652 |
+
f = 1. / self.dpi # from display coords to inch
|
| 653 |
+
if transform is None:
|
| 654 |
+
_writeln(self.fh,
|
| 655 |
+
r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
|
| 656 |
+
w, h = w * f, h * f
|
| 657 |
+
else:
|
| 658 |
+
tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
|
| 659 |
+
_writeln(self.fh,
|
| 660 |
+
r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
|
| 661 |
+
(tr1 * f, tr2 * f, tr3 * f, tr4 * f,
|
| 662 |
+
(tr5 + x) * f, (tr6 + y) * f))
|
| 663 |
+
w = h = 1 # scale is already included in the transform
|
| 664 |
+
interp = str(transform is None).lower() # interpolation in PDF reader
|
| 665 |
+
_writeln(self.fh,
|
| 666 |
+
r"\pgftext[left,bottom]"
|
| 667 |
+
r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %
|
| 668 |
+
(_get_image_inclusion_command(),
|
| 669 |
+
interp, w, h, fname_img))
|
| 670 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 671 |
+
|
| 672 |
+
def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
|
| 673 |
+
# docstring inherited
|
| 674 |
+
self.draw_text(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext)
|
| 675 |
+
|
| 676 |
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
| 677 |
+
# docstring inherited
|
| 678 |
+
|
| 679 |
+
# prepare string for tex
|
| 680 |
+
s = _escape_and_apply_props(s, prop)
|
| 681 |
+
|
| 682 |
+
_writeln(self.fh, r"\begin{pgfscope}")
|
| 683 |
+
self._print_pgf_clip(gc)
|
| 684 |
+
|
| 685 |
+
alpha = gc.get_alpha()
|
| 686 |
+
if alpha != 1.0:
|
| 687 |
+
_writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)
|
| 688 |
+
_writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)
|
| 689 |
+
rgb = tuple(gc.get_rgb())[:3]
|
| 690 |
+
_writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)
|
| 691 |
+
_writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")
|
| 692 |
+
_writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
|
| 693 |
+
s = r"\color{textcolor}" + s
|
| 694 |
+
|
| 695 |
+
dpi = self.figure.dpi
|
| 696 |
+
text_args = []
|
| 697 |
+
if mtext and (
|
| 698 |
+
(angle == 0 or
|
| 699 |
+
mtext.get_rotation_mode() == "anchor") and
|
| 700 |
+
mtext.get_verticalalignment() != "center_baseline"):
|
| 701 |
+
# if text anchoring can be supported, get the original coordinates
|
| 702 |
+
# and add alignment information
|
| 703 |
+
pos = mtext.get_unitless_position()
|
| 704 |
+
x, y = mtext.get_transform().transform(pos)
|
| 705 |
+
halign = {"left": "left", "right": "right", "center": ""}
|
| 706 |
+
valign = {"top": "top", "bottom": "bottom",
|
| 707 |
+
"baseline": "base", "center": ""}
|
| 708 |
+
text_args.extend([
|
| 709 |
+
f"x={x/dpi:f}in",
|
| 710 |
+
f"y={y/dpi:f}in",
|
| 711 |
+
halign[mtext.get_horizontalalignment()],
|
| 712 |
+
valign[mtext.get_verticalalignment()],
|
| 713 |
+
])
|
| 714 |
+
else:
|
| 715 |
+
# if not, use the text layout provided by Matplotlib.
|
| 716 |
+
text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")
|
| 717 |
+
|
| 718 |
+
if angle != 0:
|
| 719 |
+
text_args.append("rotate=%f" % angle)
|
| 720 |
+
|
| 721 |
+
_writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))
|
| 722 |
+
_writeln(self.fh, r"\end{pgfscope}")
|
| 723 |
+
|
| 724 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 725 |
+
# docstring inherited
|
| 726 |
+
# get text metrics in units of latex pt, convert to display units
|
| 727 |
+
w, h, d = (LatexManager._get_cached_or_new()
|
| 728 |
+
.get_width_height_descent(s, prop))
|
| 729 |
+
# TODO: this should be latex_pt_to_in instead of mpl_pt_to_in
|
| 730 |
+
# but having a little bit more space around the text looks better,
|
| 731 |
+
# plus the bounding box reported by LaTeX is VERY narrow
|
| 732 |
+
f = mpl_pt_to_in * self.dpi
|
| 733 |
+
return w * f, h * f, d * f
|
| 734 |
+
|
| 735 |
+
def flipy(self):
|
| 736 |
+
# docstring inherited
|
| 737 |
+
return False
|
| 738 |
+
|
| 739 |
+
def get_canvas_width_height(self):
|
| 740 |
+
# docstring inherited
|
| 741 |
+
return (self.figure.get_figwidth() * self.dpi,
|
| 742 |
+
self.figure.get_figheight() * self.dpi)
|
| 743 |
+
|
| 744 |
+
def points_to_pixels(self, points):
|
| 745 |
+
# docstring inherited
|
| 746 |
+
return points * mpl_pt_to_in * self.dpi
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
class FigureCanvasPgf(FigureCanvasBase):
|
| 750 |
+
filetypes = {"pgf": "LaTeX PGF picture",
|
| 751 |
+
"pdf": "LaTeX compiled PGF picture",
|
| 752 |
+
"png": "Portable Network Graphics", }
|
| 753 |
+
|
| 754 |
+
def get_default_filetype(self):
|
| 755 |
+
return 'pdf'
|
| 756 |
+
|
| 757 |
+
def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None):
|
| 758 |
+
|
| 759 |
+
header_text = """%% Creator: Matplotlib, PGF backend
|
| 760 |
+
%%
|
| 761 |
+
%% To include the figure in your LaTeX document, write
|
| 762 |
+
%% \\input{<filename>.pgf}
|
| 763 |
+
%%
|
| 764 |
+
%% Make sure the required packages are loaded in your preamble
|
| 765 |
+
%% \\usepackage{pgf}
|
| 766 |
+
%%
|
| 767 |
+
%% Also ensure that all the required font packages are loaded; for instance,
|
| 768 |
+
%% the lmodern package is sometimes necessary when using math font.
|
| 769 |
+
%% \\usepackage{lmodern}
|
| 770 |
+
%%
|
| 771 |
+
%% Figures using additional raster images can only be included by \\input if
|
| 772 |
+
%% they are in the same directory as the main LaTeX file. For loading figures
|
| 773 |
+
%% from other directories you can use the `import` package
|
| 774 |
+
%% \\usepackage{import}
|
| 775 |
+
%%
|
| 776 |
+
%% and then include the figures with
|
| 777 |
+
%% \\import{<path to file>}{<filename>.pgf}
|
| 778 |
+
%%
|
| 779 |
+
"""
|
| 780 |
+
|
| 781 |
+
# append the preamble used by the backend as a comment for debugging
|
| 782 |
+
header_info_preamble = ["%% Matplotlib used the following preamble"]
|
| 783 |
+
for line in _get_preamble().splitlines():
|
| 784 |
+
header_info_preamble.append("%% " + line)
|
| 785 |
+
header_info_preamble.append("%%")
|
| 786 |
+
header_info_preamble = "\n".join(header_info_preamble)
|
| 787 |
+
|
| 788 |
+
# get figure size in inch
|
| 789 |
+
w, h = self.figure.get_figwidth(), self.figure.get_figheight()
|
| 790 |
+
dpi = self.figure.dpi
|
| 791 |
+
|
| 792 |
+
# create pgfpicture environment and write the pgf code
|
| 793 |
+
fh.write(header_text)
|
| 794 |
+
fh.write(header_info_preamble)
|
| 795 |
+
fh.write("\n")
|
| 796 |
+
_writeln(fh, r"\begingroup")
|
| 797 |
+
_writeln(fh, r"\makeatletter")
|
| 798 |
+
_writeln(fh, r"\begin{pgfpicture}")
|
| 799 |
+
_writeln(fh,
|
| 800 |
+
r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
|
| 801 |
+
% (w, h))
|
| 802 |
+
_writeln(fh, r"\pgfusepath{use as bounding box, clip}")
|
| 803 |
+
renderer = MixedModeRenderer(self.figure, w, h, dpi,
|
| 804 |
+
RendererPgf(self.figure, fh),
|
| 805 |
+
bbox_inches_restore=bbox_inches_restore)
|
| 806 |
+
self.figure.draw(renderer)
|
| 807 |
+
|
| 808 |
+
# end the pgfpicture environment
|
| 809 |
+
_writeln(fh, r"\end{pgfpicture}")
|
| 810 |
+
_writeln(fh, r"\makeatother")
|
| 811 |
+
_writeln(fh, r"\endgroup")
|
| 812 |
+
|
| 813 |
+
def print_pgf(self, fname_or_fh, **kwargs):
|
| 814 |
+
"""
|
| 815 |
+
Output pgf macros for drawing the figure so it can be included and
|
| 816 |
+
rendered in latex documents.
|
| 817 |
+
"""
|
| 818 |
+
with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:
|
| 819 |
+
if not cbook.file_requires_unicode(file):
|
| 820 |
+
file = codecs.getwriter("utf-8")(file)
|
| 821 |
+
self._print_pgf_to_fh(file, **kwargs)
|
| 822 |
+
|
| 823 |
+
def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
|
| 824 |
+
"""Use LaTeX to compile a pgf generated figure to pdf."""
|
| 825 |
+
w, h = self.figure.get_size_inches()
|
| 826 |
+
|
| 827 |
+
info_dict = _create_pdf_info_dict('pgf', metadata or {})
|
| 828 |
+
pdfinfo = ','.join(
|
| 829 |
+
_metadata_to_str(k, v) for k, v in info_dict.items())
|
| 830 |
+
|
| 831 |
+
# print figure to pgf and compile it with latex
|
| 832 |
+
with TemporaryDirectory() as tmpdir:
|
| 833 |
+
tmppath = pathlib.Path(tmpdir)
|
| 834 |
+
self.print_pgf(tmppath / "figure.pgf", **kwargs)
|
| 835 |
+
(tmppath / "figure.tex").write_text(
|
| 836 |
+
"\n".join([
|
| 837 |
+
_DOCUMENTCLASS,
|
| 838 |
+
r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
|
| 839 |
+
r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
|
| 840 |
+
% (w, h),
|
| 841 |
+
r"\usepackage{pgf}",
|
| 842 |
+
_get_preamble(),
|
| 843 |
+
r"\begin{document}",
|
| 844 |
+
r"\centering",
|
| 845 |
+
r"\input{figure.pgf}",
|
| 846 |
+
r"\end{document}",
|
| 847 |
+
]), encoding="utf-8")
|
| 848 |
+
texcommand = mpl.rcParams["pgf.texsystem"]
|
| 849 |
+
cbook._check_and_log_subprocess(
|
| 850 |
+
[texcommand, "-interaction=nonstopmode", "-halt-on-error",
|
| 851 |
+
"figure.tex"], _log, cwd=tmpdir)
|
| 852 |
+
with ((tmppath / "figure.pdf").open("rb") as orig,
|
| 853 |
+
cbook.open_file_cm(fname_or_fh, "wb") as dest):
|
| 854 |
+
shutil.copyfileobj(orig, dest) # copy file contents to target
|
| 855 |
+
|
| 856 |
+
def print_png(self, fname_or_fh, **kwargs):
|
| 857 |
+
"""Use LaTeX to compile a pgf figure to pdf and convert it to png."""
|
| 858 |
+
converter = make_pdf_to_png_converter()
|
| 859 |
+
with TemporaryDirectory() as tmpdir:
|
| 860 |
+
tmppath = pathlib.Path(tmpdir)
|
| 861 |
+
pdf_path = tmppath / "figure.pdf"
|
| 862 |
+
png_path = tmppath / "figure.png"
|
| 863 |
+
self.print_pdf(pdf_path, **kwargs)
|
| 864 |
+
converter(pdf_path, png_path, dpi=self.figure.dpi)
|
| 865 |
+
with (png_path.open("rb") as orig,
|
| 866 |
+
cbook.open_file_cm(fname_or_fh, "wb") as dest):
|
| 867 |
+
shutil.copyfileobj(orig, dest) # copy file contents to target
|
| 868 |
+
|
| 869 |
+
def get_renderer(self):
|
| 870 |
+
return RendererPgf(self.figure, None)
|
| 871 |
+
|
| 872 |
+
def draw(self):
|
| 873 |
+
self.figure.draw_without_rendering()
|
| 874 |
+
return super().draw()
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
FigureManagerPgf = FigureManagerBase
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
@_Backend.export
|
| 881 |
+
class _BackendPgf(_Backend):
|
| 882 |
+
FigureCanvas = FigureCanvasPgf
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
class PdfPages:
|
| 886 |
+
"""
|
| 887 |
+
A multi-page PDF file using the pgf backend
|
| 888 |
+
|
| 889 |
+
Examples
|
| 890 |
+
--------
|
| 891 |
+
>>> import matplotlib.pyplot as plt
|
| 892 |
+
>>> # Initialize:
|
| 893 |
+
>>> with PdfPages('foo.pdf') as pdf:
|
| 894 |
+
... # As many times as you like, create a figure fig and save it:
|
| 895 |
+
... fig = plt.figure()
|
| 896 |
+
... pdf.savefig(fig)
|
| 897 |
+
... # When no figure is specified the current figure is saved
|
| 898 |
+
... pdf.savefig()
|
| 899 |
+
"""
|
| 900 |
+
|
| 901 |
+
def __init__(self, filename, *, metadata=None):
|
| 902 |
+
"""
|
| 903 |
+
Create a new PdfPages object.
|
| 904 |
+
|
| 905 |
+
Parameters
|
| 906 |
+
----------
|
| 907 |
+
filename : str or path-like
|
| 908 |
+
Plots using `PdfPages.savefig` will be written to a file at this
|
| 909 |
+
location. Any older file with the same name is overwritten.
|
| 910 |
+
|
| 911 |
+
metadata : dict, optional
|
| 912 |
+
Information dictionary object (see PDF reference section 10.2.1
|
| 913 |
+
'Document Information Dictionary'), e.g.:
|
| 914 |
+
``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
|
| 915 |
+
|
| 916 |
+
The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
|
| 917 |
+
'Creator', 'Producer', 'CreationDate', 'ModDate', and
|
| 918 |
+
'Trapped'. Values have been predefined for 'Creator', 'Producer'
|
| 919 |
+
and 'CreationDate'. They can be removed by setting them to `None`.
|
| 920 |
+
|
| 921 |
+
Note that some versions of LaTeX engines may ignore the 'Producer'
|
| 922 |
+
key and set it to themselves.
|
| 923 |
+
"""
|
| 924 |
+
self._output_name = filename
|
| 925 |
+
self._n_figures = 0
|
| 926 |
+
self._metadata = (metadata or {}).copy()
|
| 927 |
+
self._info_dict = _create_pdf_info_dict('pgf', self._metadata)
|
| 928 |
+
self._file = BytesIO()
|
| 929 |
+
|
| 930 |
+
def _write_header(self, width_inches, height_inches):
|
| 931 |
+
pdfinfo = ','.join(
|
| 932 |
+
_metadata_to_str(k, v) for k, v in self._info_dict.items())
|
| 933 |
+
latex_header = "\n".join([
|
| 934 |
+
_DOCUMENTCLASS,
|
| 935 |
+
r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
|
| 936 |
+
r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
|
| 937 |
+
% (width_inches, height_inches),
|
| 938 |
+
r"\usepackage{pgf}",
|
| 939 |
+
_get_preamble(),
|
| 940 |
+
r"\setlength{\parindent}{0pt}",
|
| 941 |
+
r"\begin{document}%",
|
| 942 |
+
])
|
| 943 |
+
self._file.write(latex_header.encode('utf-8'))
|
| 944 |
+
|
| 945 |
+
def __enter__(self):
|
| 946 |
+
return self
|
| 947 |
+
|
| 948 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 949 |
+
self.close()
|
| 950 |
+
|
| 951 |
+
def close(self):
|
| 952 |
+
"""
|
| 953 |
+
Finalize this object, running LaTeX in a temporary directory
|
| 954 |
+
and moving the final pdf file to *filename*.
|
| 955 |
+
"""
|
| 956 |
+
self._file.write(rb'\end{document}\n')
|
| 957 |
+
if self._n_figures > 0:
|
| 958 |
+
self._run_latex()
|
| 959 |
+
self._file.close()
|
| 960 |
+
|
| 961 |
+
def _run_latex(self):
|
| 962 |
+
texcommand = mpl.rcParams["pgf.texsystem"]
|
| 963 |
+
with TemporaryDirectory() as tmpdir:
|
| 964 |
+
tex_source = pathlib.Path(tmpdir, "pdf_pages.tex")
|
| 965 |
+
tex_source.write_bytes(self._file.getvalue())
|
| 966 |
+
cbook._check_and_log_subprocess(
|
| 967 |
+
[texcommand, "-interaction=nonstopmode", "-halt-on-error",
|
| 968 |
+
tex_source],
|
| 969 |
+
_log, cwd=tmpdir)
|
| 970 |
+
shutil.move(tex_source.with_suffix(".pdf"), self._output_name)
|
| 971 |
+
|
| 972 |
+
def savefig(self, figure=None, **kwargs):
|
| 973 |
+
"""
|
| 974 |
+
Save a `.Figure` to this file as a new page.
|
| 975 |
+
|
| 976 |
+
Any other keyword arguments are passed to `~.Figure.savefig`.
|
| 977 |
+
|
| 978 |
+
Parameters
|
| 979 |
+
----------
|
| 980 |
+
figure : `.Figure` or int, default: the active figure
|
| 981 |
+
The figure, or index of the figure, that is saved to the file.
|
| 982 |
+
"""
|
| 983 |
+
if not isinstance(figure, Figure):
|
| 984 |
+
if figure is None:
|
| 985 |
+
manager = Gcf.get_active()
|
| 986 |
+
else:
|
| 987 |
+
manager = Gcf.get_fig_manager(figure)
|
| 988 |
+
if manager is None:
|
| 989 |
+
raise ValueError(f"No figure {figure}")
|
| 990 |
+
figure = manager.canvas.figure
|
| 991 |
+
|
| 992 |
+
width, height = figure.get_size_inches()
|
| 993 |
+
if self._n_figures == 0:
|
| 994 |
+
self._write_header(width, height)
|
| 995 |
+
else:
|
| 996 |
+
# \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and
|
| 997 |
+
# luatex<0.85; they were renamed to \pagewidth and \pageheight
|
| 998 |
+
# on luatex>=0.85.
|
| 999 |
+
self._file.write(
|
| 1000 |
+
rb'\newpage'
|
| 1001 |
+
rb'\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%fin'
|
| 1002 |
+
rb'\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin'
|
| 1003 |
+
b'%%\n' % (width, height)
|
| 1004 |
+
)
|
| 1005 |
+
figure.savefig(self._file, format="pgf", backend="pgf", **kwargs)
|
| 1006 |
+
self._n_figures += 1
|
| 1007 |
+
|
| 1008 |
+
def get_pagecount(self):
|
| 1009 |
+
"""Return the current number of pages in the multipage pdf file."""
|
| 1010 |
+
return self._n_figures
|
pace_revision_2/.venv-pace/lib/python3.11/site-pack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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A PostScript backend, which can produce both PostScript .ps and .eps.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import bisect
|
| 6 |
+
import codecs
|
| 7 |
+
import datetime
|
| 8 |
+
from enum import Enum
|
| 9 |
+
import functools
|
| 10 |
+
from io import StringIO
|
| 11 |
+
import itertools
|
| 12 |
+
import logging
|
| 13 |
+
import math
|
| 14 |
+
import os
|
| 15 |
+
import pathlib
|
| 16 |
+
import shutil
|
| 17 |
+
import struct
|
| 18 |
+
from tempfile import TemporaryDirectory
|
| 19 |
+
import textwrap
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import fontTools
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
import matplotlib as mpl
|
| 26 |
+
from matplotlib import _api, cbook, _path, _text_helpers
|
| 27 |
+
from matplotlib._afm import AFM
|
| 28 |
+
from matplotlib.backend_bases import (
|
| 29 |
+
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
|
| 30 |
+
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
|
| 31 |
+
from matplotlib.font_manager import get_font
|
| 32 |
+
from matplotlib.ft2font import LoadFlags
|
| 33 |
+
from matplotlib._mathtext_data import uni2type1
|
| 34 |
+
from matplotlib.path import Path
|
| 35 |
+
from matplotlib.texmanager import TexManager
|
| 36 |
+
from matplotlib.transforms import Affine2D
|
| 37 |
+
from matplotlib.backends.backend_mixed import MixedModeRenderer
|
| 38 |
+
from . import _backend_pdf_ps
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_log = logging.getLogger(__name__)
|
| 42 |
+
debugPS = False
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
papersize = {'letter': (8.5, 11),
|
| 46 |
+
'legal': (8.5, 14),
|
| 47 |
+
'ledger': (11, 17),
|
| 48 |
+
'a0': (33.11, 46.81),
|
| 49 |
+
'a1': (23.39, 33.11),
|
| 50 |
+
'a2': (16.54, 23.39),
|
| 51 |
+
'a3': (11.69, 16.54),
|
| 52 |
+
'a4': (8.27, 11.69),
|
| 53 |
+
'a5': (5.83, 8.27),
|
| 54 |
+
'a6': (4.13, 5.83),
|
| 55 |
+
'a7': (2.91, 4.13),
|
| 56 |
+
'a8': (2.05, 2.91),
|
| 57 |
+
'a9': (1.46, 2.05),
|
| 58 |
+
'a10': (1.02, 1.46),
|
| 59 |
+
'b0': (40.55, 57.32),
|
| 60 |
+
'b1': (28.66, 40.55),
|
| 61 |
+
'b2': (20.27, 28.66),
|
| 62 |
+
'b3': (14.33, 20.27),
|
| 63 |
+
'b4': (10.11, 14.33),
|
| 64 |
+
'b5': (7.16, 10.11),
|
| 65 |
+
'b6': (5.04, 7.16),
|
| 66 |
+
'b7': (3.58, 5.04),
|
| 67 |
+
'b8': (2.51, 3.58),
|
| 68 |
+
'b9': (1.76, 2.51),
|
| 69 |
+
'b10': (1.26, 1.76)}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _nums_to_str(*args, sep=" "):
|
| 73 |
+
return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _move_path_to_path_or_stream(src, dst):
|
| 77 |
+
"""
|
| 78 |
+
Move the contents of file at *src* to path-or-filelike *dst*.
|
| 79 |
+
|
| 80 |
+
If *dst* is a path, the metadata of *src* are *not* copied.
|
| 81 |
+
"""
|
| 82 |
+
if is_writable_file_like(dst):
|
| 83 |
+
fh = (open(src, encoding='latin-1')
|
| 84 |
+
if file_requires_unicode(dst)
|
| 85 |
+
else open(src, 'rb'))
|
| 86 |
+
with fh:
|
| 87 |
+
shutil.copyfileobj(fh, dst)
|
| 88 |
+
else:
|
| 89 |
+
shutil.move(src, dst, copy_function=shutil.copyfile)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _font_to_ps_type3(font_path, chars):
|
| 93 |
+
"""
|
| 94 |
+
Subset *chars* from the font at *font_path* into a Type 3 font.
|
| 95 |
+
|
| 96 |
+
Parameters
|
| 97 |
+
----------
|
| 98 |
+
font_path : path-like
|
| 99 |
+
Path to the font to be subsetted.
|
| 100 |
+
chars : str
|
| 101 |
+
The characters to include in the subsetted font.
|
| 102 |
+
|
| 103 |
+
Returns
|
| 104 |
+
-------
|
| 105 |
+
str
|
| 106 |
+
The string representation of a Type 3 font, which can be included
|
| 107 |
+
verbatim into a PostScript file.
|
| 108 |
+
"""
|
| 109 |
+
font = get_font(font_path, hinting_factor=1)
|
| 110 |
+
glyph_ids = [font.get_char_index(c) for c in chars]
|
| 111 |
+
|
| 112 |
+
preamble = """\
|
| 113 |
+
%!PS-Adobe-3.0 Resource-Font
|
| 114 |
+
%%Creator: Converted from TrueType to Type 3 by Matplotlib.
|
| 115 |
+
10 dict begin
|
| 116 |
+
/FontName /{font_name} def
|
| 117 |
+
/PaintType 0 def
|
| 118 |
+
/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
|
| 119 |
+
/FontBBox [{bbox}] def
|
| 120 |
+
/FontType 3 def
|
| 121 |
+
/Encoding [{encoding}] def
|
| 122 |
+
/CharStrings {num_glyphs} dict dup begin
|
| 123 |
+
/.notdef 0 def
|
| 124 |
+
""".format(font_name=font.postscript_name,
|
| 125 |
+
inv_units_per_em=1 / font.units_per_EM,
|
| 126 |
+
bbox=" ".join(map(str, font.bbox)),
|
| 127 |
+
encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"
|
| 128 |
+
for glyph_id in glyph_ids),
|
| 129 |
+
num_glyphs=len(glyph_ids) + 1)
|
| 130 |
+
postamble = """
|
| 131 |
+
end readonly def
|
| 132 |
+
|
| 133 |
+
/BuildGlyph {
|
| 134 |
+
exch begin
|
| 135 |
+
CharStrings exch
|
| 136 |
+
2 copy known not {pop /.notdef} if
|
| 137 |
+
true 3 1 roll get exec
|
| 138 |
+
end
|
| 139 |
+
} _d
|
| 140 |
+
|
| 141 |
+
/BuildChar {
|
| 142 |
+
1 index /Encoding get exch get
|
| 143 |
+
1 index /BuildGlyph get exec
|
| 144 |
+
} _d
|
| 145 |
+
|
| 146 |
+
FontName currentdict end definefont pop
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
entries = []
|
| 150 |
+
for glyph_id in glyph_ids:
|
| 151 |
+
g = font.load_glyph(glyph_id, LoadFlags.NO_SCALE)
|
| 152 |
+
v, c = font.get_path()
|
| 153 |
+
entries.append(
|
| 154 |
+
"/%(name)s{%(bbox)s sc\n" % {
|
| 155 |
+
"name": font.get_glyph_name(glyph_id),
|
| 156 |
+
"bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
|
| 157 |
+
}
|
| 158 |
+
+ _path.convert_to_string(
|
| 159 |
+
# Convert back to TrueType's internal units (1/64's).
|
| 160 |
+
# (Other dimensions are already in these units.)
|
| 161 |
+
Path(v * 64, c), None, None, False, None, 0,
|
| 162 |
+
# No code for quad Beziers triggers auto-conversion to cubics.
|
| 163 |
+
# Drop intermediate closepolys (relying on the outline
|
| 164 |
+
# decomposer always explicitly moving to the closing point
|
| 165 |
+
# first).
|
| 166 |
+
[b"m", b"l", b"", b"c", b""], True).decode("ascii")
|
| 167 |
+
+ "ce} _d"
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
return preamble + "\n".join(entries) + postamble
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _font_to_ps_type42(font_path, chars, fh):
|
| 174 |
+
"""
|
| 175 |
+
Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
font_path : path-like
|
| 180 |
+
Path to the font to be subsetted.
|
| 181 |
+
chars : str
|
| 182 |
+
The characters to include in the subsetted font.
|
| 183 |
+
fh : file-like
|
| 184 |
+
Where to write the font.
|
| 185 |
+
"""
|
| 186 |
+
subset_str = ''.join(chr(c) for c in chars)
|
| 187 |
+
_log.debug("SUBSET %s characters: %s", font_path, subset_str)
|
| 188 |
+
try:
|
| 189 |
+
kw = {}
|
| 190 |
+
# fix this once we support loading more fonts from a collection
|
| 191 |
+
# https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541
|
| 192 |
+
if font_path.endswith('.ttc'):
|
| 193 |
+
kw['fontNumber'] = 0
|
| 194 |
+
with (fontTools.ttLib.TTFont(font_path, **kw) as font,
|
| 195 |
+
_backend_pdf_ps.get_glyphs_subset(font_path, subset_str) as subset):
|
| 196 |
+
fontdata = _backend_pdf_ps.font_as_file(subset).getvalue()
|
| 197 |
+
_log.debug(
|
| 198 |
+
"SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
|
| 199 |
+
len(fontdata)
|
| 200 |
+
)
|
| 201 |
+
fh.write(_serialize_type42(font, subset, fontdata))
|
| 202 |
+
except RuntimeError:
|
| 203 |
+
_log.warning(
|
| 204 |
+
"The PostScript backend does not currently support the selected font (%s).",
|
| 205 |
+
font_path)
|
| 206 |
+
raise
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _serialize_type42(font, subset, fontdata):
|
| 210 |
+
"""
|
| 211 |
+
Output a PostScript Type-42 format representation of font
|
| 212 |
+
|
| 213 |
+
Parameters
|
| 214 |
+
----------
|
| 215 |
+
font : fontTools.ttLib.ttFont.TTFont
|
| 216 |
+
The original font object
|
| 217 |
+
subset : fontTools.ttLib.ttFont.TTFont
|
| 218 |
+
The subset font object
|
| 219 |
+
fontdata : bytes
|
| 220 |
+
The raw font data in TTF format
|
| 221 |
+
|
| 222 |
+
Returns
|
| 223 |
+
-------
|
| 224 |
+
str
|
| 225 |
+
The Type-42 formatted font
|
| 226 |
+
"""
|
| 227 |
+
version, breakpoints = _version_and_breakpoints(font.get('loca'), fontdata)
|
| 228 |
+
post = font['post']
|
| 229 |
+
name = font['name']
|
| 230 |
+
chars = _generate_charstrings(subset)
|
| 231 |
+
sfnts = _generate_sfnts(fontdata, subset, breakpoints)
|
| 232 |
+
return textwrap.dedent(f"""
|
| 233 |
+
%%!PS-TrueTypeFont-{version[0]}.{version[1]}-{font['head'].fontRevision:.7f}
|
| 234 |
+
10 dict begin
|
| 235 |
+
/FontType 42 def
|
| 236 |
+
/FontMatrix [1 0 0 1 0 0] def
|
| 237 |
+
/FontName /{name.getDebugName(6)} def
|
| 238 |
+
/FontInfo 7 dict dup begin
|
| 239 |
+
/FullName ({name.getDebugName(4)}) def
|
| 240 |
+
/FamilyName ({name.getDebugName(1)}) def
|
| 241 |
+
/Version ({name.getDebugName(5)}) def
|
| 242 |
+
/ItalicAngle {post.italicAngle} def
|
| 243 |
+
/isFixedPitch {'true' if post.isFixedPitch else 'false'} def
|
| 244 |
+
/UnderlinePosition {post.underlinePosition} def
|
| 245 |
+
/UnderlineThickness {post.underlineThickness} def
|
| 246 |
+
end readonly def
|
| 247 |
+
/Encoding StandardEncoding def
|
| 248 |
+
/FontBBox [{_nums_to_str(*_bounds(font))}] def
|
| 249 |
+
/PaintType 0 def
|
| 250 |
+
/CIDMap 0 def
|
| 251 |
+
{chars}
|
| 252 |
+
{sfnts}
|
| 253 |
+
FontName currentdict end definefont pop
|
| 254 |
+
""")
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _version_and_breakpoints(loca, fontdata):
|
| 258 |
+
"""
|
| 259 |
+
Read the version number of the font and determine sfnts breakpoints.
|
| 260 |
+
|
| 261 |
+
When a TrueType font file is written as a Type 42 font, it has to be
|
| 262 |
+
broken into substrings of at most 65535 bytes. These substrings must
|
| 263 |
+
begin at font table boundaries or glyph boundaries in the glyf table.
|
| 264 |
+
This function determines all possible breakpoints and it is the caller's
|
| 265 |
+
responsibility to do the splitting.
|
| 266 |
+
|
| 267 |
+
Helper function for _font_to_ps_type42.
|
| 268 |
+
|
| 269 |
+
Parameters
|
| 270 |
+
----------
|
| 271 |
+
loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None
|
| 272 |
+
The loca table of the font if available
|
| 273 |
+
fontdata : bytes
|
| 274 |
+
The raw data of the font
|
| 275 |
+
|
| 276 |
+
Returns
|
| 277 |
+
-------
|
| 278 |
+
version : tuple[int, int]
|
| 279 |
+
A 2-tuple of the major version number and minor version number.
|
| 280 |
+
breakpoints : list[int]
|
| 281 |
+
The breakpoints is a sorted list of offsets into fontdata; if loca is not
|
| 282 |
+
available, just the table boundaries.
|
| 283 |
+
"""
|
| 284 |
+
v1, v2, numTables = struct.unpack('>3h', fontdata[:6])
|
| 285 |
+
version = (v1, v2)
|
| 286 |
+
|
| 287 |
+
tables = {}
|
| 288 |
+
for i in range(numTables):
|
| 289 |
+
tag, _, offset, _ = struct.unpack('>4sIII', fontdata[12 + i*16:12 + (i+1)*16])
|
| 290 |
+
tables[tag.decode('ascii')] = offset
|
| 291 |
+
if loca is not None:
|
| 292 |
+
glyf_breakpoints = {tables['glyf'] + offset for offset in loca.locations[:-1]}
|
| 293 |
+
else:
|
| 294 |
+
glyf_breakpoints = set()
|
| 295 |
+
breakpoints = sorted({*tables.values(), *glyf_breakpoints, len(fontdata)})
|
| 296 |
+
|
| 297 |
+
return version, breakpoints
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _bounds(font):
|
| 301 |
+
"""
|
| 302 |
+
Compute the font bounding box, as if all glyphs were written
|
| 303 |
+
at the same start position.
|
| 304 |
+
|
| 305 |
+
Helper function for _font_to_ps_type42.
|
| 306 |
+
|
| 307 |
+
Parameters
|
| 308 |
+
----------
|
| 309 |
+
font : fontTools.ttLib.ttFont.TTFont
|
| 310 |
+
The font
|
| 311 |
+
|
| 312 |
+
Returns
|
| 313 |
+
-------
|
| 314 |
+
tuple
|
| 315 |
+
(xMin, yMin, xMax, yMax) of the combined bounding box
|
| 316 |
+
of all the glyphs in the font
|
| 317 |
+
"""
|
| 318 |
+
gs = font.getGlyphSet(False)
|
| 319 |
+
pen = fontTools.pens.boundsPen.BoundsPen(gs)
|
| 320 |
+
for name in gs.keys():
|
| 321 |
+
gs[name].draw(pen)
|
| 322 |
+
return pen.bounds or (0, 0, 0, 0)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _generate_charstrings(font):
|
| 326 |
+
"""
|
| 327 |
+
Transform font glyphs into CharStrings
|
| 328 |
+
|
| 329 |
+
Helper function for _font_to_ps_type42.
|
| 330 |
+
|
| 331 |
+
Parameters
|
| 332 |
+
----------
|
| 333 |
+
font : fontTools.ttLib.ttFont.TTFont
|
| 334 |
+
The font
|
| 335 |
+
|
| 336 |
+
Returns
|
| 337 |
+
-------
|
| 338 |
+
str
|
| 339 |
+
A definition of the CharStrings dictionary in PostScript
|
| 340 |
+
"""
|
| 341 |
+
go = font.getGlyphOrder()
|
| 342 |
+
s = f'/CharStrings {len(go)} dict dup begin\n'
|
| 343 |
+
for i, name in enumerate(go):
|
| 344 |
+
s += f'/{name} {i} def\n'
|
| 345 |
+
s += 'end readonly def'
|
| 346 |
+
return s
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _generate_sfnts(fontdata, font, breakpoints):
|
| 350 |
+
"""
|
| 351 |
+
Transform font data into PostScript sfnts format.
|
| 352 |
+
|
| 353 |
+
Helper function for _font_to_ps_type42.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
----------
|
| 357 |
+
fontdata : bytes
|
| 358 |
+
The raw data of the font
|
| 359 |
+
font : fontTools.ttLib.ttFont.TTFont
|
| 360 |
+
The fontTools font object
|
| 361 |
+
breakpoints : list
|
| 362 |
+
Sorted offsets of possible breakpoints
|
| 363 |
+
|
| 364 |
+
Returns
|
| 365 |
+
-------
|
| 366 |
+
str
|
| 367 |
+
The sfnts array for the font definition, consisting
|
| 368 |
+
of hex-encoded strings in PostScript format
|
| 369 |
+
"""
|
| 370 |
+
s = '/sfnts['
|
| 371 |
+
pos = 0
|
| 372 |
+
while pos < len(fontdata):
|
| 373 |
+
i = bisect.bisect_left(breakpoints, pos + 65534)
|
| 374 |
+
newpos = breakpoints[i-1]
|
| 375 |
+
if newpos <= pos:
|
| 376 |
+
# have to accept a larger string
|
| 377 |
+
newpos = breakpoints[-1]
|
| 378 |
+
s += f'<{fontdata[pos:newpos].hex()}00>' # Always NUL terminate.
|
| 379 |
+
pos = newpos
|
| 380 |
+
s += ']def'
|
| 381 |
+
return '\n'.join(s[i:i+100] for i in range(0, len(s), 100))
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def _log_if_debug_on(meth):
|
| 385 |
+
"""
|
| 386 |
+
Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
|
| 387 |
+
if the global flag `debugPS` is set.
|
| 388 |
+
"""
|
| 389 |
+
@functools.wraps(meth)
|
| 390 |
+
def wrapper(self, *args, **kwargs):
|
| 391 |
+
if debugPS:
|
| 392 |
+
self._pswriter.write(f"% {meth.__name__}\n")
|
| 393 |
+
return meth(self, *args, **kwargs)
|
| 394 |
+
|
| 395 |
+
return wrapper
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
|
| 399 |
+
"""
|
| 400 |
+
The renderer handles all the drawing primitives using a graphics
|
| 401 |
+
context instance that controls the colors/styles.
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
_afm_font_dir = cbook._get_data_path("fonts/afm")
|
| 405 |
+
_use_afm_rc_name = "ps.useafm"
|
| 406 |
+
|
| 407 |
+
def __init__(self, width, height, pswriter, imagedpi=72):
|
| 408 |
+
# Although postscript itself is dpi independent, we need to inform the
|
| 409 |
+
# image code about a requested dpi to generate high resolution images
|
| 410 |
+
# and them scale them before embedding them.
|
| 411 |
+
super().__init__(width, height)
|
| 412 |
+
self._pswriter = pswriter
|
| 413 |
+
if mpl.rcParams['text.usetex']:
|
| 414 |
+
self.textcnt = 0
|
| 415 |
+
self.psfrag = []
|
| 416 |
+
self.imagedpi = imagedpi
|
| 417 |
+
|
| 418 |
+
# current renderer state (None=uninitialised)
|
| 419 |
+
self.color = None
|
| 420 |
+
self.linewidth = None
|
| 421 |
+
self.linejoin = None
|
| 422 |
+
self.linecap = None
|
| 423 |
+
self.linedash = None
|
| 424 |
+
self.fontname = None
|
| 425 |
+
self.fontsize = None
|
| 426 |
+
self._hatches = {}
|
| 427 |
+
self.image_magnification = imagedpi / 72
|
| 428 |
+
self._clip_paths = {}
|
| 429 |
+
self._path_collection_id = 0
|
| 430 |
+
|
| 431 |
+
self._character_tracker = _backend_pdf_ps.CharacterTracker()
|
| 432 |
+
self._logwarn_once = functools.cache(_log.warning)
|
| 433 |
+
|
| 434 |
+
def _is_transparent(self, rgb_or_rgba):
|
| 435 |
+
if rgb_or_rgba is None:
|
| 436 |
+
return True # Consistent with rgbFace semantics.
|
| 437 |
+
elif len(rgb_or_rgba) == 4:
|
| 438 |
+
if rgb_or_rgba[3] == 0:
|
| 439 |
+
return True
|
| 440 |
+
if rgb_or_rgba[3] != 1:
|
| 441 |
+
self._logwarn_once(
|
| 442 |
+
"The PostScript backend does not support transparency; "
|
| 443 |
+
"partially transparent artists will be rendered opaque.")
|
| 444 |
+
return False
|
| 445 |
+
else: # len() == 3.
|
| 446 |
+
return False
|
| 447 |
+
|
| 448 |
+
def set_color(self, r, g, b, store=True):
|
| 449 |
+
if (r, g, b) != self.color:
|
| 450 |
+
self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
|
| 451 |
+
if r == g == b else
|
| 452 |
+
f"{_nums_to_str(r, g, b)} setrgbcolor\n")
|
| 453 |
+
if store:
|
| 454 |
+
self.color = (r, g, b)
|
| 455 |
+
|
| 456 |
+
def set_linewidth(self, linewidth, store=True):
|
| 457 |
+
linewidth = float(linewidth)
|
| 458 |
+
if linewidth != self.linewidth:
|
| 459 |
+
self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
|
| 460 |
+
if store:
|
| 461 |
+
self.linewidth = linewidth
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def _linejoin_cmd(linejoin):
|
| 465 |
+
# Support for directly passing integer values is for backcompat.
|
| 466 |
+
linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
|
| 467 |
+
linejoin]
|
| 468 |
+
return f"{linejoin:d} setlinejoin\n"
|
| 469 |
+
|
| 470 |
+
def set_linejoin(self, linejoin, store=True):
|
| 471 |
+
if linejoin != self.linejoin:
|
| 472 |
+
self._pswriter.write(self._linejoin_cmd(linejoin))
|
| 473 |
+
if store:
|
| 474 |
+
self.linejoin = linejoin
|
| 475 |
+
|
| 476 |
+
@staticmethod
|
| 477 |
+
def _linecap_cmd(linecap):
|
| 478 |
+
# Support for directly passing integer values is for backcompat.
|
| 479 |
+
linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
|
| 480 |
+
linecap]
|
| 481 |
+
return f"{linecap:d} setlinecap\n"
|
| 482 |
+
|
| 483 |
+
def set_linecap(self, linecap, store=True):
|
| 484 |
+
if linecap != self.linecap:
|
| 485 |
+
self._pswriter.write(self._linecap_cmd(linecap))
|
| 486 |
+
if store:
|
| 487 |
+
self.linecap = linecap
|
| 488 |
+
|
| 489 |
+
def set_linedash(self, offset, seq, store=True):
|
| 490 |
+
if self.linedash is not None:
|
| 491 |
+
oldo, oldseq = self.linedash
|
| 492 |
+
if np.array_equal(seq, oldseq) and oldo == offset:
|
| 493 |
+
return
|
| 494 |
+
|
| 495 |
+
self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
|
| 496 |
+
if seq is not None and len(seq) else
|
| 497 |
+
"[] 0 setdash\n")
|
| 498 |
+
if store:
|
| 499 |
+
self.linedash = (offset, seq)
|
| 500 |
+
|
| 501 |
+
def set_font(self, fontname, fontsize, store=True):
|
| 502 |
+
if (fontname, fontsize) != (self.fontname, self.fontsize):
|
| 503 |
+
self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
|
| 504 |
+
if store:
|
| 505 |
+
self.fontname = fontname
|
| 506 |
+
self.fontsize = fontsize
|
| 507 |
+
|
| 508 |
+
def create_hatch(self, hatch, linewidth):
|
| 509 |
+
sidelen = 72
|
| 510 |
+
if hatch in self._hatches:
|
| 511 |
+
return self._hatches[hatch]
|
| 512 |
+
name = 'H%d' % len(self._hatches)
|
| 513 |
+
pageheight = self.height * 72
|
| 514 |
+
self._pswriter.write(f"""\
|
| 515 |
+
<< /PatternType 1
|
| 516 |
+
/PaintType 2
|
| 517 |
+
/TilingType 2
|
| 518 |
+
/BBox[0 0 {sidelen:d} {sidelen:d}]
|
| 519 |
+
/XStep {sidelen:d}
|
| 520 |
+
/YStep {sidelen:d}
|
| 521 |
+
|
| 522 |
+
/PaintProc {{
|
| 523 |
+
pop
|
| 524 |
+
{linewidth:g} setlinewidth
|
| 525 |
+
{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
|
| 526 |
+
gsave
|
| 527 |
+
fill
|
| 528 |
+
grestore
|
| 529 |
+
stroke
|
| 530 |
+
}} bind
|
| 531 |
+
>>
|
| 532 |
+
matrix
|
| 533 |
+
0 {pageheight:g} translate
|
| 534 |
+
makepattern
|
| 535 |
+
/{name} exch def
|
| 536 |
+
""")
|
| 537 |
+
self._hatches[hatch] = name
|
| 538 |
+
return name
|
| 539 |
+
|
| 540 |
+
def get_image_magnification(self):
|
| 541 |
+
"""
|
| 542 |
+
Get the factor by which to magnify images passed to draw_image.
|
| 543 |
+
Allows a backend to have images at a different resolution to other
|
| 544 |
+
artists.
|
| 545 |
+
"""
|
| 546 |
+
return self.image_magnification
|
| 547 |
+
|
| 548 |
+
def _convert_path(self, path, transform, clip=False, simplify=None):
|
| 549 |
+
if clip:
|
| 550 |
+
clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
|
| 551 |
+
else:
|
| 552 |
+
clip = None
|
| 553 |
+
return _path.convert_to_string(
|
| 554 |
+
path, transform, clip, simplify, None,
|
| 555 |
+
6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
|
| 556 |
+
|
| 557 |
+
def _get_clip_cmd(self, gc):
|
| 558 |
+
clip = []
|
| 559 |
+
rect = gc.get_clip_rectangle()
|
| 560 |
+
if rect is not None:
|
| 561 |
+
clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
|
| 562 |
+
path, trf = gc.get_clip_path()
|
| 563 |
+
if path is not None:
|
| 564 |
+
key = (path, id(trf))
|
| 565 |
+
custom_clip_cmd = self._clip_paths.get(key)
|
| 566 |
+
if custom_clip_cmd is None:
|
| 567 |
+
custom_clip_cmd = "c%d" % len(self._clip_paths)
|
| 568 |
+
self._pswriter.write(f"""\
|
| 569 |
+
/{custom_clip_cmd} {{
|
| 570 |
+
{self._convert_path(path, trf, simplify=False)}
|
| 571 |
+
clip
|
| 572 |
+
newpath
|
| 573 |
+
}} bind def
|
| 574 |
+
""")
|
| 575 |
+
self._clip_paths[key] = custom_clip_cmd
|
| 576 |
+
clip.append(f"{custom_clip_cmd}\n")
|
| 577 |
+
return "".join(clip)
|
| 578 |
+
|
| 579 |
+
@_log_if_debug_on
|
| 580 |
+
def draw_image(self, gc, x, y, im, transform=None):
|
| 581 |
+
# docstring inherited
|
| 582 |
+
|
| 583 |
+
h, w = im.shape[:2]
|
| 584 |
+
imagecmd = "false 3 colorimage"
|
| 585 |
+
data = im[::-1, :, :3] # Vertically flipped rgb values.
|
| 586 |
+
hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
|
| 587 |
+
|
| 588 |
+
if transform is None:
|
| 589 |
+
matrix = "1 0 0 1 0 0"
|
| 590 |
+
xscale = w / self.image_magnification
|
| 591 |
+
yscale = h / self.image_magnification
|
| 592 |
+
else:
|
| 593 |
+
matrix = " ".join(map(str, transform.frozen().to_values()))
|
| 594 |
+
xscale = 1.0
|
| 595 |
+
yscale = 1.0
|
| 596 |
+
|
| 597 |
+
self._pswriter.write(f"""\
|
| 598 |
+
gsave
|
| 599 |
+
{self._get_clip_cmd(gc)}
|
| 600 |
+
{x:g} {y:g} translate
|
| 601 |
+
[{matrix}] concat
|
| 602 |
+
{xscale:g} {yscale:g} scale
|
| 603 |
+
/DataString {w:d} string def
|
| 604 |
+
{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
|
| 605 |
+
{{
|
| 606 |
+
currentfile DataString readhexstring pop
|
| 607 |
+
}} bind {imagecmd}
|
| 608 |
+
{hexdata}
|
| 609 |
+
grestore
|
| 610 |
+
""")
|
| 611 |
+
|
| 612 |
+
@_log_if_debug_on
|
| 613 |
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
| 614 |
+
# docstring inherited
|
| 615 |
+
clip = rgbFace is None and gc.get_hatch_path() is None
|
| 616 |
+
simplify = path.should_simplify and clip
|
| 617 |
+
ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
|
| 618 |
+
self._draw_ps(ps, gc, rgbFace)
|
| 619 |
+
|
| 620 |
+
@_log_if_debug_on
|
| 621 |
+
def draw_markers(
|
| 622 |
+
self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
|
| 623 |
+
# docstring inherited
|
| 624 |
+
|
| 625 |
+
ps_color = (
|
| 626 |
+
None
|
| 627 |
+
if self._is_transparent(rgbFace)
|
| 628 |
+
else f'{_nums_to_str(rgbFace[0])} setgray'
|
| 629 |
+
if rgbFace[0] == rgbFace[1] == rgbFace[2]
|
| 630 |
+
else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
|
| 631 |
+
|
| 632 |
+
# construct the generic marker command:
|
| 633 |
+
|
| 634 |
+
# don't want the translate to be global
|
| 635 |
+
ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
|
| 636 |
+
|
| 637 |
+
lw = gc.get_linewidth()
|
| 638 |
+
alpha = (gc.get_alpha()
|
| 639 |
+
if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
|
| 640 |
+
else gc.get_rgb()[3])
|
| 641 |
+
stroke = lw > 0 and alpha > 0
|
| 642 |
+
if stroke:
|
| 643 |
+
ps_cmd.append('%.1f setlinewidth' % lw)
|
| 644 |
+
ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
|
| 645 |
+
ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
|
| 646 |
+
|
| 647 |
+
ps_cmd.append(self._convert_path(marker_path, marker_trans,
|
| 648 |
+
simplify=False))
|
| 649 |
+
|
| 650 |
+
if rgbFace:
|
| 651 |
+
if stroke:
|
| 652 |
+
ps_cmd.append('gsave')
|
| 653 |
+
if ps_color:
|
| 654 |
+
ps_cmd.extend([ps_color, 'fill'])
|
| 655 |
+
if stroke:
|
| 656 |
+
ps_cmd.append('grestore')
|
| 657 |
+
|
| 658 |
+
if stroke:
|
| 659 |
+
ps_cmd.append('stroke')
|
| 660 |
+
ps_cmd.extend(['grestore', '} bind def'])
|
| 661 |
+
|
| 662 |
+
for vertices, code in path.iter_segments(
|
| 663 |
+
trans,
|
| 664 |
+
clip=(0, 0, self.width*72, self.height*72),
|
| 665 |
+
simplify=False):
|
| 666 |
+
if len(vertices):
|
| 667 |
+
x, y = vertices[-2:]
|
| 668 |
+
ps_cmd.append(f"{x:g} {y:g} o")
|
| 669 |
+
|
| 670 |
+
ps = '\n'.join(ps_cmd)
|
| 671 |
+
self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
|
| 672 |
+
|
| 673 |
+
@_log_if_debug_on
|
| 674 |
+
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
|
| 675 |
+
offsets, offset_trans, facecolors, edgecolors,
|
| 676 |
+
linewidths, linestyles, antialiaseds, urls,
|
| 677 |
+
offset_position):
|
| 678 |
+
# Is the optimization worth it? Rough calculation:
|
| 679 |
+
# cost of emitting a path in-line is
|
| 680 |
+
# (len_path + 2) * uses_per_path
|
| 681 |
+
# cost of definition+use is
|
| 682 |
+
# (len_path + 3) + 3 * uses_per_path
|
| 683 |
+
len_path = len(paths[0].vertices) if len(paths) > 0 else 0
|
| 684 |
+
uses_per_path = self._iter_collection_uses_per_path(
|
| 685 |
+
paths, all_transforms, offsets, facecolors, edgecolors)
|
| 686 |
+
should_do_optimization = \
|
| 687 |
+
len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
|
| 688 |
+
if not should_do_optimization:
|
| 689 |
+
return RendererBase.draw_path_collection(
|
| 690 |
+
self, gc, master_transform, paths, all_transforms,
|
| 691 |
+
offsets, offset_trans, facecolors, edgecolors,
|
| 692 |
+
linewidths, linestyles, antialiaseds, urls,
|
| 693 |
+
offset_position)
|
| 694 |
+
|
| 695 |
+
path_codes = []
|
| 696 |
+
for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
|
| 697 |
+
master_transform, paths, all_transforms)):
|
| 698 |
+
name = 'p%d_%d' % (self._path_collection_id, i)
|
| 699 |
+
path_bytes = self._convert_path(path, transform, simplify=False)
|
| 700 |
+
self._pswriter.write(f"""\
|
| 701 |
+
/{name} {{
|
| 702 |
+
newpath
|
| 703 |
+
translate
|
| 704 |
+
{path_bytes}
|
| 705 |
+
}} bind def
|
| 706 |
+
""")
|
| 707 |
+
path_codes.append(name)
|
| 708 |
+
|
| 709 |
+
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
|
| 710 |
+
gc, path_codes, offsets, offset_trans,
|
| 711 |
+
facecolors, edgecolors, linewidths, linestyles,
|
| 712 |
+
antialiaseds, urls, offset_position):
|
| 713 |
+
ps = f"{xo:g} {yo:g} {path_id}"
|
| 714 |
+
self._draw_ps(ps, gc0, rgbFace)
|
| 715 |
+
|
| 716 |
+
self._path_collection_id += 1
|
| 717 |
+
|
| 718 |
+
@_log_if_debug_on
|
| 719 |
+
def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
|
| 720 |
+
# docstring inherited
|
| 721 |
+
if self._is_transparent(gc.get_rgb()):
|
| 722 |
+
return # Special handling for fully transparent.
|
| 723 |
+
|
| 724 |
+
if not hasattr(self, "psfrag"):
|
| 725 |
+
self._logwarn_once(
|
| 726 |
+
"The PS backend determines usetex status solely based on "
|
| 727 |
+
"rcParams['text.usetex'] and does not support having "
|
| 728 |
+
"usetex=True only for some elements; this element will thus "
|
| 729 |
+
"be rendered as if usetex=False.")
|
| 730 |
+
self.draw_text(gc, x, y, s, prop, angle, False, mtext)
|
| 731 |
+
return
|
| 732 |
+
|
| 733 |
+
w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
|
| 734 |
+
fontsize = prop.get_size_in_points()
|
| 735 |
+
thetext = 'psmarker%d' % self.textcnt
|
| 736 |
+
color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
|
| 737 |
+
fontcmd = {'sans-serif': r'{\sffamily %s}',
|
| 738 |
+
'monospace': r'{\ttfamily %s}'}.get(
|
| 739 |
+
mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
|
| 740 |
+
s = fontcmd % s
|
| 741 |
+
tex = r'\color[rgb]{%s} %s' % (color, s)
|
| 742 |
+
|
| 743 |
+
# Stick to bottom-left alignment, so subtract descent from the text-normal
|
| 744 |
+
# direction since text is normally positioned by its baseline.
|
| 745 |
+
rangle = np.radians(angle + 90)
|
| 746 |
+
pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
|
| 747 |
+
self.psfrag.append(
|
| 748 |
+
r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
|
| 749 |
+
thetext, angle, fontsize, fontsize*1.25, tex))
|
| 750 |
+
|
| 751 |
+
self._pswriter.write(f"""\
|
| 752 |
+
gsave
|
| 753 |
+
{pos} moveto
|
| 754 |
+
({thetext})
|
| 755 |
+
show
|
| 756 |
+
grestore
|
| 757 |
+
""")
|
| 758 |
+
self.textcnt += 1
|
| 759 |
+
|
| 760 |
+
@_log_if_debug_on
|
| 761 |
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
| 762 |
+
# docstring inherited
|
| 763 |
+
|
| 764 |
+
if self._is_transparent(gc.get_rgb()):
|
| 765 |
+
return # Special handling for fully transparent.
|
| 766 |
+
|
| 767 |
+
if ismath == 'TeX':
|
| 768 |
+
return self.draw_tex(gc, x, y, s, prop, angle)
|
| 769 |
+
|
| 770 |
+
if ismath:
|
| 771 |
+
return self.draw_mathtext(gc, x, y, s, prop, angle)
|
| 772 |
+
|
| 773 |
+
stream = [] # list of (ps_name, x, char_name)
|
| 774 |
+
|
| 775 |
+
if mpl.rcParams['ps.useafm']:
|
| 776 |
+
font = self._get_font_afm(prop)
|
| 777 |
+
ps_name = (font.postscript_name.encode("ascii", "replace")
|
| 778 |
+
.decode("ascii"))
|
| 779 |
+
scale = 0.001 * prop.get_size_in_points()
|
| 780 |
+
thisx = 0
|
| 781 |
+
last_name = None # kerns returns 0 for None.
|
| 782 |
+
for c in s:
|
| 783 |
+
name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
|
| 784 |
+
try:
|
| 785 |
+
width = font.get_width_from_char_name(name)
|
| 786 |
+
except KeyError:
|
| 787 |
+
name = 'question'
|
| 788 |
+
width = font.get_width_char('?')
|
| 789 |
+
kern = font.get_kern_dist_from_name(last_name, name)
|
| 790 |
+
last_name = name
|
| 791 |
+
thisx += kern * scale
|
| 792 |
+
stream.append((ps_name, thisx, name))
|
| 793 |
+
thisx += width * scale
|
| 794 |
+
|
| 795 |
+
else:
|
| 796 |
+
font = self._get_font_ttf(prop)
|
| 797 |
+
self._character_tracker.track(font, s)
|
| 798 |
+
for item in _text_helpers.layout(s, font):
|
| 799 |
+
ps_name = (item.ft_object.postscript_name
|
| 800 |
+
.encode("ascii", "replace").decode("ascii"))
|
| 801 |
+
glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
|
| 802 |
+
stream.append((ps_name, item.x, glyph_name))
|
| 803 |
+
self.set_color(*gc.get_rgb())
|
| 804 |
+
|
| 805 |
+
for ps_name, group in itertools. \
|
| 806 |
+
groupby(stream, lambda entry: entry[0]):
|
| 807 |
+
self.set_font(ps_name, prop.get_size_in_points(), False)
|
| 808 |
+
thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
|
| 809 |
+
for _, x, name in group)
|
| 810 |
+
self._pswriter.write(f"""\
|
| 811 |
+
gsave
|
| 812 |
+
{self._get_clip_cmd(gc)}
|
| 813 |
+
{x:g} {y:g} translate
|
| 814 |
+
{angle:g} rotate
|
| 815 |
+
{thetext}
|
| 816 |
+
grestore
|
| 817 |
+
""")
|
| 818 |
+
|
| 819 |
+
@_log_if_debug_on
|
| 820 |
+
def draw_mathtext(self, gc, x, y, s, prop, angle):
|
| 821 |
+
"""Draw the math text using matplotlib.mathtext."""
|
| 822 |
+
width, height, descent, glyphs, rects = \
|
| 823 |
+
self._text2path.mathtext_parser.parse(s, 72, prop)
|
| 824 |
+
self.set_color(*gc.get_rgb())
|
| 825 |
+
self._pswriter.write(
|
| 826 |
+
f"gsave\n"
|
| 827 |
+
f"{x:g} {y:g} translate\n"
|
| 828 |
+
f"{angle:g} rotate\n")
|
| 829 |
+
lastfont = None
|
| 830 |
+
for font, fontsize, num, ox, oy in glyphs:
|
| 831 |
+
self._character_tracker.track_glyph(font, num)
|
| 832 |
+
if (font.postscript_name, fontsize) != lastfont:
|
| 833 |
+
lastfont = font.postscript_name, fontsize
|
| 834 |
+
self._pswriter.write(
|
| 835 |
+
f"/{font.postscript_name} {fontsize} selectfont\n")
|
| 836 |
+
glyph_name = (
|
| 837 |
+
font.get_name_char(chr(num)) if isinstance(font, AFM) else
|
| 838 |
+
font.get_glyph_name(font.get_char_index(num)))
|
| 839 |
+
self._pswriter.write(
|
| 840 |
+
f"{ox:g} {oy:g} moveto\n"
|
| 841 |
+
f"/{glyph_name} glyphshow\n")
|
| 842 |
+
for ox, oy, w, h in rects:
|
| 843 |
+
self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
|
| 844 |
+
self._pswriter.write("grestore\n")
|
| 845 |
+
|
| 846 |
+
@_log_if_debug_on
|
| 847 |
+
def draw_gouraud_triangles(self, gc, points, colors, trans):
|
| 848 |
+
assert len(points) == len(colors)
|
| 849 |
+
if len(points) == 0:
|
| 850 |
+
return
|
| 851 |
+
assert points.ndim == 3
|
| 852 |
+
assert points.shape[1] == 3
|
| 853 |
+
assert points.shape[2] == 2
|
| 854 |
+
assert colors.ndim == 3
|
| 855 |
+
assert colors.shape[1] == 3
|
| 856 |
+
assert colors.shape[2] == 4
|
| 857 |
+
|
| 858 |
+
shape = points.shape
|
| 859 |
+
flat_points = points.reshape((shape[0] * shape[1], 2))
|
| 860 |
+
flat_points = trans.transform(flat_points)
|
| 861 |
+
flat_colors = colors.reshape((shape[0] * shape[1], 4))
|
| 862 |
+
points_min = np.min(flat_points, axis=0) - (1 << 12)
|
| 863 |
+
points_max = np.max(flat_points, axis=0) + (1 << 12)
|
| 864 |
+
factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
|
| 865 |
+
|
| 866 |
+
xmin, ymin = points_min
|
| 867 |
+
xmax, ymax = points_max
|
| 868 |
+
|
| 869 |
+
data = np.empty(
|
| 870 |
+
shape[0] * shape[1],
|
| 871 |
+
dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
|
| 872 |
+
data['flags'] = 0
|
| 873 |
+
data['points'] = (flat_points - points_min) * factor
|
| 874 |
+
data['colors'] = flat_colors[:, :3] * 255.0
|
| 875 |
+
hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
|
| 876 |
+
|
| 877 |
+
self._pswriter.write(f"""\
|
| 878 |
+
gsave
|
| 879 |
+
<< /ShadingType 4
|
| 880 |
+
/ColorSpace [/DeviceRGB]
|
| 881 |
+
/BitsPerCoordinate 32
|
| 882 |
+
/BitsPerComponent 8
|
| 883 |
+
/BitsPerFlag 8
|
| 884 |
+
/AntiAlias true
|
| 885 |
+
/Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
|
| 886 |
+
/DataSource <
|
| 887 |
+
{hexdata}
|
| 888 |
+
>
|
| 889 |
+
>>
|
| 890 |
+
shfill
|
| 891 |
+
grestore
|
| 892 |
+
""")
|
| 893 |
+
|
| 894 |
+
def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
|
| 895 |
+
"""
|
| 896 |
+
Emit the PostScript snippet *ps* with all the attributes from *gc*
|
| 897 |
+
applied. *ps* must consist of PostScript commands to construct a path.
|
| 898 |
+
|
| 899 |
+
The *fill* and/or *stroke* kwargs can be set to False if the *ps*
|
| 900 |
+
string already includes filling and/or stroking, in which case
|
| 901 |
+
`_draw_ps` is just supplying properties and clipping.
|
| 902 |
+
"""
|
| 903 |
+
write = self._pswriter.write
|
| 904 |
+
mightstroke = (gc.get_linewidth() > 0
|
| 905 |
+
and not self._is_transparent(gc.get_rgb()))
|
| 906 |
+
if not mightstroke:
|
| 907 |
+
stroke = False
|
| 908 |
+
if self._is_transparent(rgbFace):
|
| 909 |
+
fill = False
|
| 910 |
+
hatch = gc.get_hatch()
|
| 911 |
+
|
| 912 |
+
if mightstroke:
|
| 913 |
+
self.set_linewidth(gc.get_linewidth())
|
| 914 |
+
self.set_linejoin(gc.get_joinstyle())
|
| 915 |
+
self.set_linecap(gc.get_capstyle())
|
| 916 |
+
self.set_linedash(*gc.get_dashes())
|
| 917 |
+
if mightstroke or hatch:
|
| 918 |
+
self.set_color(*gc.get_rgb()[:3])
|
| 919 |
+
write('gsave\n')
|
| 920 |
+
|
| 921 |
+
write(self._get_clip_cmd(gc))
|
| 922 |
+
|
| 923 |
+
write(ps.strip())
|
| 924 |
+
write("\n")
|
| 925 |
+
|
| 926 |
+
if fill:
|
| 927 |
+
if stroke or hatch:
|
| 928 |
+
write("gsave\n")
|
| 929 |
+
self.set_color(*rgbFace[:3], store=False)
|
| 930 |
+
write("fill\n")
|
| 931 |
+
if stroke or hatch:
|
| 932 |
+
write("grestore\n")
|
| 933 |
+
|
| 934 |
+
if hatch:
|
| 935 |
+
hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth())
|
| 936 |
+
write("gsave\n")
|
| 937 |
+
write(_nums_to_str(*gc.get_hatch_color()[:3]))
|
| 938 |
+
write(f" {hatch_name} setpattern fill grestore\n")
|
| 939 |
+
|
| 940 |
+
if stroke:
|
| 941 |
+
write("stroke\n")
|
| 942 |
+
|
| 943 |
+
write("grestore\n")
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
class _Orientation(Enum):
|
| 947 |
+
portrait, landscape = range(2)
|
| 948 |
+
|
| 949 |
+
def swap_if_landscape(self, shape):
|
| 950 |
+
return shape[::-1] if self.name == "landscape" else shape
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class FigureCanvasPS(FigureCanvasBase):
|
| 954 |
+
fixed_dpi = 72
|
| 955 |
+
filetypes = {'ps': 'Postscript',
|
| 956 |
+
'eps': 'Encapsulated Postscript'}
|
| 957 |
+
|
| 958 |
+
def get_default_filetype(self):
|
| 959 |
+
return 'ps'
|
| 960 |
+
|
| 961 |
+
def _print_ps(
|
| 962 |
+
self, fmt, outfile, *,
|
| 963 |
+
metadata=None, papertype=None, orientation='portrait',
|
| 964 |
+
bbox_inches_restore=None, **kwargs):
|
| 965 |
+
|
| 966 |
+
dpi = self.figure.dpi
|
| 967 |
+
self.figure.dpi = 72 # Override the dpi kwarg
|
| 968 |
+
|
| 969 |
+
dsc_comments = {}
|
| 970 |
+
if isinstance(outfile, (str, os.PathLike)):
|
| 971 |
+
filename = pathlib.Path(outfile).name
|
| 972 |
+
dsc_comments["Title"] = \
|
| 973 |
+
filename.encode("ascii", "replace").decode("ascii")
|
| 974 |
+
dsc_comments["Creator"] = (metadata or {}).get(
|
| 975 |
+
"Creator",
|
| 976 |
+
f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
|
| 977 |
+
# See https://reproducible-builds.org/specs/source-date-epoch/
|
| 978 |
+
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
|
| 979 |
+
dsc_comments["CreationDate"] = (
|
| 980 |
+
datetime.datetime.fromtimestamp(
|
| 981 |
+
int(source_date_epoch),
|
| 982 |
+
datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
|
| 983 |
+
if source_date_epoch
|
| 984 |
+
else time.ctime())
|
| 985 |
+
dsc_comments = "\n".join(
|
| 986 |
+
f"%%{k}: {v}" for k, v in dsc_comments.items())
|
| 987 |
+
|
| 988 |
+
if papertype is None:
|
| 989 |
+
papertype = mpl.rcParams['ps.papersize']
|
| 990 |
+
papertype = papertype.lower()
|
| 991 |
+
_api.check_in_list(['figure', *papersize], papertype=papertype)
|
| 992 |
+
|
| 993 |
+
orientation = _api.check_getitem(
|
| 994 |
+
_Orientation, orientation=orientation.lower())
|
| 995 |
+
|
| 996 |
+
printer = (self._print_figure_tex
|
| 997 |
+
if mpl.rcParams['text.usetex'] else
|
| 998 |
+
self._print_figure)
|
| 999 |
+
printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
|
| 1000 |
+
orientation=orientation, papertype=papertype,
|
| 1001 |
+
bbox_inches_restore=bbox_inches_restore, **kwargs)
|
| 1002 |
+
|
| 1003 |
+
def _print_figure(
|
| 1004 |
+
self, fmt, outfile, *,
|
| 1005 |
+
dpi, dsc_comments, orientation, papertype,
|
| 1006 |
+
bbox_inches_restore=None):
|
| 1007 |
+
"""
|
| 1008 |
+
Render the figure to a filesystem path or a file-like object.
|
| 1009 |
+
|
| 1010 |
+
Parameters are as for `.print_figure`, except that *dsc_comments* is a
|
| 1011 |
+
string containing Document Structuring Convention comments,
|
| 1012 |
+
generated from the *metadata* parameter to `.print_figure`.
|
| 1013 |
+
"""
|
| 1014 |
+
is_eps = fmt == 'eps'
|
| 1015 |
+
if not (isinstance(outfile, (str, os.PathLike))
|
| 1016 |
+
or is_writable_file_like(outfile)):
|
| 1017 |
+
raise ValueError("outfile must be a path or a file-like object")
|
| 1018 |
+
|
| 1019 |
+
# find the appropriate papertype
|
| 1020 |
+
width, height = self.figure.get_size_inches()
|
| 1021 |
+
if is_eps or papertype == 'figure':
|
| 1022 |
+
paper_width, paper_height = width, height
|
| 1023 |
+
else:
|
| 1024 |
+
paper_width, paper_height = orientation.swap_if_landscape(
|
| 1025 |
+
papersize[papertype])
|
| 1026 |
+
|
| 1027 |
+
# center the figure on the paper
|
| 1028 |
+
xo = 72 * 0.5 * (paper_width - width)
|
| 1029 |
+
yo = 72 * 0.5 * (paper_height - height)
|
| 1030 |
+
|
| 1031 |
+
llx = xo
|
| 1032 |
+
lly = yo
|
| 1033 |
+
urx = llx + self.figure.bbox.width
|
| 1034 |
+
ury = lly + self.figure.bbox.height
|
| 1035 |
+
rotation = 0
|
| 1036 |
+
if orientation is _Orientation.landscape:
|
| 1037 |
+
llx, lly, urx, ury = lly, llx, ury, urx
|
| 1038 |
+
xo, yo = 72 * paper_height - yo, xo
|
| 1039 |
+
rotation = 90
|
| 1040 |
+
bbox = (llx, lly, urx, ury)
|
| 1041 |
+
|
| 1042 |
+
self._pswriter = StringIO()
|
| 1043 |
+
|
| 1044 |
+
# mixed mode rendering
|
| 1045 |
+
ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
|
| 1046 |
+
renderer = MixedModeRenderer(
|
| 1047 |
+
self.figure, width, height, dpi, ps_renderer,
|
| 1048 |
+
bbox_inches_restore=bbox_inches_restore)
|
| 1049 |
+
|
| 1050 |
+
self.figure.draw(renderer)
|
| 1051 |
+
|
| 1052 |
+
def print_figure_impl(fh):
|
| 1053 |
+
# write the PostScript headers
|
| 1054 |
+
if is_eps:
|
| 1055 |
+
print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
|
| 1056 |
+
else:
|
| 1057 |
+
print("%!PS-Adobe-3.0", file=fh)
|
| 1058 |
+
if papertype != 'figure':
|
| 1059 |
+
print(f"%%DocumentPaperSizes: {papertype}", file=fh)
|
| 1060 |
+
print("%%Pages: 1", file=fh)
|
| 1061 |
+
print(f"%%LanguageLevel: 3\n"
|
| 1062 |
+
f"{dsc_comments}\n"
|
| 1063 |
+
f"%%Orientation: {orientation.name}\n"
|
| 1064 |
+
f"{_get_bbox_header(bbox)}\n"
|
| 1065 |
+
f"%%EndComments\n",
|
| 1066 |
+
end="", file=fh)
|
| 1067 |
+
|
| 1068 |
+
Ndict = len(_psDefs)
|
| 1069 |
+
print("%%BeginProlog", file=fh)
|
| 1070 |
+
if not mpl.rcParams['ps.useafm']:
|
| 1071 |
+
Ndict += len(ps_renderer._character_tracker.used)
|
| 1072 |
+
print("/mpldict %d dict def" % Ndict, file=fh)
|
| 1073 |
+
print("mpldict begin", file=fh)
|
| 1074 |
+
print("\n".join(_psDefs), file=fh)
|
| 1075 |
+
if not mpl.rcParams['ps.useafm']:
|
| 1076 |
+
for font_path, chars \
|
| 1077 |
+
in ps_renderer._character_tracker.used.items():
|
| 1078 |
+
if not chars:
|
| 1079 |
+
continue
|
| 1080 |
+
fonttype = mpl.rcParams['ps.fonttype']
|
| 1081 |
+
# Can't use more than 255 chars from a single Type 3 font.
|
| 1082 |
+
if len(chars) > 255:
|
| 1083 |
+
fonttype = 42
|
| 1084 |
+
fh.flush()
|
| 1085 |
+
if fonttype == 3:
|
| 1086 |
+
fh.write(_font_to_ps_type3(font_path, chars))
|
| 1087 |
+
else: # Type 42 only.
|
| 1088 |
+
_font_to_ps_type42(font_path, chars, fh)
|
| 1089 |
+
print("end", file=fh)
|
| 1090 |
+
print("%%EndProlog", file=fh)
|
| 1091 |
+
|
| 1092 |
+
if not is_eps:
|
| 1093 |
+
print("%%Page: 1 1", file=fh)
|
| 1094 |
+
print("mpldict begin", file=fh)
|
| 1095 |
+
|
| 1096 |
+
print("%s translate" % _nums_to_str(xo, yo), file=fh)
|
| 1097 |
+
if rotation:
|
| 1098 |
+
print("%d rotate" % rotation, file=fh)
|
| 1099 |
+
print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
|
| 1100 |
+
|
| 1101 |
+
# write the figure
|
| 1102 |
+
print(self._pswriter.getvalue(), file=fh)
|
| 1103 |
+
|
| 1104 |
+
# write the trailer
|
| 1105 |
+
print("end", file=fh)
|
| 1106 |
+
print("showpage", file=fh)
|
| 1107 |
+
if not is_eps:
|
| 1108 |
+
print("%%EOF", file=fh)
|
| 1109 |
+
fh.flush()
|
| 1110 |
+
|
| 1111 |
+
if mpl.rcParams['ps.usedistiller']:
|
| 1112 |
+
# We are going to use an external program to process the output.
|
| 1113 |
+
# Write to a temporary file.
|
| 1114 |
+
with TemporaryDirectory() as tmpdir:
|
| 1115 |
+
tmpfile = os.path.join(tmpdir, "tmp.ps")
|
| 1116 |
+
with open(tmpfile, 'w', encoding='latin-1') as fh:
|
| 1117 |
+
print_figure_impl(fh)
|
| 1118 |
+
if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
|
| 1119 |
+
_try_distill(gs_distill,
|
| 1120 |
+
tmpfile, is_eps, ptype=papertype, bbox=bbox)
|
| 1121 |
+
elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
|
| 1122 |
+
_try_distill(xpdf_distill,
|
| 1123 |
+
tmpfile, is_eps, ptype=papertype, bbox=bbox)
|
| 1124 |
+
_move_path_to_path_or_stream(tmpfile, outfile)
|
| 1125 |
+
|
| 1126 |
+
else: # Write directly to outfile.
|
| 1127 |
+
with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
|
| 1128 |
+
if not file_requires_unicode(file):
|
| 1129 |
+
file = codecs.getwriter("latin-1")(file)
|
| 1130 |
+
print_figure_impl(file)
|
| 1131 |
+
|
| 1132 |
+
def _print_figure_tex(
|
| 1133 |
+
self, fmt, outfile, *,
|
| 1134 |
+
dpi, dsc_comments, orientation, papertype,
|
| 1135 |
+
bbox_inches_restore=None):
|
| 1136 |
+
"""
|
| 1137 |
+
If :rc:`text.usetex` is True, a temporary pair of tex/eps files
|
| 1138 |
+
are created to allow tex to manage the text layout via the PSFrags
|
| 1139 |
+
package. These files are processed to yield the final ps or eps file.
|
| 1140 |
+
|
| 1141 |
+
The rest of the behavior is as for `._print_figure`.
|
| 1142 |
+
"""
|
| 1143 |
+
is_eps = fmt == 'eps'
|
| 1144 |
+
|
| 1145 |
+
width, height = self.figure.get_size_inches()
|
| 1146 |
+
xo = 0
|
| 1147 |
+
yo = 0
|
| 1148 |
+
|
| 1149 |
+
llx = xo
|
| 1150 |
+
lly = yo
|
| 1151 |
+
urx = llx + self.figure.bbox.width
|
| 1152 |
+
ury = lly + self.figure.bbox.height
|
| 1153 |
+
bbox = (llx, lly, urx, ury)
|
| 1154 |
+
|
| 1155 |
+
self._pswriter = StringIO()
|
| 1156 |
+
|
| 1157 |
+
# mixed mode rendering
|
| 1158 |
+
ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
|
| 1159 |
+
renderer = MixedModeRenderer(self.figure,
|
| 1160 |
+
width, height, dpi, ps_renderer,
|
| 1161 |
+
bbox_inches_restore=bbox_inches_restore)
|
| 1162 |
+
|
| 1163 |
+
self.figure.draw(renderer)
|
| 1164 |
+
|
| 1165 |
+
# write to a temp file, we'll move it to outfile when done
|
| 1166 |
+
with TemporaryDirectory() as tmpdir:
|
| 1167 |
+
tmppath = pathlib.Path(tmpdir, "tmp.ps")
|
| 1168 |
+
tmppath.write_text(
|
| 1169 |
+
f"""\
|
| 1170 |
+
%!PS-Adobe-3.0 EPSF-3.0
|
| 1171 |
+
%%LanguageLevel: 3
|
| 1172 |
+
{dsc_comments}
|
| 1173 |
+
{_get_bbox_header(bbox)}
|
| 1174 |
+
%%EndComments
|
| 1175 |
+
%%BeginProlog
|
| 1176 |
+
/mpldict {len(_psDefs)} dict def
|
| 1177 |
+
mpldict begin
|
| 1178 |
+
{"".join(_psDefs)}
|
| 1179 |
+
end
|
| 1180 |
+
%%EndProlog
|
| 1181 |
+
mpldict begin
|
| 1182 |
+
{_nums_to_str(xo, yo)} translate
|
| 1183 |
+
0 0 {_nums_to_str(width*72, height*72)} rectclip
|
| 1184 |
+
{self._pswriter.getvalue()}
|
| 1185 |
+
end
|
| 1186 |
+
showpage
|
| 1187 |
+
""",
|
| 1188 |
+
encoding="latin-1")
|
| 1189 |
+
|
| 1190 |
+
if orientation is _Orientation.landscape: # now, ready to rotate
|
| 1191 |
+
width, height = height, width
|
| 1192 |
+
bbox = (lly, llx, ury, urx)
|
| 1193 |
+
|
| 1194 |
+
# set the paper size to the figure size if is_eps. The
|
| 1195 |
+
# resulting ps file has the given size with correct bounding
|
| 1196 |
+
# box so that there is no need to call 'pstoeps'
|
| 1197 |
+
if is_eps or papertype == 'figure':
|
| 1198 |
+
paper_width, paper_height = orientation.swap_if_landscape(
|
| 1199 |
+
self.figure.get_size_inches())
|
| 1200 |
+
else:
|
| 1201 |
+
paper_width, paper_height = papersize[papertype]
|
| 1202 |
+
|
| 1203 |
+
psfrag_rotated = _convert_psfrags(
|
| 1204 |
+
tmppath, ps_renderer.psfrag, paper_width, paper_height,
|
| 1205 |
+
orientation.name)
|
| 1206 |
+
|
| 1207 |
+
if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
|
| 1208 |
+
or mpl.rcParams['text.usetex']):
|
| 1209 |
+
_try_distill(gs_distill,
|
| 1210 |
+
tmppath, is_eps, ptype=papertype, bbox=bbox,
|
| 1211 |
+
rotated=psfrag_rotated)
|
| 1212 |
+
elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
|
| 1213 |
+
_try_distill(xpdf_distill,
|
| 1214 |
+
tmppath, is_eps, ptype=papertype, bbox=bbox,
|
| 1215 |
+
rotated=psfrag_rotated)
|
| 1216 |
+
|
| 1217 |
+
_move_path_to_path_or_stream(tmppath, outfile)
|
| 1218 |
+
|
| 1219 |
+
print_ps = functools.partialmethod(_print_ps, "ps")
|
| 1220 |
+
print_eps = functools.partialmethod(_print_ps, "eps")
|
| 1221 |
+
|
| 1222 |
+
def draw(self):
|
| 1223 |
+
self.figure.draw_without_rendering()
|
| 1224 |
+
return super().draw()
|
| 1225 |
+
|
| 1226 |
+
|
| 1227 |
+
def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
|
| 1228 |
+
"""
|
| 1229 |
+
When we want to use the LaTeX backend with postscript, we write PSFrag tags
|
| 1230 |
+
to a temporary postscript file, each one marking a position for LaTeX to
|
| 1231 |
+
render some text. convert_psfrags generates a LaTeX document containing the
|
| 1232 |
+
commands to convert those tags to text. LaTeX/dvips produces the postscript
|
| 1233 |
+
file that includes the actual text.
|
| 1234 |
+
"""
|
| 1235 |
+
with mpl.rc_context({
|
| 1236 |
+
"text.latex.preamble":
|
| 1237 |
+
mpl.rcParams["text.latex.preamble"] +
|
| 1238 |
+
mpl.texmanager._usepackage_if_not_loaded("color") +
|
| 1239 |
+
mpl.texmanager._usepackage_if_not_loaded("graphicx") +
|
| 1240 |
+
mpl.texmanager._usepackage_if_not_loaded("psfrag") +
|
| 1241 |
+
r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
|
| 1242 |
+
% {"width": paper_width, "height": paper_height}
|
| 1243 |
+
}):
|
| 1244 |
+
dvifile = TexManager().make_dvi(
|
| 1245 |
+
"\n"
|
| 1246 |
+
r"\begin{figure}""\n"
|
| 1247 |
+
r" \centering\leavevmode""\n"
|
| 1248 |
+
r" %(psfrags)s""\n"
|
| 1249 |
+
r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
|
| 1250 |
+
r"\end{figure}"
|
| 1251 |
+
% {
|
| 1252 |
+
"psfrags": "\n".join(psfrags),
|
| 1253 |
+
"angle": 90 if orientation == 'landscape' else 0,
|
| 1254 |
+
"epsfile": tmppath.resolve().as_posix(),
|
| 1255 |
+
},
|
| 1256 |
+
fontsize=10) # tex's default fontsize.
|
| 1257 |
+
|
| 1258 |
+
with TemporaryDirectory() as tmpdir:
|
| 1259 |
+
psfile = os.path.join(tmpdir, "tmp.ps")
|
| 1260 |
+
cbook._check_and_log_subprocess(
|
| 1261 |
+
['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
|
| 1262 |
+
shutil.move(psfile, tmppath)
|
| 1263 |
+
|
| 1264 |
+
# check if the dvips created a ps in landscape paper. Somehow,
|
| 1265 |
+
# above latex+dvips results in a ps file in a landscape mode for a
|
| 1266 |
+
# certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
|
| 1267 |
+
# bounding box of the final output got messed up. We check see if
|
| 1268 |
+
# the generated ps file is in landscape and return this
|
| 1269 |
+
# information. The return value is used in pstoeps step to recover
|
| 1270 |
+
# the correct bounding box. 2010-06-05 JJL
|
| 1271 |
+
with open(tmppath) as fh:
|
| 1272 |
+
psfrag_rotated = "Landscape" in fh.read(1000)
|
| 1273 |
+
return psfrag_rotated
|
| 1274 |
+
|
| 1275 |
+
|
| 1276 |
+
def _try_distill(func, tmppath, *args, **kwargs):
|
| 1277 |
+
try:
|
| 1278 |
+
func(str(tmppath), *args, **kwargs)
|
| 1279 |
+
except mpl.ExecutableNotFoundError as exc:
|
| 1280 |
+
_log.warning("%s. Distillation step skipped.", exc)
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
|
| 1284 |
+
"""
|
| 1285 |
+
Use ghostscript's pswrite or epswrite device to distill a file.
|
| 1286 |
+
This yields smaller files without illegal encapsulated postscript
|
| 1287 |
+
operators. The output is low-level, converting text to outlines.
|
| 1288 |
+
"""
|
| 1289 |
+
|
| 1290 |
+
if eps:
|
| 1291 |
+
paper_option = ["-dEPSCrop"]
|
| 1292 |
+
elif ptype == "figure":
|
| 1293 |
+
# The bbox will have its lower-left corner at (0, 0), so upper-right
|
| 1294 |
+
# corner corresponds with paper size.
|
| 1295 |
+
paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
|
| 1296 |
+
f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
|
| 1297 |
+
else:
|
| 1298 |
+
paper_option = [f"-sPAPERSIZE={ptype}"]
|
| 1299 |
+
|
| 1300 |
+
psfile = tmpfile + '.ps'
|
| 1301 |
+
dpi = mpl.rcParams['ps.distiller.res']
|
| 1302 |
+
|
| 1303 |
+
cbook._check_and_log_subprocess(
|
| 1304 |
+
[mpl._get_executable_info("gs").executable,
|
| 1305 |
+
"-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
|
| 1306 |
+
*paper_option, f"-sOutputFile={psfile}", tmpfile],
|
| 1307 |
+
_log)
|
| 1308 |
+
|
| 1309 |
+
os.remove(tmpfile)
|
| 1310 |
+
shutil.move(psfile, tmpfile)
|
| 1311 |
+
|
| 1312 |
+
# While it is best if above steps preserve the original bounding
|
| 1313 |
+
# box, there seem to be cases when it is not. For those cases,
|
| 1314 |
+
# the original bbox can be restored during the pstoeps step.
|
| 1315 |
+
|
| 1316 |
+
if eps:
|
| 1317 |
+
# For some versions of gs, above steps result in a ps file where the
|
| 1318 |
+
# original bbox is no more correct. Do not adjust bbox for now.
|
| 1319 |
+
pstoeps(tmpfile, bbox, rotated=rotated)
|
| 1320 |
+
|
| 1321 |
+
|
| 1322 |
+
def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
|
| 1323 |
+
"""
|
| 1324 |
+
Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
|
| 1325 |
+
This yields smaller files without illegal encapsulated postscript
|
| 1326 |
+
operators. This distiller is preferred, generating high-level postscript
|
| 1327 |
+
output that treats text as text.
|
| 1328 |
+
"""
|
| 1329 |
+
mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
|
| 1330 |
+
mpl._get_executable_info("pdftops")
|
| 1331 |
+
|
| 1332 |
+
if eps:
|
| 1333 |
+
paper_option = ["-dEPSCrop"]
|
| 1334 |
+
elif ptype == "figure":
|
| 1335 |
+
# The bbox will have its lower-left corner at (0, 0), so upper-right
|
| 1336 |
+
# corner corresponds with paper size.
|
| 1337 |
+
paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
|
| 1338 |
+
f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
|
| 1339 |
+
else:
|
| 1340 |
+
paper_option = [f"-sPAPERSIZE#{ptype}"]
|
| 1341 |
+
|
| 1342 |
+
with TemporaryDirectory() as tmpdir:
|
| 1343 |
+
tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
|
| 1344 |
+
tmpps = pathlib.Path(tmpdir, "tmp.ps")
|
| 1345 |
+
# Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
|
| 1346 |
+
# happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
|
| 1347 |
+
cbook._check_and_log_subprocess(
|
| 1348 |
+
["ps2pdf",
|
| 1349 |
+
"-dAutoFilterColorImages#false",
|
| 1350 |
+
"-dAutoFilterGrayImages#false",
|
| 1351 |
+
"-sAutoRotatePages#None",
|
| 1352 |
+
"-sGrayImageFilter#FlateEncode",
|
| 1353 |
+
"-sColorImageFilter#FlateEncode",
|
| 1354 |
+
*paper_option,
|
| 1355 |
+
tmpfile, tmppdf], _log)
|
| 1356 |
+
cbook._check_and_log_subprocess(
|
| 1357 |
+
["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
|
| 1358 |
+
shutil.move(tmpps, tmpfile)
|
| 1359 |
+
if eps:
|
| 1360 |
+
pstoeps(tmpfile)
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
@_api.deprecated("3.9")
|
| 1364 |
+
def get_bbox_header(lbrt, rotated=False):
|
| 1365 |
+
"""
|
| 1366 |
+
Return a postscript header string for the given bbox lbrt=(l, b, r, t).
|
| 1367 |
+
Optionally, return rotate command.
|
| 1368 |
+
"""
|
| 1369 |
+
return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "")
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def _get_bbox_header(lbrt):
|
| 1373 |
+
"""Return a PostScript header string for bounding box *lbrt*=(l, b, r, t)."""
|
| 1374 |
+
l, b, r, t = lbrt
|
| 1375 |
+
return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n"
|
| 1376 |
+
f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}")
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def _get_rotate_command(lbrt):
|
| 1380 |
+
"""Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t)."""
|
| 1381 |
+
l, b, r, t = lbrt
|
| 1382 |
+
return f"{l+r:.2f} {0:.2f} translate\n90 rotate"
|
| 1383 |
+
|
| 1384 |
+
|
| 1385 |
+
def pstoeps(tmpfile, bbox=None, rotated=False):
|
| 1386 |
+
"""
|
| 1387 |
+
Convert the postscript to encapsulated postscript. The bbox of
|
| 1388 |
+
the eps file will be replaced with the given *bbox* argument. If
|
| 1389 |
+
None, original bbox will be used.
|
| 1390 |
+
"""
|
| 1391 |
+
|
| 1392 |
+
epsfile = tmpfile + '.eps'
|
| 1393 |
+
with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
|
| 1394 |
+
write = epsh.write
|
| 1395 |
+
# Modify the header:
|
| 1396 |
+
for line in tmph:
|
| 1397 |
+
if line.startswith(b'%!PS'):
|
| 1398 |
+
write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
|
| 1399 |
+
if bbox:
|
| 1400 |
+
write(_get_bbox_header(bbox).encode('ascii') + b'\n')
|
| 1401 |
+
elif line.startswith(b'%%EndComments'):
|
| 1402 |
+
write(line)
|
| 1403 |
+
write(b'%%BeginProlog\n'
|
| 1404 |
+
b'save\n'
|
| 1405 |
+
b'countdictstack\n'
|
| 1406 |
+
b'mark\n'
|
| 1407 |
+
b'newpath\n'
|
| 1408 |
+
b'/showpage {} def\n'
|
| 1409 |
+
b'/setpagedevice {pop} def\n'
|
| 1410 |
+
b'%%EndProlog\n'
|
| 1411 |
+
b'%%Page 1 1\n')
|
| 1412 |
+
if rotated: # The output eps file need to be rotated.
|
| 1413 |
+
write(_get_rotate_command(bbox).encode('ascii') + b'\n')
|
| 1414 |
+
break
|
| 1415 |
+
elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
|
| 1416 |
+
b'%%DocumentMedia', b'%%Pages')):
|
| 1417 |
+
pass
|
| 1418 |
+
else:
|
| 1419 |
+
write(line)
|
| 1420 |
+
# Now rewrite the rest of the file, and modify the trailer.
|
| 1421 |
+
# This is done in a second loop such that the header of the embedded
|
| 1422 |
+
# eps file is not modified.
|
| 1423 |
+
for line in tmph:
|
| 1424 |
+
if line.startswith(b'%%EOF'):
|
| 1425 |
+
write(b'cleartomark\n'
|
| 1426 |
+
b'countdictstack\n'
|
| 1427 |
+
b'exch sub { end } repeat\n'
|
| 1428 |
+
b'restore\n'
|
| 1429 |
+
b'showpage\n'
|
| 1430 |
+
b'%%EOF\n')
|
| 1431 |
+
elif line.startswith(b'%%PageBoundingBox'):
|
| 1432 |
+
pass
|
| 1433 |
+
else:
|
| 1434 |
+
write(line)
|
| 1435 |
+
|
| 1436 |
+
os.remove(tmpfile)
|
| 1437 |
+
shutil.move(epsfile, tmpfile)
|
| 1438 |
+
|
| 1439 |
+
|
| 1440 |
+
FigureManagerPS = FigureManagerBase
|
| 1441 |
+
|
| 1442 |
+
|
| 1443 |
+
# The following Python dictionary psDefs contains the entries for the
|
| 1444 |
+
# PostScript dictionary mpldict. This dictionary implements most of
|
| 1445 |
+
# the matplotlib primitives and some abbreviations.
|
| 1446 |
+
#
|
| 1447 |
+
# References:
|
| 1448 |
+
# https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
|
| 1449 |
+
# http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
|
| 1450 |
+
# http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
|
| 1451 |
+
#
|
| 1452 |
+
|
| 1453 |
+
# The usage comments use the notation of the operator summary
|
| 1454 |
+
# in the PostScript Language reference manual.
|
| 1455 |
+
_psDefs = [
|
| 1456 |
+
# name proc *_d* -
|
| 1457 |
+
# Note that this cannot be bound to /d, because when embedding a Type3 font
|
| 1458 |
+
# we may want to define a "d" glyph using "/d{...} d" which would locally
|
| 1459 |
+
# overwrite the definition.
|
| 1460 |
+
"/_d { bind def } bind def",
|
| 1461 |
+
# x y *m* -
|
| 1462 |
+
"/m { moveto } _d",
|
| 1463 |
+
# x y *l* -
|
| 1464 |
+
"/l { lineto } _d",
|
| 1465 |
+
# x y *r* -
|
| 1466 |
+
"/r { rlineto } _d",
|
| 1467 |
+
# x1 y1 x2 y2 x y *c* -
|
| 1468 |
+
"/c { curveto } _d",
|
| 1469 |
+
# *cl* -
|
| 1470 |
+
"/cl { closepath } _d",
|
| 1471 |
+
# *ce* -
|
| 1472 |
+
"/ce { closepath eofill } _d",
|
| 1473 |
+
# wx wy llx lly urx ury *setcachedevice* -
|
| 1474 |
+
"/sc { setcachedevice } _d",
|
| 1475 |
+
]
|
| 1476 |
+
|
| 1477 |
+
|
| 1478 |
+
@_Backend.export
|
| 1479 |
+
class _BackendPS(_Backend):
|
| 1480 |
+
backend_version = 'Level II'
|
| 1481 |
+
FigureCanvas = FigureCanvasPS
|
pace_revision_2/.venv-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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
|
| 6 |
+
import matplotlib as mpl
|
| 7 |
+
from matplotlib import _api, backend_tools, cbook
|
| 8 |
+
from matplotlib._pylab_helpers import Gcf
|
| 9 |
+
from matplotlib.backend_bases import (
|
| 10 |
+
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
|
| 11 |
+
TimerBase, cursors, ToolContainerBase, MouseButton,
|
| 12 |
+
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent,
|
| 13 |
+
_allow_interrupt)
|
| 14 |
+
import matplotlib.backends.qt_editor.figureoptions as figureoptions
|
| 15 |
+
from . import qt_compat
|
| 16 |
+
from .qt_compat import (
|
| 17 |
+
QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name
|
| 21 |
+
# instead they have manually specified names.
|
| 22 |
+
SPECIAL_KEYS = {
|
| 23 |
+
_to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [
|
| 24 |
+
("Key_Escape", "escape"),
|
| 25 |
+
("Key_Tab", "tab"),
|
| 26 |
+
("Key_Backspace", "backspace"),
|
| 27 |
+
("Key_Return", "enter"),
|
| 28 |
+
("Key_Enter", "enter"),
|
| 29 |
+
("Key_Insert", "insert"),
|
| 30 |
+
("Key_Delete", "delete"),
|
| 31 |
+
("Key_Pause", "pause"),
|
| 32 |
+
("Key_SysReq", "sysreq"),
|
| 33 |
+
("Key_Clear", "clear"),
|
| 34 |
+
("Key_Home", "home"),
|
| 35 |
+
("Key_End", "end"),
|
| 36 |
+
("Key_Left", "left"),
|
| 37 |
+
("Key_Up", "up"),
|
| 38 |
+
("Key_Right", "right"),
|
| 39 |
+
("Key_Down", "down"),
|
| 40 |
+
("Key_PageUp", "pageup"),
|
| 41 |
+
("Key_PageDown", "pagedown"),
|
| 42 |
+
("Key_Shift", "shift"),
|
| 43 |
+
# In macOS, the control and super (aka cmd/apple) keys are switched.
|
| 44 |
+
("Key_Control", "control" if sys.platform != "darwin" else "cmd"),
|
| 45 |
+
("Key_Meta", "meta" if sys.platform != "darwin" else "control"),
|
| 46 |
+
("Key_Alt", "alt"),
|
| 47 |
+
("Key_CapsLock", "caps_lock"),
|
| 48 |
+
("Key_F1", "f1"),
|
| 49 |
+
("Key_F2", "f2"),
|
| 50 |
+
("Key_F3", "f3"),
|
| 51 |
+
("Key_F4", "f4"),
|
| 52 |
+
("Key_F5", "f5"),
|
| 53 |
+
("Key_F6", "f6"),
|
| 54 |
+
("Key_F7", "f7"),
|
| 55 |
+
("Key_F8", "f8"),
|
| 56 |
+
("Key_F9", "f9"),
|
| 57 |
+
("Key_F10", "f10"),
|
| 58 |
+
("Key_F10", "f11"),
|
| 59 |
+
("Key_F12", "f12"),
|
| 60 |
+
("Key_Super_L", "super"),
|
| 61 |
+
("Key_Super_R", "super"),
|
| 62 |
+
]
|
| 63 |
+
}
|
| 64 |
+
# Define which modifier keys are collected on keyboard events.
|
| 65 |
+
# Elements are (Qt::KeyboardModifiers, Qt::Key) tuples.
|
| 66 |
+
# Order determines the modifier order (ctrl+alt+...) reported by Matplotlib.
|
| 67 |
+
_MODIFIER_KEYS = [
|
| 68 |
+
(_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)),
|
| 69 |
+
_to_int(getattr(QtCore.Qt.Key, key)))
|
| 70 |
+
for mod, key in [
|
| 71 |
+
("ControlModifier", "Key_Control"),
|
| 72 |
+
("AltModifier", "Key_Alt"),
|
| 73 |
+
("ShiftModifier", "Key_Shift"),
|
| 74 |
+
("MetaModifier", "Key_Meta"),
|
| 75 |
+
]
|
| 76 |
+
]
|
| 77 |
+
cursord = {
|
| 78 |
+
k: getattr(QtCore.Qt.CursorShape, v) for k, v in [
|
| 79 |
+
(cursors.MOVE, "SizeAllCursor"),
|
| 80 |
+
(cursors.HAND, "PointingHandCursor"),
|
| 81 |
+
(cursors.POINTER, "ArrowCursor"),
|
| 82 |
+
(cursors.SELECT_REGION, "CrossCursor"),
|
| 83 |
+
(cursors.WAIT, "WaitCursor"),
|
| 84 |
+
(cursors.RESIZE_HORIZONTAL, "SizeHorCursor"),
|
| 85 |
+
(cursors.RESIZE_VERTICAL, "SizeVerCursor"),
|
| 86 |
+
]
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# lru_cache keeps a reference to the QApplication instance, keeping it from
|
| 91 |
+
# being GC'd.
|
| 92 |
+
@functools.lru_cache(1)
|
| 93 |
+
def _create_qApp():
|
| 94 |
+
app = QtWidgets.QApplication.instance()
|
| 95 |
+
|
| 96 |
+
# Create a new QApplication and configure it if none exists yet, as only
|
| 97 |
+
# one QApplication can exist at a time.
|
| 98 |
+
if app is None:
|
| 99 |
+
# display_is_valid returns False only if on Linux and neither X11
|
| 100 |
+
# nor Wayland display can be opened.
|
| 101 |
+
if not mpl._c_internal_utils.display_is_valid():
|
| 102 |
+
raise RuntimeError('Invalid DISPLAY variable')
|
| 103 |
+
|
| 104 |
+
# Check to make sure a QApplication from a different major version
|
| 105 |
+
# of Qt is not instantiated in the process
|
| 106 |
+
if QT_API in {'PyQt6', 'PySide6'}:
|
| 107 |
+
other_bindings = ('PyQt5', 'PySide2')
|
| 108 |
+
qt_version = 6
|
| 109 |
+
elif QT_API in {'PyQt5', 'PySide2'}:
|
| 110 |
+
other_bindings = ('PyQt6', 'PySide6')
|
| 111 |
+
qt_version = 5
|
| 112 |
+
else:
|
| 113 |
+
raise RuntimeError("Should never be here")
|
| 114 |
+
|
| 115 |
+
for binding in other_bindings:
|
| 116 |
+
mod = sys.modules.get(f'{binding}.QtWidgets')
|
| 117 |
+
if mod is not None and mod.QApplication.instance() is not None:
|
| 118 |
+
other_core = sys.modules.get(f'{binding}.QtCore')
|
| 119 |
+
_api.warn_external(
|
| 120 |
+
f'Matplotlib is using {QT_API} which wraps '
|
| 121 |
+
f'{QtCore.qVersion()} however an instantiated '
|
| 122 |
+
f'QApplication from {binding} which wraps '
|
| 123 |
+
f'{other_core.qVersion()} exists. Mixing Qt major '
|
| 124 |
+
'versions may not work as expected.'
|
| 125 |
+
)
|
| 126 |
+
break
|
| 127 |
+
if qt_version == 5:
|
| 128 |
+
try:
|
| 129 |
+
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
|
| 130 |
+
except AttributeError: # Only for Qt>=5.6, <6.
|
| 131 |
+
pass
|
| 132 |
+
try:
|
| 133 |
+
QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(
|
| 134 |
+
QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
|
| 135 |
+
except AttributeError: # Only for Qt>=5.14.
|
| 136 |
+
pass
|
| 137 |
+
app = QtWidgets.QApplication(["matplotlib"])
|
| 138 |
+
if sys.platform == "darwin":
|
| 139 |
+
image = str(cbook._get_data_path('images/matplotlib.svg'))
|
| 140 |
+
icon = QtGui.QIcon(image)
|
| 141 |
+
app.setWindowIcon(icon)
|
| 142 |
+
app.setQuitOnLastWindowClosed(True)
|
| 143 |
+
cbook._setup_new_guiapp()
|
| 144 |
+
if qt_version == 5:
|
| 145 |
+
app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
|
| 146 |
+
|
| 147 |
+
return app
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _allow_interrupt_qt(qapp_or_eventloop):
|
| 151 |
+
"""A context manager that allows terminating a plot by sending a SIGINT."""
|
| 152 |
+
|
| 153 |
+
# Use QSocketNotifier to read the socketpair while the Qt event loop runs.
|
| 154 |
+
|
| 155 |
+
def prepare_notifier(rsock):
|
| 156 |
+
sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read)
|
| 157 |
+
|
| 158 |
+
@sn.activated.connect
|
| 159 |
+
def _may_clear_sock():
|
| 160 |
+
# Running a Python function on socket activation gives the interpreter a
|
| 161 |
+
# chance to handle the signal in Python land. We also need to drain the
|
| 162 |
+
# socket with recv() to re-arm it, because it will be written to as part of
|
| 163 |
+
# the wakeup. (We need this in case set_wakeup_fd catches a signal other
|
| 164 |
+
# than SIGINT and we shall continue waiting.)
|
| 165 |
+
try:
|
| 166 |
+
rsock.recv(1)
|
| 167 |
+
except BlockingIOError:
|
| 168 |
+
# This may occasionally fire too soon or more than once on Windows, so
|
| 169 |
+
# be forgiving about reading an empty socket.
|
| 170 |
+
pass
|
| 171 |
+
|
| 172 |
+
# We return the QSocketNotifier so that the caller holds a reference, and we
|
| 173 |
+
# also explicitly clean it up in handle_sigint(). Without doing both, deletion
|
| 174 |
+
# of the socket notifier can happen prematurely or not at all.
|
| 175 |
+
return sn
|
| 176 |
+
|
| 177 |
+
def handle_sigint(sn):
|
| 178 |
+
sn.deleteLater()
|
| 179 |
+
QtCore.QCoreApplication.sendPostedEvents(sn, QtCore.QEvent.Type.DeferredDelete)
|
| 180 |
+
if hasattr(qapp_or_eventloop, 'closeAllWindows'):
|
| 181 |
+
qapp_or_eventloop.closeAllWindows()
|
| 182 |
+
qapp_or_eventloop.quit()
|
| 183 |
+
|
| 184 |
+
return _allow_interrupt(prepare_notifier, handle_sigint)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class TimerQT(TimerBase):
|
| 188 |
+
"""Subclass of `.TimerBase` using QTimer events."""
|
| 189 |
+
|
| 190 |
+
def __init__(self, *args, **kwargs):
|
| 191 |
+
# Create a new timer and connect the timeout() signal to the
|
| 192 |
+
# _on_timer method.
|
| 193 |
+
self._timer = QtCore.QTimer()
|
| 194 |
+
self._timer.timeout.connect(self._on_timer)
|
| 195 |
+
super().__init__(*args, **kwargs)
|
| 196 |
+
|
| 197 |
+
def __del__(self):
|
| 198 |
+
# The check for deletedness is needed to avoid an error at animation
|
| 199 |
+
# shutdown with PySide2.
|
| 200 |
+
if not _isdeleted(self._timer):
|
| 201 |
+
self._timer_stop()
|
| 202 |
+
|
| 203 |
+
def _timer_set_single_shot(self):
|
| 204 |
+
self._timer.setSingleShot(self._single)
|
| 205 |
+
|
| 206 |
+
def _timer_set_interval(self):
|
| 207 |
+
self._timer.setInterval(self._interval)
|
| 208 |
+
|
| 209 |
+
def _timer_start(self):
|
| 210 |
+
self._timer.start()
|
| 211 |
+
|
| 212 |
+
def _timer_stop(self):
|
| 213 |
+
self._timer.stop()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget):
|
| 217 |
+
required_interactive_framework = "qt"
|
| 218 |
+
_timer_cls = TimerQT
|
| 219 |
+
manager_class = _api.classproperty(lambda cls: FigureManagerQT)
|
| 220 |
+
|
| 221 |
+
buttond = {
|
| 222 |
+
getattr(QtCore.Qt.MouseButton, k): v for k, v in [
|
| 223 |
+
("LeftButton", MouseButton.LEFT),
|
| 224 |
+
("RightButton", MouseButton.RIGHT),
|
| 225 |
+
("MiddleButton", MouseButton.MIDDLE),
|
| 226 |
+
("XButton1", MouseButton.BACK),
|
| 227 |
+
("XButton2", MouseButton.FORWARD),
|
| 228 |
+
]
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
def __init__(self, figure=None):
|
| 232 |
+
_create_qApp()
|
| 233 |
+
super().__init__(figure=figure)
|
| 234 |
+
|
| 235 |
+
self._draw_pending = False
|
| 236 |
+
self._is_drawing = False
|
| 237 |
+
self._draw_rect_callback = lambda painter: None
|
| 238 |
+
self._in_resize_event = False
|
| 239 |
+
|
| 240 |
+
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent)
|
| 241 |
+
self.setMouseTracking(True)
|
| 242 |
+
self.resize(*self.get_width_height())
|
| 243 |
+
|
| 244 |
+
palette = QtGui.QPalette(QtGui.QColor("white"))
|
| 245 |
+
self.setPalette(palette)
|
| 246 |
+
|
| 247 |
+
@QtCore.Slot()
|
| 248 |
+
def _update_pixel_ratio(self):
|
| 249 |
+
if self._set_device_pixel_ratio(
|
| 250 |
+
self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0
|
| 251 |
+
# The easiest way to resize the canvas is to emit a resizeEvent
|
| 252 |
+
# since we implement all the logic for resizing the canvas for
|
| 253 |
+
# that event.
|
| 254 |
+
event = QtGui.QResizeEvent(self.size(), self.size())
|
| 255 |
+
self.resizeEvent(event)
|
| 256 |
+
|
| 257 |
+
@QtCore.Slot(QtGui.QScreen)
|
| 258 |
+
def _update_screen(self, screen):
|
| 259 |
+
# Handler for changes to a window's attached screen.
|
| 260 |
+
self._update_pixel_ratio()
|
| 261 |
+
if screen is not None:
|
| 262 |
+
screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio)
|
| 263 |
+
screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio)
|
| 264 |
+
|
| 265 |
+
def eventFilter(self, source, event):
|
| 266 |
+
if event.type() == QtCore.QEvent.Type.DevicePixelRatioChange:
|
| 267 |
+
self._update_pixel_ratio()
|
| 268 |
+
return super().eventFilter(source, event)
|
| 269 |
+
|
| 270 |
+
def showEvent(self, event):
|
| 271 |
+
# Set up correct pixel ratio, and connect to any signal changes for it,
|
| 272 |
+
# once the window is shown (and thus has these attributes).
|
| 273 |
+
window = self.window().windowHandle()
|
| 274 |
+
current_version = tuple(int(x) for x in QtCore.qVersion().split('.', 2)[:2])
|
| 275 |
+
if current_version >= (6, 6):
|
| 276 |
+
self._update_pixel_ratio()
|
| 277 |
+
window.installEventFilter(self)
|
| 278 |
+
else:
|
| 279 |
+
window.screenChanged.connect(self._update_screen)
|
| 280 |
+
self._update_screen(window.screen())
|
| 281 |
+
|
| 282 |
+
def set_cursor(self, cursor):
|
| 283 |
+
# docstring inherited
|
| 284 |
+
self.setCursor(_api.check_getitem(cursord, cursor=cursor))
|
| 285 |
+
|
| 286 |
+
def mouseEventCoords(self, pos=None):
|
| 287 |
+
"""
|
| 288 |
+
Calculate mouse coordinates in physical pixels.
|
| 289 |
+
|
| 290 |
+
Qt uses logical pixels, but the figure is scaled to physical
|
| 291 |
+
pixels for rendering. Transform to physical pixels so that
|
| 292 |
+
all of the down-stream transforms work as expected.
|
| 293 |
+
|
| 294 |
+
Also, the origin is different and needs to be corrected.
|
| 295 |
+
"""
|
| 296 |
+
if pos is None:
|
| 297 |
+
pos = self.mapFromGlobal(QtGui.QCursor.pos())
|
| 298 |
+
elif hasattr(pos, "position"): # qt6 QtGui.QEvent
|
| 299 |
+
pos = pos.position()
|
| 300 |
+
elif hasattr(pos, "pos"): # qt5 QtCore.QEvent
|
| 301 |
+
pos = pos.pos()
|
| 302 |
+
# (otherwise, it's already a QPoint)
|
| 303 |
+
x = pos.x()
|
| 304 |
+
# flip y so y=0 is bottom of canvas
|
| 305 |
+
y = self.figure.bbox.height / self.device_pixel_ratio - pos.y()
|
| 306 |
+
return x * self.device_pixel_ratio, y * self.device_pixel_ratio
|
| 307 |
+
|
| 308 |
+
def enterEvent(self, event):
|
| 309 |
+
# Force querying of the modifiers, as the cached modifier state can
|
| 310 |
+
# have been invalidated while the window was out of focus.
|
| 311 |
+
mods = QtWidgets.QApplication.instance().queryKeyboardModifiers()
|
| 312 |
+
if self.figure is None:
|
| 313 |
+
return
|
| 314 |
+
LocationEvent("figure_enter_event", self,
|
| 315 |
+
*self.mouseEventCoords(event),
|
| 316 |
+
modifiers=self._mpl_modifiers(mods),
|
| 317 |
+
guiEvent=event)._process()
|
| 318 |
+
|
| 319 |
+
def leaveEvent(self, event):
|
| 320 |
+
QtWidgets.QApplication.restoreOverrideCursor()
|
| 321 |
+
if self.figure is None:
|
| 322 |
+
return
|
| 323 |
+
LocationEvent("figure_leave_event", self,
|
| 324 |
+
*self.mouseEventCoords(),
|
| 325 |
+
modifiers=self._mpl_modifiers(),
|
| 326 |
+
guiEvent=event)._process()
|
| 327 |
+
|
| 328 |
+
def mousePressEvent(self, event):
|
| 329 |
+
button = self.buttond.get(event.button())
|
| 330 |
+
if button is not None and self.figure is not None:
|
| 331 |
+
MouseEvent("button_press_event", self,
|
| 332 |
+
*self.mouseEventCoords(event), button,
|
| 333 |
+
modifiers=self._mpl_modifiers(),
|
| 334 |
+
guiEvent=event)._process()
|
| 335 |
+
|
| 336 |
+
def mouseDoubleClickEvent(self, event):
|
| 337 |
+
button = self.buttond.get(event.button())
|
| 338 |
+
if button is not None and self.figure is not None:
|
| 339 |
+
MouseEvent("button_press_event", self,
|
| 340 |
+
*self.mouseEventCoords(event), button, dblclick=True,
|
| 341 |
+
modifiers=self._mpl_modifiers(),
|
| 342 |
+
guiEvent=event)._process()
|
| 343 |
+
|
| 344 |
+
def mouseMoveEvent(self, event):
|
| 345 |
+
if self.figure is None:
|
| 346 |
+
return
|
| 347 |
+
MouseEvent("motion_notify_event", self,
|
| 348 |
+
*self.mouseEventCoords(event),
|
| 349 |
+
buttons=self._mpl_buttons(event.buttons()),
|
| 350 |
+
modifiers=self._mpl_modifiers(),
|
| 351 |
+
guiEvent=event)._process()
|
| 352 |
+
|
| 353 |
+
def mouseReleaseEvent(self, event):
|
| 354 |
+
button = self.buttond.get(event.button())
|
| 355 |
+
if button is not None and self.figure is not None:
|
| 356 |
+
MouseEvent("button_release_event", self,
|
| 357 |
+
*self.mouseEventCoords(event), button,
|
| 358 |
+
modifiers=self._mpl_modifiers(),
|
| 359 |
+
guiEvent=event)._process()
|
| 360 |
+
|
| 361 |
+
def wheelEvent(self, event):
|
| 362 |
+
# from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not
|
| 363 |
+
# provided (`isNull()`) and is unreliable on X11 ("xcb").
|
| 364 |
+
if (event.pixelDelta().isNull()
|
| 365 |
+
or QtWidgets.QApplication.instance().platformName() == "xcb"):
|
| 366 |
+
steps = event.angleDelta().y() / 120
|
| 367 |
+
else:
|
| 368 |
+
steps = event.pixelDelta().y()
|
| 369 |
+
if steps and self.figure is not None:
|
| 370 |
+
MouseEvent("scroll_event", self,
|
| 371 |
+
*self.mouseEventCoords(event), step=steps,
|
| 372 |
+
modifiers=self._mpl_modifiers(),
|
| 373 |
+
guiEvent=event)._process()
|
| 374 |
+
|
| 375 |
+
def keyPressEvent(self, event):
|
| 376 |
+
key = self._get_key(event)
|
| 377 |
+
if key is not None and self.figure is not None:
|
| 378 |
+
KeyEvent("key_press_event", self,
|
| 379 |
+
key, *self.mouseEventCoords(),
|
| 380 |
+
guiEvent=event)._process()
|
| 381 |
+
|
| 382 |
+
def keyReleaseEvent(self, event):
|
| 383 |
+
key = self._get_key(event)
|
| 384 |
+
if key is not None and self.figure is not None:
|
| 385 |
+
KeyEvent("key_release_event", self,
|
| 386 |
+
key, *self.mouseEventCoords(),
|
| 387 |
+
guiEvent=event)._process()
|
| 388 |
+
|
| 389 |
+
def resizeEvent(self, event):
|
| 390 |
+
if self._in_resize_event: # Prevent PyQt6 recursion
|
| 391 |
+
return
|
| 392 |
+
if self.figure is None:
|
| 393 |
+
return
|
| 394 |
+
self._in_resize_event = True
|
| 395 |
+
try:
|
| 396 |
+
w = event.size().width() * self.device_pixel_ratio
|
| 397 |
+
h = event.size().height() * self.device_pixel_ratio
|
| 398 |
+
dpival = self.figure.dpi
|
| 399 |
+
winch = w / dpival
|
| 400 |
+
hinch = h / dpival
|
| 401 |
+
self.figure.set_size_inches(winch, hinch, forward=False)
|
| 402 |
+
# pass back into Qt to let it finish
|
| 403 |
+
QtWidgets.QWidget.resizeEvent(self, event)
|
| 404 |
+
# emit our resize events
|
| 405 |
+
ResizeEvent("resize_event", self)._process()
|
| 406 |
+
self.draw_idle()
|
| 407 |
+
finally:
|
| 408 |
+
self._in_resize_event = False
|
| 409 |
+
|
| 410 |
+
def sizeHint(self):
|
| 411 |
+
w, h = self.get_width_height()
|
| 412 |
+
return QtCore.QSize(w, h)
|
| 413 |
+
|
| 414 |
+
def minimumSizeHint(self):
|
| 415 |
+
return QtCore.QSize(10, 10)
|
| 416 |
+
|
| 417 |
+
@staticmethod
|
| 418 |
+
def _mpl_buttons(buttons):
|
| 419 |
+
buttons = _to_int(buttons)
|
| 420 |
+
# State *after* press/release.
|
| 421 |
+
return {button for mask, button in FigureCanvasQT.buttond.items()
|
| 422 |
+
if _to_int(mask) & buttons}
|
| 423 |
+
|
| 424 |
+
@staticmethod
|
| 425 |
+
def _mpl_modifiers(modifiers=None, *, exclude=None):
|
| 426 |
+
if modifiers is None:
|
| 427 |
+
modifiers = QtWidgets.QApplication.instance().keyboardModifiers()
|
| 428 |
+
modifiers = _to_int(modifiers)
|
| 429 |
+
# get names of the pressed modifier keys
|
| 430 |
+
# 'control' is named 'control' when a standalone key, but 'ctrl' when a
|
| 431 |
+
# modifier
|
| 432 |
+
# bit twiddling to pick out modifier keys from modifiers bitmask,
|
| 433 |
+
# if exclude is a MODIFIER, it should not be duplicated in mods
|
| 434 |
+
return [SPECIAL_KEYS[key].replace('control', 'ctrl')
|
| 435 |
+
for mask, key in _MODIFIER_KEYS
|
| 436 |
+
if exclude != key and modifiers & mask]
|
| 437 |
+
|
| 438 |
+
def _get_key(self, event):
|
| 439 |
+
event_key = event.key()
|
| 440 |
+
mods = self._mpl_modifiers(exclude=event_key)
|
| 441 |
+
try:
|
| 442 |
+
# for certain keys (enter, left, backspace, etc) use a word for the
|
| 443 |
+
# key, rather than Unicode
|
| 444 |
+
key = SPECIAL_KEYS[event_key]
|
| 445 |
+
except KeyError:
|
| 446 |
+
# Unicode defines code points up to 0x10ffff (sys.maxunicode)
|
| 447 |
+
# QT will use Key_Codes larger than that for keyboard keys that are
|
| 448 |
+
# not Unicode characters (like multimedia keys)
|
| 449 |
+
# skip these
|
| 450 |
+
# if you really want them, you should add them to SPECIAL_KEYS
|
| 451 |
+
if event_key > sys.maxunicode:
|
| 452 |
+
return None
|
| 453 |
+
|
| 454 |
+
key = chr(event_key)
|
| 455 |
+
# qt delivers capitalized letters. fix capitalization
|
| 456 |
+
# note that capslock is ignored
|
| 457 |
+
if 'shift' in mods:
|
| 458 |
+
mods.remove('shift')
|
| 459 |
+
else:
|
| 460 |
+
key = key.lower()
|
| 461 |
+
|
| 462 |
+
return '+'.join(mods + [key])
|
| 463 |
+
|
| 464 |
+
def flush_events(self):
|
| 465 |
+
# docstring inherited
|
| 466 |
+
QtWidgets.QApplication.instance().processEvents()
|
| 467 |
+
|
| 468 |
+
def start_event_loop(self, timeout=0):
|
| 469 |
+
# docstring inherited
|
| 470 |
+
if hasattr(self, "_event_loop") and self._event_loop.isRunning():
|
| 471 |
+
raise RuntimeError("Event loop already running")
|
| 472 |
+
self._event_loop = event_loop = QtCore.QEventLoop()
|
| 473 |
+
if timeout > 0:
|
| 474 |
+
_ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit)
|
| 475 |
+
|
| 476 |
+
with _allow_interrupt_qt(event_loop):
|
| 477 |
+
qt_compat._exec(event_loop)
|
| 478 |
+
|
| 479 |
+
def stop_event_loop(self, event=None):
|
| 480 |
+
# docstring inherited
|
| 481 |
+
if hasattr(self, "_event_loop"):
|
| 482 |
+
self._event_loop.quit()
|
| 483 |
+
|
| 484 |
+
def draw(self):
|
| 485 |
+
"""Render the figure, and queue a request for a Qt draw."""
|
| 486 |
+
# The renderer draw is done here; delaying causes problems with code
|
| 487 |
+
# that uses the result of the draw() to update plot elements.
|
| 488 |
+
if self._is_drawing:
|
| 489 |
+
return
|
| 490 |
+
with cbook._setattr_cm(self, _is_drawing=True):
|
| 491 |
+
super().draw()
|
| 492 |
+
self.update()
|
| 493 |
+
|
| 494 |
+
def draw_idle(self):
|
| 495 |
+
"""Queue redraw of the Agg buffer and request Qt paintEvent."""
|
| 496 |
+
# The Agg draw needs to be handled by the same thread Matplotlib
|
| 497 |
+
# modifies the scene graph from. Post Agg draw request to the
|
| 498 |
+
# current event loop in order to ensure thread affinity and to
|
| 499 |
+
# accumulate multiple draw requests from event handling.
|
| 500 |
+
# TODO: queued signal connection might be safer than singleShot
|
| 501 |
+
if not (getattr(self, '_draw_pending', False) or
|
| 502 |
+
getattr(self, '_is_drawing', False)):
|
| 503 |
+
self._draw_pending = True
|
| 504 |
+
QtCore.QTimer.singleShot(0, self._draw_idle)
|
| 505 |
+
|
| 506 |
+
def blit(self, bbox=None):
|
| 507 |
+
# docstring inherited
|
| 508 |
+
if bbox is None and self.figure:
|
| 509 |
+
bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
|
| 510 |
+
# repaint uses logical pixels, not physical pixels like the renderer.
|
| 511 |
+
l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds)
|
| 512 |
+
t = b + h
|
| 513 |
+
self.repaint(l, self.rect().height() - t, w, h)
|
| 514 |
+
|
| 515 |
+
def _draw_idle(self):
|
| 516 |
+
with self._idle_draw_cntx():
|
| 517 |
+
if not self._draw_pending:
|
| 518 |
+
return
|
| 519 |
+
self._draw_pending = False
|
| 520 |
+
if _isdeleted(self) or self.height() <= 0 or self.width() <= 0:
|
| 521 |
+
return
|
| 522 |
+
try:
|
| 523 |
+
self.draw()
|
| 524 |
+
except Exception:
|
| 525 |
+
# Uncaught exceptions are fatal for PyQt5, so catch them.
|
| 526 |
+
traceback.print_exc()
|
| 527 |
+
|
| 528 |
+
def drawRectangle(self, rect):
|
| 529 |
+
# Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
|
| 530 |
+
# to be called at the end of paintEvent.
|
| 531 |
+
if rect is not None:
|
| 532 |
+
x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect)
|
| 533 |
+
x1 = x0 + w
|
| 534 |
+
y1 = y0 + h
|
| 535 |
+
def _draw_rect_callback(painter):
|
| 536 |
+
pen = QtGui.QPen(
|
| 537 |
+
QtGui.QColor("black"),
|
| 538 |
+
1 / self.device_pixel_ratio
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
pen.setDashPattern([3, 3])
|
| 542 |
+
for color, offset in [
|
| 543 |
+
(QtGui.QColor("black"), 0),
|
| 544 |
+
(QtGui.QColor("white"), 3),
|
| 545 |
+
]:
|
| 546 |
+
pen.setDashOffset(offset)
|
| 547 |
+
pen.setColor(color)
|
| 548 |
+
painter.setPen(pen)
|
| 549 |
+
# Draw the lines from x0, y0 towards x1, y1 so that the
|
| 550 |
+
# dashes don't "jump" when moving the zoom box.
|
| 551 |
+
painter.drawLine(x0, y0, x0, y1)
|
| 552 |
+
painter.drawLine(x0, y0, x1, y0)
|
| 553 |
+
painter.drawLine(x0, y1, x1, y1)
|
| 554 |
+
painter.drawLine(x1, y0, x1, y1)
|
| 555 |
+
else:
|
| 556 |
+
def _draw_rect_callback(painter):
|
| 557 |
+
return
|
| 558 |
+
self._draw_rect_callback = _draw_rect_callback
|
| 559 |
+
self.update()
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class MainWindow(QtWidgets.QMainWindow):
|
| 563 |
+
closing = QtCore.Signal()
|
| 564 |
+
|
| 565 |
+
def closeEvent(self, event):
|
| 566 |
+
self.closing.emit()
|
| 567 |
+
super().closeEvent(event)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class FigureManagerQT(FigureManagerBase):
|
| 571 |
+
"""
|
| 572 |
+
Attributes
|
| 573 |
+
----------
|
| 574 |
+
canvas : `FigureCanvas`
|
| 575 |
+
The FigureCanvas instance
|
| 576 |
+
num : int or str
|
| 577 |
+
The Figure number
|
| 578 |
+
toolbar : qt.QToolBar
|
| 579 |
+
The qt.QToolBar
|
| 580 |
+
window : qt.QMainWindow
|
| 581 |
+
The qt.QMainWindow
|
| 582 |
+
"""
|
| 583 |
+
|
| 584 |
+
def __init__(self, canvas, num):
|
| 585 |
+
self.window = MainWindow()
|
| 586 |
+
super().__init__(canvas, num)
|
| 587 |
+
self.window.closing.connect(self._widgetclosed)
|
| 588 |
+
|
| 589 |
+
if sys.platform != "darwin":
|
| 590 |
+
image = str(cbook._get_data_path('images/matplotlib.svg'))
|
| 591 |
+
icon = QtGui.QIcon(image)
|
| 592 |
+
self.window.setWindowIcon(icon)
|
| 593 |
+
|
| 594 |
+
self.window._destroying = False
|
| 595 |
+
|
| 596 |
+
if self.toolbar:
|
| 597 |
+
self.window.addToolBar(self.toolbar)
|
| 598 |
+
tbs_height = self.toolbar.sizeHint().height()
|
| 599 |
+
else:
|
| 600 |
+
tbs_height = 0
|
| 601 |
+
|
| 602 |
+
# resize the main window so it will display the canvas with the
|
| 603 |
+
# requested size:
|
| 604 |
+
cs = canvas.sizeHint()
|
| 605 |
+
cs_height = cs.height()
|
| 606 |
+
height = cs_height + tbs_height
|
| 607 |
+
self.window.resize(cs.width(), height)
|
| 608 |
+
|
| 609 |
+
self.window.setCentralWidget(self.canvas)
|
| 610 |
+
|
| 611 |
+
if mpl.is_interactive():
|
| 612 |
+
self.window.show()
|
| 613 |
+
self.canvas.draw_idle()
|
| 614 |
+
|
| 615 |
+
# Give the keyboard focus to the figure instead of the manager:
|
| 616 |
+
# StrongFocus accepts both tab and click to focus and will enable the
|
| 617 |
+
# canvas to process event without clicking.
|
| 618 |
+
# https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum
|
| 619 |
+
self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
|
| 620 |
+
self.canvas.setFocus()
|
| 621 |
+
|
| 622 |
+
self.window.raise_()
|
| 623 |
+
|
| 624 |
+
def full_screen_toggle(self):
|
| 625 |
+
if self.window.isFullScreen():
|
| 626 |
+
self.window.showNormal()
|
| 627 |
+
else:
|
| 628 |
+
self.window.showFullScreen()
|
| 629 |
+
|
| 630 |
+
def _widgetclosed(self):
|
| 631 |
+
CloseEvent("close_event", self.canvas)._process()
|
| 632 |
+
if self.window._destroying:
|
| 633 |
+
return
|
| 634 |
+
self.window._destroying = True
|
| 635 |
+
try:
|
| 636 |
+
Gcf.destroy(self)
|
| 637 |
+
except AttributeError:
|
| 638 |
+
pass
|
| 639 |
+
# It seems that when the python session is killed,
|
| 640 |
+
# Gcf can get destroyed before the Gcf.destroy
|
| 641 |
+
# line is run, leading to a useless AttributeError.
|
| 642 |
+
|
| 643 |
+
def resize(self, width, height):
|
| 644 |
+
# The Qt methods return sizes in 'virtual' pixels so we do need to
|
| 645 |
+
# rescale from physical to logical pixels.
|
| 646 |
+
width = int(width / self.canvas.device_pixel_ratio)
|
| 647 |
+
height = int(height / self.canvas.device_pixel_ratio)
|
| 648 |
+
extra_width = self.window.width() - self.canvas.width()
|
| 649 |
+
extra_height = self.window.height() - self.canvas.height()
|
| 650 |
+
self.canvas.resize(width, height)
|
| 651 |
+
self.window.resize(width + extra_width, height + extra_height)
|
| 652 |
+
|
| 653 |
+
@classmethod
|
| 654 |
+
def start_main_loop(cls):
|
| 655 |
+
qapp = QtWidgets.QApplication.instance()
|
| 656 |
+
if qapp:
|
| 657 |
+
with _allow_interrupt_qt(qapp):
|
| 658 |
+
qt_compat._exec(qapp)
|
| 659 |
+
|
| 660 |
+
def show(self):
|
| 661 |
+
self.window._destroying = False
|
| 662 |
+
self.window.show()
|
| 663 |
+
if mpl.rcParams['figure.raise_window']:
|
| 664 |
+
self.window.activateWindow()
|
| 665 |
+
self.window.raise_()
|
| 666 |
+
|
| 667 |
+
def destroy(self, *args):
|
| 668 |
+
# check for qApp first, as PySide deletes it in its atexit handler
|
| 669 |
+
if QtWidgets.QApplication.instance() is None:
|
| 670 |
+
return
|
| 671 |
+
if self.window._destroying:
|
| 672 |
+
return
|
| 673 |
+
self.window._destroying = True
|
| 674 |
+
if self.toolbar:
|
| 675 |
+
self.toolbar.destroy()
|
| 676 |
+
self.window.close()
|
| 677 |
+
|
| 678 |
+
def get_window_title(self):
|
| 679 |
+
return self.window.windowTitle()
|
| 680 |
+
|
| 681 |
+
def set_window_title(self, title):
|
| 682 |
+
self.window.setWindowTitle(title)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar):
|
| 686 |
+
toolitems = [*NavigationToolbar2.toolitems]
|
| 687 |
+
toolitems.insert(
|
| 688 |
+
# Add 'customize' action after 'subplots'
|
| 689 |
+
[name for name, *_ in toolitems].index("Subplots") + 1,
|
| 690 |
+
("Customize", "Edit axis, curve and image parameters",
|
| 691 |
+
"qt4_editor_options", "edit_parameters"))
|
| 692 |
+
|
| 693 |
+
def __init__(self, canvas, parent=None, coordinates=True):
|
| 694 |
+
"""coordinates: should we show the coordinates on the right?"""
|
| 695 |
+
QtWidgets.QToolBar.__init__(self, parent)
|
| 696 |
+
self.setAllowedAreas(QtCore.Qt.ToolBarArea(
|
| 697 |
+
_to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
|
| 698 |
+
_to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
|
| 699 |
+
self.coordinates = coordinates
|
| 700 |
+
self._actions = {} # mapping of toolitem method names to QActions.
|
| 701 |
+
self._subplot_dialog = None
|
| 702 |
+
|
| 703 |
+
for text, tooltip_text, image_file, callback in self.toolitems:
|
| 704 |
+
if text is None:
|
| 705 |
+
self.addSeparator()
|
| 706 |
+
else:
|
| 707 |
+
slot = getattr(self, callback)
|
| 708 |
+
# https://bugreports.qt.io/browse/PYSIDE-2512
|
| 709 |
+
slot = functools.wraps(slot)(functools.partial(slot))
|
| 710 |
+
slot = QtCore.Slot()(slot)
|
| 711 |
+
|
| 712 |
+
a = self.addAction(self._icon(image_file + '.png'),
|
| 713 |
+
text, slot)
|
| 714 |
+
self._actions[callback] = a
|
| 715 |
+
if callback in ['zoom', 'pan']:
|
| 716 |
+
a.setCheckable(True)
|
| 717 |
+
if tooltip_text is not None:
|
| 718 |
+
a.setToolTip(tooltip_text)
|
| 719 |
+
|
| 720 |
+
# Add the (x, y) location widget at the right side of the toolbar
|
| 721 |
+
# The stretch factor is 1 which means any resizing of the toolbar
|
| 722 |
+
# will resize this label instead of the buttons.
|
| 723 |
+
if self.coordinates:
|
| 724 |
+
self.locLabel = QtWidgets.QLabel("", self)
|
| 725 |
+
self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag(
|
| 726 |
+
_to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
|
| 727 |
+
_to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
|
| 728 |
+
|
| 729 |
+
self.locLabel.setSizePolicy(QtWidgets.QSizePolicy(
|
| 730 |
+
QtWidgets.QSizePolicy.Policy.Expanding,
|
| 731 |
+
QtWidgets.QSizePolicy.Policy.Ignored,
|
| 732 |
+
))
|
| 733 |
+
labelAction = self.addWidget(self.locLabel)
|
| 734 |
+
labelAction.setVisible(True)
|
| 735 |
+
|
| 736 |
+
NavigationToolbar2.__init__(self, canvas)
|
| 737 |
+
|
| 738 |
+
def _icon(self, name):
|
| 739 |
+
"""
|
| 740 |
+
Construct a `.QIcon` from an image file *name*, including the extension
|
| 741 |
+
and relative to Matplotlib's "images" data directory.
|
| 742 |
+
"""
|
| 743 |
+
# use a high-resolution icon with suffix '_large' if available
|
| 744 |
+
# note: user-provided icons may not have '_large' versions
|
| 745 |
+
path_regular = cbook._get_data_path('images', name)
|
| 746 |
+
path_large = path_regular.with_name(
|
| 747 |
+
path_regular.name.replace('.png', '_large.png'))
|
| 748 |
+
filename = str(path_large if path_large.exists() else path_regular)
|
| 749 |
+
|
| 750 |
+
pm = QtGui.QPixmap(filename)
|
| 751 |
+
pm.setDevicePixelRatio(
|
| 752 |
+
self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0
|
| 753 |
+
if self.palette().color(self.backgroundRole()).value() < 128:
|
| 754 |
+
icon_color = self.palette().color(self.foregroundRole())
|
| 755 |
+
mask = pm.createMaskFromColor(
|
| 756 |
+
QtGui.QColor('black'),
|
| 757 |
+
QtCore.Qt.MaskMode.MaskOutColor)
|
| 758 |
+
pm.fill(icon_color)
|
| 759 |
+
pm.setMask(mask)
|
| 760 |
+
return QtGui.QIcon(pm)
|
| 761 |
+
|
| 762 |
+
def edit_parameters(self):
|
| 763 |
+
axes = self.canvas.figure.get_axes()
|
| 764 |
+
if not axes:
|
| 765 |
+
QtWidgets.QMessageBox.warning(
|
| 766 |
+
self.canvas.parent(), "Error", "There are no Axes to edit.")
|
| 767 |
+
return
|
| 768 |
+
elif len(axes) == 1:
|
| 769 |
+
ax, = axes
|
| 770 |
+
else:
|
| 771 |
+
titles = [
|
| 772 |
+
ax.get_label() or
|
| 773 |
+
ax.get_title() or
|
| 774 |
+
ax.get_title("left") or
|
| 775 |
+
ax.get_title("right") or
|
| 776 |
+
" - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
|
| 777 |
+
f"<anonymous {type(ax).__name__}>"
|
| 778 |
+
for ax in axes]
|
| 779 |
+
duplicate_titles = [
|
| 780 |
+
title for title in titles if titles.count(title) > 1]
|
| 781 |
+
for i, ax in enumerate(axes):
|
| 782 |
+
if titles[i] in duplicate_titles:
|
| 783 |
+
titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles.
|
| 784 |
+
item, ok = QtWidgets.QInputDialog.getItem(
|
| 785 |
+
self.canvas.parent(),
|
| 786 |
+
'Customize', 'Select Axes:', titles, 0, False)
|
| 787 |
+
if not ok:
|
| 788 |
+
return
|
| 789 |
+
ax = axes[titles.index(item)]
|
| 790 |
+
figureoptions.figure_edit(ax, self)
|
| 791 |
+
|
| 792 |
+
def _update_buttons_checked(self):
|
| 793 |
+
# sync button checkstates to match active mode
|
| 794 |
+
if 'pan' in self._actions:
|
| 795 |
+
self._actions['pan'].setChecked(self.mode.name == 'PAN')
|
| 796 |
+
if 'zoom' in self._actions:
|
| 797 |
+
self._actions['zoom'].setChecked(self.mode.name == 'ZOOM')
|
| 798 |
+
|
| 799 |
+
def pan(self, *args):
|
| 800 |
+
super().pan(*args)
|
| 801 |
+
self._update_buttons_checked()
|
| 802 |
+
|
| 803 |
+
def zoom(self, *args):
|
| 804 |
+
super().zoom(*args)
|
| 805 |
+
self._update_buttons_checked()
|
| 806 |
+
|
| 807 |
+
def set_message(self, s):
|
| 808 |
+
if self.coordinates:
|
| 809 |
+
self.locLabel.setText(s)
|
| 810 |
+
|
| 811 |
+
def draw_rubberband(self, event, x0, y0, x1, y1):
|
| 812 |
+
height = self.canvas.figure.bbox.height
|
| 813 |
+
y1 = height - y1
|
| 814 |
+
y0 = height - y0
|
| 815 |
+
rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
|
| 816 |
+
self.canvas.drawRectangle(rect)
|
| 817 |
+
|
| 818 |
+
def remove_rubberband(self):
|
| 819 |
+
self.canvas.drawRectangle(None)
|
| 820 |
+
|
| 821 |
+
def configure_subplots(self):
|
| 822 |
+
if self._subplot_dialog is None:
|
| 823 |
+
self._subplot_dialog = SubplotToolQt(
|
| 824 |
+
self.canvas.figure, self.canvas.parent())
|
| 825 |
+
self.canvas.mpl_connect(
|
| 826 |
+
"close_event", lambda e: self._subplot_dialog.reject())
|
| 827 |
+
self._subplot_dialog.update_from_current_subplotpars()
|
| 828 |
+
self._subplot_dialog.setModal(True)
|
| 829 |
+
self._subplot_dialog.show()
|
| 830 |
+
return self._subplot_dialog
|
| 831 |
+
|
| 832 |
+
def save_figure(self, *args):
|
| 833 |
+
filetypes = self.canvas.get_supported_filetypes_grouped()
|
| 834 |
+
sorted_filetypes = sorted(filetypes.items())
|
| 835 |
+
default_filetype = self.canvas.get_default_filetype()
|
| 836 |
+
|
| 837 |
+
startpath = os.path.expanduser(mpl.rcParams['savefig.directory'])
|
| 838 |
+
start = os.path.join(startpath, self.canvas.get_default_filename())
|
| 839 |
+
filters = []
|
| 840 |
+
selectedFilter = None
|
| 841 |
+
for name, exts in sorted_filetypes:
|
| 842 |
+
exts_list = " ".join(['*.%s' % ext for ext in exts])
|
| 843 |
+
filter = f'{name} ({exts_list})'
|
| 844 |
+
if default_filetype in exts:
|
| 845 |
+
selectedFilter = filter
|
| 846 |
+
filters.append(filter)
|
| 847 |
+
filters = ';;'.join(filters)
|
| 848 |
+
|
| 849 |
+
fname, filter = QtWidgets.QFileDialog.getSaveFileName(
|
| 850 |
+
self.canvas.parent(), "Choose a filename to save to", start,
|
| 851 |
+
filters, selectedFilter)
|
| 852 |
+
if fname:
|
| 853 |
+
# Save dir for next time, unless empty str (i.e., use cwd).
|
| 854 |
+
if startpath != "":
|
| 855 |
+
mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
|
| 856 |
+
try:
|
| 857 |
+
self.canvas.figure.savefig(fname)
|
| 858 |
+
except Exception as e:
|
| 859 |
+
QtWidgets.QMessageBox.critical(
|
| 860 |
+
self, "Error saving file", str(e),
|
| 861 |
+
QtWidgets.QMessageBox.StandardButton.Ok,
|
| 862 |
+
QtWidgets.QMessageBox.StandardButton.NoButton)
|
| 863 |
+
return fname
|
| 864 |
+
|
| 865 |
+
def set_history_buttons(self):
|
| 866 |
+
can_backward = self._nav_stack._pos > 0
|
| 867 |
+
can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
|
| 868 |
+
if 'back' in self._actions:
|
| 869 |
+
self._actions['back'].setEnabled(can_backward)
|
| 870 |
+
if 'forward' in self._actions:
|
| 871 |
+
self._actions['forward'].setEnabled(can_forward)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
class SubplotToolQt(QtWidgets.QDialog):
|
| 875 |
+
def __init__(self, targetfig, parent):
|
| 876 |
+
super().__init__(parent)
|
| 877 |
+
self.setWindowIcon(QtGui.QIcon(
|
| 878 |
+
str(cbook._get_data_path("images/matplotlib.png"))))
|
| 879 |
+
self.setObjectName("SubplotTool")
|
| 880 |
+
self._spinboxes = {}
|
| 881 |
+
main_layout = QtWidgets.QHBoxLayout()
|
| 882 |
+
self.setLayout(main_layout)
|
| 883 |
+
for group, spinboxes, buttons in [
|
| 884 |
+
("Borders",
|
| 885 |
+
["top", "bottom", "left", "right"],
|
| 886 |
+
[("Export values", self._export_values)]),
|
| 887 |
+
("Spacings",
|
| 888 |
+
["hspace", "wspace"],
|
| 889 |
+
[("Tight layout", self._tight_layout),
|
| 890 |
+
("Reset", self._reset),
|
| 891 |
+
("Close", self.close)])]:
|
| 892 |
+
layout = QtWidgets.QVBoxLayout()
|
| 893 |
+
main_layout.addLayout(layout)
|
| 894 |
+
box = QtWidgets.QGroupBox(group)
|
| 895 |
+
layout.addWidget(box)
|
| 896 |
+
inner = QtWidgets.QFormLayout(box)
|
| 897 |
+
for name in spinboxes:
|
| 898 |
+
self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox()
|
| 899 |
+
spinbox.setRange(0, 1)
|
| 900 |
+
spinbox.setDecimals(3)
|
| 901 |
+
spinbox.setSingleStep(0.005)
|
| 902 |
+
spinbox.setKeyboardTracking(False)
|
| 903 |
+
spinbox.valueChanged.connect(self._on_value_changed)
|
| 904 |
+
inner.addRow(name, spinbox)
|
| 905 |
+
layout.addStretch(1)
|
| 906 |
+
for name, method in buttons:
|
| 907 |
+
button = QtWidgets.QPushButton(name)
|
| 908 |
+
# Don't trigger on <enter>, which is used to input values.
|
| 909 |
+
button.setAutoDefault(False)
|
| 910 |
+
button.clicked.connect(method)
|
| 911 |
+
layout.addWidget(button)
|
| 912 |
+
if name == "Close":
|
| 913 |
+
button.setFocus()
|
| 914 |
+
self._figure = targetfig
|
| 915 |
+
self._defaults = {}
|
| 916 |
+
self._export_values_dialog = None
|
| 917 |
+
self.update_from_current_subplotpars()
|
| 918 |
+
|
| 919 |
+
def update_from_current_subplotpars(self):
|
| 920 |
+
self._defaults = {spinbox: getattr(self._figure.subplotpars, name)
|
| 921 |
+
for name, spinbox in self._spinboxes.items()}
|
| 922 |
+
self._reset() # Set spinbox current values without triggering signals.
|
| 923 |
+
|
| 924 |
+
def _export_values(self):
|
| 925 |
+
# Explicitly round to 3 decimals (which is also the spinbox precision)
|
| 926 |
+
# to avoid numbers of the form 0.100...001.
|
| 927 |
+
self._export_values_dialog = QtWidgets.QDialog()
|
| 928 |
+
layout = QtWidgets.QVBoxLayout()
|
| 929 |
+
self._export_values_dialog.setLayout(layout)
|
| 930 |
+
text = QtWidgets.QPlainTextEdit()
|
| 931 |
+
text.setReadOnly(True)
|
| 932 |
+
layout.addWidget(text)
|
| 933 |
+
text.setPlainText(
|
| 934 |
+
",\n".join(f"{attr}={spinbox.value():.3}"
|
| 935 |
+
for attr, spinbox in self._spinboxes.items()))
|
| 936 |
+
# Adjust the height of the text widget to fit the whole text, plus
|
| 937 |
+
# some padding.
|
| 938 |
+
size = text.maximumSize()
|
| 939 |
+
size.setHeight(
|
| 940 |
+
QtGui.QFontMetrics(text.document().defaultFont())
|
| 941 |
+
.size(0, text.toPlainText()).height() + 20)
|
| 942 |
+
text.setMaximumSize(size)
|
| 943 |
+
self._export_values_dialog.show()
|
| 944 |
+
|
| 945 |
+
def _on_value_changed(self):
|
| 946 |
+
spinboxes = self._spinboxes
|
| 947 |
+
# Set all mins and maxes, so that this can also be used in _reset().
|
| 948 |
+
for lower, higher in [("bottom", "top"), ("left", "right")]:
|
| 949 |
+
spinboxes[higher].setMinimum(spinboxes[lower].value() + .001)
|
| 950 |
+
spinboxes[lower].setMaximum(spinboxes[higher].value() - .001)
|
| 951 |
+
self._figure.subplots_adjust(
|
| 952 |
+
**{attr: spinbox.value() for attr, spinbox in spinboxes.items()})
|
| 953 |
+
self._figure.canvas.draw_idle()
|
| 954 |
+
|
| 955 |
+
def _tight_layout(self):
|
| 956 |
+
self._figure.tight_layout()
|
| 957 |
+
for attr, spinbox in self._spinboxes.items():
|
| 958 |
+
spinbox.blockSignals(True)
|
| 959 |
+
spinbox.setValue(getattr(self._figure.subplotpars, attr))
|
| 960 |
+
spinbox.blockSignals(False)
|
| 961 |
+
self._figure.canvas.draw_idle()
|
| 962 |
+
|
| 963 |
+
def _reset(self):
|
| 964 |
+
for spinbox, value in self._defaults.items():
|
| 965 |
+
spinbox.setRange(0, 1)
|
| 966 |
+
spinbox.blockSignals(True)
|
| 967 |
+
spinbox.setValue(value)
|
| 968 |
+
spinbox.blockSignals(False)
|
| 969 |
+
self._on_value_changed()
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar):
|
| 973 |
+
def __init__(self, toolmanager, parent=None):
|
| 974 |
+
ToolContainerBase.__init__(self, toolmanager)
|
| 975 |
+
QtWidgets.QToolBar.__init__(self, parent)
|
| 976 |
+
self.setAllowedAreas(QtCore.Qt.ToolBarArea(
|
| 977 |
+
_to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
|
| 978 |
+
_to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
|
| 979 |
+
message_label = QtWidgets.QLabel("")
|
| 980 |
+
message_label.setAlignment(QtCore.Qt.AlignmentFlag(
|
| 981 |
+
_to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
|
| 982 |
+
_to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
|
| 983 |
+
message_label.setSizePolicy(QtWidgets.QSizePolicy(
|
| 984 |
+
QtWidgets.QSizePolicy.Policy.Expanding,
|
| 985 |
+
QtWidgets.QSizePolicy.Policy.Ignored,
|
| 986 |
+
))
|
| 987 |
+
self._message_action = self.addWidget(message_label)
|
| 988 |
+
self._toolitems = {}
|
| 989 |
+
self._groups = {}
|
| 990 |
+
|
| 991 |
+
def add_toolitem(
|
| 992 |
+
self, name, group, position, image_file, description, toggle):
|
| 993 |
+
|
| 994 |
+
button = QtWidgets.QToolButton(self)
|
| 995 |
+
if image_file:
|
| 996 |
+
button.setIcon(NavigationToolbar2QT._icon(self, image_file))
|
| 997 |
+
button.setText(name)
|
| 998 |
+
if description:
|
| 999 |
+
button.setToolTip(description)
|
| 1000 |
+
|
| 1001 |
+
def handler():
|
| 1002 |
+
self.trigger_tool(name)
|
| 1003 |
+
if toggle:
|
| 1004 |
+
button.setCheckable(True)
|
| 1005 |
+
button.toggled.connect(handler)
|
| 1006 |
+
else:
|
| 1007 |
+
button.clicked.connect(handler)
|
| 1008 |
+
|
| 1009 |
+
self._toolitems.setdefault(name, [])
|
| 1010 |
+
self._add_to_group(group, name, button, position)
|
| 1011 |
+
self._toolitems[name].append((button, handler))
|
| 1012 |
+
|
| 1013 |
+
def _add_to_group(self, group, name, button, position):
|
| 1014 |
+
gr = self._groups.get(group, [])
|
| 1015 |
+
if not gr:
|
| 1016 |
+
sep = self.insertSeparator(self._message_action)
|
| 1017 |
+
gr.append(sep)
|
| 1018 |
+
before = gr[position]
|
| 1019 |
+
widget = self.insertWidget(before, button)
|
| 1020 |
+
gr.insert(position, widget)
|
| 1021 |
+
self._groups[group] = gr
|
| 1022 |
+
|
| 1023 |
+
def toggle_toolitem(self, name, toggled):
|
| 1024 |
+
if name not in self._toolitems:
|
| 1025 |
+
return
|
| 1026 |
+
for button, handler in self._toolitems[name]:
|
| 1027 |
+
button.toggled.disconnect(handler)
|
| 1028 |
+
button.setChecked(toggled)
|
| 1029 |
+
button.toggled.connect(handler)
|
| 1030 |
+
|
| 1031 |
+
def remove_toolitem(self, name):
|
| 1032 |
+
for button, handler in self._toolitems.pop(name, []):
|
| 1033 |
+
button.setParent(None)
|
| 1034 |
+
|
| 1035 |
+
def set_message(self, s):
|
| 1036 |
+
self.widgetForAction(self._message_action).setText(s)
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
@backend_tools._register_tool_class(FigureCanvasQT)
|
| 1040 |
+
class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase):
|
| 1041 |
+
def __init__(self, *args, **kwargs):
|
| 1042 |
+
super().__init__(*args, **kwargs)
|
| 1043 |
+
self._subplot_dialog = None
|
| 1044 |
+
|
| 1045 |
+
def trigger(self, *args):
|
| 1046 |
+
NavigationToolbar2QT.configure_subplots(self)
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
@backend_tools._register_tool_class(FigureCanvasQT)
|
| 1050 |
+
class SaveFigureQt(backend_tools.SaveFigureBase):
|
| 1051 |
+
def trigger(self, *args):
|
| 1052 |
+
NavigationToolbar2QT.save_figure(
|
| 1053 |
+
self._make_classic_style_pseudo_toolbar())
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
@backend_tools._register_tool_class(FigureCanvasQT)
|
| 1057 |
+
class RubberbandQt(backend_tools.RubberbandBase):
|
| 1058 |
+
def draw_rubberband(self, x0, y0, x1, y1):
|
| 1059 |
+
NavigationToolbar2QT.draw_rubberband(
|
| 1060 |
+
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
|
| 1061 |
+
|
| 1062 |
+
def remove_rubberband(self):
|
| 1063 |
+
NavigationToolbar2QT.remove_rubberband(
|
| 1064 |
+
self._make_classic_style_pseudo_toolbar())
|
| 1065 |
+
|
| 1066 |
+
|
| 1067 |
+
@backend_tools._register_tool_class(FigureCanvasQT)
|
| 1068 |
+
class HelpQt(backend_tools.ToolHelpBase):
|
| 1069 |
+
def trigger(self, *args):
|
| 1070 |
+
QtWidgets.QMessageBox.information(None, "Help", self._get_help_html())
|
| 1071 |
+
|
| 1072 |
+
|
| 1073 |
+
@backend_tools._register_tool_class(FigureCanvasQT)
|
| 1074 |
+
class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase):
|
| 1075 |
+
def trigger(self, *args, **kwargs):
|
| 1076 |
+
pixmap = self.canvas.grab()
|
| 1077 |
+
QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap)
|
| 1078 |
+
|
| 1079 |
+
|
| 1080 |
+
FigureManagerQT._toolbar2_class = NavigationToolbar2QT
|
| 1081 |
+
FigureManagerQT._toolmanager_toolbar_class = ToolbarQt
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
@_Backend.export
|
| 1085 |
+
class _BackendQT(_Backend):
|
| 1086 |
+
backend_version = __version__
|
| 1087 |
+
FigureCanvas = FigureCanvasQT
|
| 1088 |
+
FigureManager = FigureManagerQT
|
| 1089 |
+
mainloop = FigureManagerQT.start_main_loop
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import backends
|
| 2 |
+
|
| 3 |
+
backends._QT_FORCE_QT5_BINDING = True
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from .backend_qt import ( # noqa
|
| 7 |
+
SPECIAL_KEYS,
|
| 8 |
+
# Public API
|
| 9 |
+
cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT,
|
| 10 |
+
FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt,
|
| 11 |
+
SaveFigureQt, ConfigureSubplotsQt, RubberbandQt,
|
| 12 |
+
HelpQt, ToolCopyToClipboardQT,
|
| 13 |
+
# internal re-exports
|
| 14 |
+
FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2,
|
| 15 |
+
TimerBase, ToolContainerBase, figureoptions, Gcf
|
| 16 |
+
)
|
| 17 |
+
from . import backend_qt as _backend_qt # noqa
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@_BackendQT.export
|
| 21 |
+
class _BackendQT5(_BackendQT):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def __getattr__(name):
|
| 26 |
+
if name == 'qApp':
|
| 27 |
+
return _backend_qt.qApp
|
| 28 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5agg.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Render to qt from agg
|
| 3 |
+
"""
|
| 4 |
+
from .. import backends
|
| 5 |
+
|
| 6 |
+
backends._QT_FORCE_QT5_BINDING = True
|
| 7 |
+
from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611
|
| 8 |
+
_BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT,
|
| 9 |
+
FigureCanvasAgg, FigureCanvasQT)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@_BackendQTAgg.export
|
| 13 |
+
class _BackendQT5Agg(_BackendQTAgg):
|
| 14 |
+
pass
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qt5cairo.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import backends
|
| 2 |
+
|
| 3 |
+
backends._QT_FORCE_QT5_BINDING = True
|
| 4 |
+
from .backend_qtcairo import ( # noqa: F401, E402 # pylint: disable=W0611
|
| 5 |
+
_BackendQTCairo, FigureCanvasQTCairo, FigureCanvasCairo, FigureCanvasQT
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@_BackendQTCairo.export
|
| 10 |
+
class _BackendQT5Cairo(_BackendQTCairo):
|
| 11 |
+
pass
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qtagg.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Render to qt from agg.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import ctypes
|
| 6 |
+
|
| 7 |
+
from matplotlib.transforms import Bbox
|
| 8 |
+
|
| 9 |
+
from .qt_compat import QT_API, QtCore, QtGui
|
| 10 |
+
from .backend_agg import FigureCanvasAgg
|
| 11 |
+
from .backend_qt import _BackendQT, FigureCanvasQT
|
| 12 |
+
from .backend_qt import ( # noqa: F401 # pylint: disable=W0611
|
| 13 |
+
FigureManagerQT, NavigationToolbar2QT)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT):
|
| 17 |
+
|
| 18 |
+
def paintEvent(self, event):
|
| 19 |
+
"""
|
| 20 |
+
Copy the image from the Agg canvas to the qt.drawable.
|
| 21 |
+
|
| 22 |
+
In Qt, all drawing should be done inside of here when a widget is
|
| 23 |
+
shown onscreen.
|
| 24 |
+
"""
|
| 25 |
+
self._draw_idle() # Only does something if a draw is pending.
|
| 26 |
+
|
| 27 |
+
# If the canvas does not have a renderer, then give up and wait for
|
| 28 |
+
# FigureCanvasAgg.draw(self) to be called.
|
| 29 |
+
if not hasattr(self, 'renderer'):
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
painter = QtGui.QPainter(self)
|
| 33 |
+
try:
|
| 34 |
+
# See documentation of QRect: bottom() and right() are off
|
| 35 |
+
# by 1, so use left() + width() and top() + height().
|
| 36 |
+
rect = event.rect()
|
| 37 |
+
# scale rect dimensions using the screen dpi ratio to get
|
| 38 |
+
# correct values for the Figure coordinates (rather than
|
| 39 |
+
# QT5's coords)
|
| 40 |
+
width = rect.width() * self.device_pixel_ratio
|
| 41 |
+
height = rect.height() * self.device_pixel_ratio
|
| 42 |
+
left, top = self.mouseEventCoords(rect.topLeft())
|
| 43 |
+
# shift the "top" by the height of the image to get the
|
| 44 |
+
# correct corner for our coordinate system
|
| 45 |
+
bottom = top - height
|
| 46 |
+
# same with the right side of the image
|
| 47 |
+
right = left + width
|
| 48 |
+
# create a buffer using the image bounding box
|
| 49 |
+
bbox = Bbox([[left, bottom], [right, top]])
|
| 50 |
+
buf = memoryview(self.copy_from_bbox(bbox))
|
| 51 |
+
|
| 52 |
+
if QT_API == "PyQt6":
|
| 53 |
+
from PyQt6 import sip
|
| 54 |
+
ptr = int(sip.voidptr(buf))
|
| 55 |
+
else:
|
| 56 |
+
ptr = buf
|
| 57 |
+
|
| 58 |
+
painter.eraseRect(rect) # clear the widget canvas
|
| 59 |
+
qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0],
|
| 60 |
+
QtGui.QImage.Format.Format_RGBA8888)
|
| 61 |
+
qimage.setDevicePixelRatio(self.device_pixel_ratio)
|
| 62 |
+
# set origin using original QT coordinates
|
| 63 |
+
origin = QtCore.QPoint(rect.left(), rect.top())
|
| 64 |
+
painter.drawImage(origin, qimage)
|
| 65 |
+
# Adjust the buf reference count to work around a memory
|
| 66 |
+
# leak bug in QImage under PySide.
|
| 67 |
+
if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):
|
| 68 |
+
ctypes.c_long.from_address(id(buf)).value = 1
|
| 69 |
+
|
| 70 |
+
self._draw_rect_callback(painter)
|
| 71 |
+
finally:
|
| 72 |
+
painter.end()
|
| 73 |
+
|
| 74 |
+
def print_figure(self, *args, **kwargs):
|
| 75 |
+
super().print_figure(*args, **kwargs)
|
| 76 |
+
# In some cases, Qt will itself trigger a paint event after closing the file
|
| 77 |
+
# save dialog. When that happens, we need to be sure that the internal canvas is
|
| 78 |
+
# re-drawn. However, if the user is using an automatically-chosen Qt backend but
|
| 79 |
+
# saving with a different backend (such as pgf), we do not want to trigger a
|
| 80 |
+
# full draw in Qt, so just set the flag for next time.
|
| 81 |
+
self._draw_pending = True
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@_BackendQT.export
|
| 85 |
+
class _BackendQTAgg(_BackendQT):
|
| 86 |
+
FigureCanvas = FigureCanvasQTAgg
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/backend_qtcairo.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ctypes
|
| 2 |
+
|
| 3 |
+
from .backend_cairo import cairo, FigureCanvasCairo
|
| 4 |
+
from .backend_qt import _BackendQT, FigureCanvasQT
|
| 5 |
+
from .qt_compat import QT_API, QtCore, QtGui
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT):
|
| 9 |
+
def draw(self):
|
| 10 |
+
if hasattr(self._renderer.gc, "ctx"):
|
| 11 |
+
self._renderer.dpi = self.figure.dpi
|
| 12 |
+
self.figure.draw(self._renderer)
|
| 13 |
+
super().draw()
|
| 14 |
+
|
| 15 |
+
def paintEvent(self, event):
|
| 16 |
+
width = int(self.device_pixel_ratio * self.width())
|
| 17 |
+
height = int(self.device_pixel_ratio * self.height())
|
| 18 |
+
if (width, height) != self._renderer.get_canvas_width_height():
|
| 19 |
+
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
|
| 20 |
+
self._renderer.set_context(cairo.Context(surface))
|
| 21 |
+
self._renderer.dpi = self.figure.dpi
|
| 22 |
+
self.figure.draw(self._renderer)
|
| 23 |
+
buf = self._renderer.gc.ctx.get_target().get_data()
|
| 24 |
+
if QT_API == "PyQt6":
|
| 25 |
+
from PyQt6 import sip
|
| 26 |
+
ptr = int(sip.voidptr(buf))
|
| 27 |
+
else:
|
| 28 |
+
ptr = buf
|
| 29 |
+
qimage = QtGui.QImage(
|
| 30 |
+
ptr, width, height,
|
| 31 |
+
QtGui.QImage.Format.Format_ARGB32_Premultiplied)
|
| 32 |
+
# Adjust the buf reference count to work around a memory leak bug in
|
| 33 |
+
# QImage under PySide.
|
| 34 |
+
if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):
|
| 35 |
+
ctypes.c_long.from_address(id(buf)).value = 1
|
| 36 |
+
qimage.setDevicePixelRatio(self.device_pixel_ratio)
|
| 37 |
+
painter = QtGui.QPainter(self)
|
| 38 |
+
painter.eraseRect(event.rect())
|
| 39 |
+
painter.drawImage(0, 0, qimage)
|
| 40 |
+
self._draw_rect_callback(painter)
|
| 41 |
+
painter.end()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@_BackendQT.export
|
| 45 |
+
class _BackendQTCairo(_BackendQT):
|
| 46 |
+
FigureCanvas = FigureCanvasQTCairo
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/backends/back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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import codecs
|
| 3 |
+
import datetime
|
| 4 |
+
import gzip
|
| 5 |
+
import hashlib
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
import itertools
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import uuid
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
import matplotlib as mpl
|
| 17 |
+
from matplotlib import cbook, font_manager as fm
|
| 18 |
+
from matplotlib.backend_bases import (
|
| 19 |
+
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
|
| 20 |
+
from matplotlib.backends.backend_mixed import MixedModeRenderer
|
| 21 |
+
from matplotlib.colors import rgb2hex
|
| 22 |
+
from matplotlib.dates import UTC
|
| 23 |
+
from matplotlib.path import Path
|
| 24 |
+
from matplotlib import _path
|
| 25 |
+
from matplotlib.transforms import Affine2D, Affine2DBase
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_log = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ----------------------------------------------------------------------
|
| 32 |
+
# SimpleXMLWriter class
|
| 33 |
+
#
|
| 34 |
+
# Based on an original by Fredrik Lundh, but modified here to:
|
| 35 |
+
# 1. Support modern Python idioms
|
| 36 |
+
# 2. Remove encoding support (it's handled by the file writer instead)
|
| 37 |
+
# 3. Support proper indentation
|
| 38 |
+
# 4. Minify things a little bit
|
| 39 |
+
|
| 40 |
+
# --------------------------------------------------------------------
|
| 41 |
+
# The SimpleXMLWriter module is
|
| 42 |
+
#
|
| 43 |
+
# Copyright (c) 2001-2004 by Fredrik Lundh
|
| 44 |
+
#
|
| 45 |
+
# By obtaining, using, and/or copying this software and/or its
|
| 46 |
+
# associated documentation, you agree that you have read, understood,
|
| 47 |
+
# and will comply with the following terms and conditions:
|
| 48 |
+
#
|
| 49 |
+
# Permission to use, copy, modify, and distribute this software and
|
| 50 |
+
# its associated documentation for any purpose and without fee is
|
| 51 |
+
# hereby granted, provided that the above copyright notice appears in
|
| 52 |
+
# all copies, and that both that copyright notice and this permission
|
| 53 |
+
# notice appear in supporting documentation, and that the name of
|
| 54 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
| 55 |
+
# pertaining to distribution of the software without specific, written
|
| 56 |
+
# prior permission.
|
| 57 |
+
#
|
| 58 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
| 59 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
| 60 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
| 61 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
| 62 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 63 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 64 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 65 |
+
# OF THIS SOFTWARE.
|
| 66 |
+
# --------------------------------------------------------------------
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _escape_cdata(s):
|
| 70 |
+
s = s.replace("&", "&")
|
| 71 |
+
s = s.replace("<", "<")
|
| 72 |
+
s = s.replace(">", ">")
|
| 73 |
+
return s
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
_escape_xml_comment = re.compile(r'-(?=-)')
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _escape_comment(s):
|
| 80 |
+
s = _escape_cdata(s)
|
| 81 |
+
return _escape_xml_comment.sub('- ', s)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _escape_attrib(s):
|
| 85 |
+
s = s.replace("&", "&")
|
| 86 |
+
s = s.replace("'", "'")
|
| 87 |
+
s = s.replace('"', """)
|
| 88 |
+
s = s.replace("<", "<")
|
| 89 |
+
s = s.replace(">", ">")
|
| 90 |
+
return s
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _quote_escape_attrib(s):
|
| 94 |
+
return ('"' + _escape_cdata(s) + '"' if '"' not in s else
|
| 95 |
+
"'" + _escape_cdata(s) + "'" if "'" not in s else
|
| 96 |
+
'"' + _escape_attrib(s) + '"')
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _short_float_fmt(x):
|
| 100 |
+
"""
|
| 101 |
+
Create a short string representation of a float, which is %f
|
| 102 |
+
formatting with trailing zeros and the decimal point removed.
|
| 103 |
+
"""
|
| 104 |
+
return f'{x:f}'.rstrip('0').rstrip('.')
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class XMLWriter:
|
| 108 |
+
"""
|
| 109 |
+
Parameters
|
| 110 |
+
----------
|
| 111 |
+
file : writable text file-like object
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
def __init__(self, file):
|
| 115 |
+
self.__write = file.write
|
| 116 |
+
if hasattr(file, "flush"):
|
| 117 |
+
self.flush = file.flush
|
| 118 |
+
self.__open = 0 # true if start tag is open
|
| 119 |
+
self.__tags = []
|
| 120 |
+
self.__data = []
|
| 121 |
+
self.__indentation = " " * 64
|
| 122 |
+
|
| 123 |
+
def __flush(self, indent=True):
|
| 124 |
+
# flush internal buffers
|
| 125 |
+
if self.__open:
|
| 126 |
+
if indent:
|
| 127 |
+
self.__write(">\n")
|
| 128 |
+
else:
|
| 129 |
+
self.__write(">")
|
| 130 |
+
self.__open = 0
|
| 131 |
+
if self.__data:
|
| 132 |
+
data = ''.join(self.__data)
|
| 133 |
+
self.__write(_escape_cdata(data))
|
| 134 |
+
self.__data = []
|
| 135 |
+
|
| 136 |
+
def start(self, tag, attrib={}, **extra):
|
| 137 |
+
"""
|
| 138 |
+
Open a new element. Attributes can be given as keyword
|
| 139 |
+
arguments, or as a string/string dictionary. The method returns
|
| 140 |
+
an opaque identifier that can be passed to the :meth:`close`
|
| 141 |
+
method, to close all open elements up to and including this one.
|
| 142 |
+
|
| 143 |
+
Parameters
|
| 144 |
+
----------
|
| 145 |
+
tag
|
| 146 |
+
Element tag.
|
| 147 |
+
attrib
|
| 148 |
+
Attribute dictionary. Alternatively, attributes can be given as
|
| 149 |
+
keyword arguments.
|
| 150 |
+
|
| 151 |
+
Returns
|
| 152 |
+
-------
|
| 153 |
+
An element identifier.
|
| 154 |
+
"""
|
| 155 |
+
self.__flush()
|
| 156 |
+
tag = _escape_cdata(tag)
|
| 157 |
+
self.__data = []
|
| 158 |
+
self.__tags.append(tag)
|
| 159 |
+
self.__write(self.__indentation[:len(self.__tags) - 1])
|
| 160 |
+
self.__write(f"<{tag}")
|
| 161 |
+
for k, v in {**attrib, **extra}.items():
|
| 162 |
+
if v:
|
| 163 |
+
k = _escape_cdata(k)
|
| 164 |
+
v = _quote_escape_attrib(v)
|
| 165 |
+
self.__write(f' {k}={v}')
|
| 166 |
+
self.__open = 1
|
| 167 |
+
return len(self.__tags) - 1
|
| 168 |
+
|
| 169 |
+
def comment(self, comment):
|
| 170 |
+
"""
|
| 171 |
+
Add a comment to the output stream.
|
| 172 |
+
|
| 173 |
+
Parameters
|
| 174 |
+
----------
|
| 175 |
+
comment : str
|
| 176 |
+
Comment text.
|
| 177 |
+
"""
|
| 178 |
+
self.__flush()
|
| 179 |
+
self.__write(self.__indentation[:len(self.__tags)])
|
| 180 |
+
self.__write(f"<!-- {_escape_comment(comment)} -->\n")
|
| 181 |
+
|
| 182 |
+
def data(self, text):
|
| 183 |
+
"""
|
| 184 |
+
Add character data to the output stream.
|
| 185 |
+
|
| 186 |
+
Parameters
|
| 187 |
+
----------
|
| 188 |
+
text : str
|
| 189 |
+
Character data.
|
| 190 |
+
"""
|
| 191 |
+
self.__data.append(text)
|
| 192 |
+
|
| 193 |
+
def end(self, tag=None, indent=True):
|
| 194 |
+
"""
|
| 195 |
+
Close the current element (opened by the most recent call to
|
| 196 |
+
:meth:`start`).
|
| 197 |
+
|
| 198 |
+
Parameters
|
| 199 |
+
----------
|
| 200 |
+
tag
|
| 201 |
+
Element tag. If given, the tag must match the start tag. If
|
| 202 |
+
omitted, the current element is closed.
|
| 203 |
+
indent : bool, default: True
|
| 204 |
+
"""
|
| 205 |
+
if tag:
|
| 206 |
+
assert self.__tags, f"unbalanced end({tag})"
|
| 207 |
+
assert _escape_cdata(tag) == self.__tags[-1], \
|
| 208 |
+
f"expected end({self.__tags[-1]}), got {tag}"
|
| 209 |
+
else:
|
| 210 |
+
assert self.__tags, "unbalanced end()"
|
| 211 |
+
tag = self.__tags.pop()
|
| 212 |
+
if self.__data:
|
| 213 |
+
self.__flush(indent)
|
| 214 |
+
elif self.__open:
|
| 215 |
+
self.__open = 0
|
| 216 |
+
self.__write("/>\n")
|
| 217 |
+
return
|
| 218 |
+
if indent:
|
| 219 |
+
self.__write(self.__indentation[:len(self.__tags)])
|
| 220 |
+
self.__write(f"</{tag}>\n")
|
| 221 |
+
|
| 222 |
+
def close(self, id):
|
| 223 |
+
"""
|
| 224 |
+
Close open elements, up to (and including) the element identified
|
| 225 |
+
by the given identifier.
|
| 226 |
+
|
| 227 |
+
Parameters
|
| 228 |
+
----------
|
| 229 |
+
id
|
| 230 |
+
Element identifier, as returned by the :meth:`start` method.
|
| 231 |
+
"""
|
| 232 |
+
while len(self.__tags) > id:
|
| 233 |
+
self.end()
|
| 234 |
+
|
| 235 |
+
def element(self, tag, text=None, attrib={}, **extra):
|
| 236 |
+
"""
|
| 237 |
+
Add an entire element. This is the same as calling :meth:`start`,
|
| 238 |
+
:meth:`data`, and :meth:`end` in sequence. The *text* argument can be
|
| 239 |
+
omitted.
|
| 240 |
+
"""
|
| 241 |
+
self.start(tag, attrib, **extra)
|
| 242 |
+
if text:
|
| 243 |
+
self.data(text)
|
| 244 |
+
self.end(indent=False)
|
| 245 |
+
|
| 246 |
+
def flush(self):
|
| 247 |
+
"""Flush the output stream."""
|
| 248 |
+
pass # replaced by the constructor
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _generate_transform(transform_list):
|
| 252 |
+
parts = []
|
| 253 |
+
for type, value in transform_list:
|
| 254 |
+
if (type == 'scale' and (value == (1,) or value == (1, 1))
|
| 255 |
+
or type == 'translate' and value == (0, 0)
|
| 256 |
+
or type == 'rotate' and value == (0,)):
|
| 257 |
+
continue
|
| 258 |
+
if type == 'matrix' and isinstance(value, Affine2DBase):
|
| 259 |
+
value = value.to_values()
|
| 260 |
+
parts.append('{}({})'.format(
|
| 261 |
+
type, ' '.join(_short_float_fmt(x) for x in value)))
|
| 262 |
+
return ' '.join(parts)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _generate_css(attrib):
|
| 266 |
+
return "; ".join(f"{k}: {v}" for k, v in attrib.items())
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'}
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _check_is_str(info, key):
|
| 273 |
+
if not isinstance(info, str):
|
| 274 |
+
raise TypeError(f'Invalid type for {key} metadata. Expected str, not '
|
| 275 |
+
f'{type(info)}.')
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _check_is_iterable_of_str(infos, key):
|
| 279 |
+
if np.iterable(infos):
|
| 280 |
+
for info in infos:
|
| 281 |
+
if not isinstance(info, str):
|
| 282 |
+
raise TypeError(f'Invalid type for {key} metadata. Expected '
|
| 283 |
+
f'iterable of str, not {type(info)}.')
|
| 284 |
+
else:
|
| 285 |
+
raise TypeError(f'Invalid type for {key} metadata. Expected str or '
|
| 286 |
+
f'iterable of str, not {type(infos)}.')
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class RendererSVG(RendererBase):
|
| 290 |
+
def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
|
| 291 |
+
*, metadata=None):
|
| 292 |
+
self.width = width
|
| 293 |
+
self.height = height
|
| 294 |
+
self.writer = XMLWriter(svgwriter)
|
| 295 |
+
self.image_dpi = image_dpi # actual dpi at which we rasterize stuff
|
| 296 |
+
|
| 297 |
+
if basename is None:
|
| 298 |
+
basename = getattr(svgwriter, "name", "")
|
| 299 |
+
if not isinstance(basename, str):
|
| 300 |
+
basename = ""
|
| 301 |
+
self.basename = basename
|
| 302 |
+
|
| 303 |
+
self._groupd = {}
|
| 304 |
+
self._image_counter = itertools.count()
|
| 305 |
+
self._clip_path_ids = {}
|
| 306 |
+
self._clipd = {}
|
| 307 |
+
self._markers = {}
|
| 308 |
+
self._path_collection_id = 0
|
| 309 |
+
self._hatchd = {}
|
| 310 |
+
self._has_gouraud = False
|
| 311 |
+
self._n_gradients = 0
|
| 312 |
+
|
| 313 |
+
super().__init__()
|
| 314 |
+
self._glyph_map = dict()
|
| 315 |
+
str_height = _short_float_fmt(height)
|
| 316 |
+
str_width = _short_float_fmt(width)
|
| 317 |
+
svgwriter.write(svgProlog)
|
| 318 |
+
self._start_id = self.writer.start(
|
| 319 |
+
'svg',
|
| 320 |
+
width=f'{str_width}pt',
|
| 321 |
+
height=f'{str_height}pt',
|
| 322 |
+
viewBox=f'0 0 {str_width} {str_height}',
|
| 323 |
+
xmlns="http://www.w3.org/2000/svg",
|
| 324 |
+
version="1.1",
|
| 325 |
+
id=mpl.rcParams['svg.id'],
|
| 326 |
+
attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
|
| 327 |
+
self._write_metadata(metadata)
|
| 328 |
+
self._write_default_style()
|
| 329 |
+
|
| 330 |
+
def _get_clippath_id(self, clippath):
|
| 331 |
+
"""
|
| 332 |
+
Returns a stable and unique identifier for the *clippath* argument
|
| 333 |
+
object within the current rendering context.
|
| 334 |
+
|
| 335 |
+
This allows plots that include custom clip paths to produce identical
|
| 336 |
+
SVG output on each render, provided that the :rc:`svg.hashsalt` config
|
| 337 |
+
setting and the ``SOURCE_DATE_EPOCH`` build-time environment variable
|
| 338 |
+
are set to fixed values.
|
| 339 |
+
"""
|
| 340 |
+
if clippath not in self._clip_path_ids:
|
| 341 |
+
self._clip_path_ids[clippath] = len(self._clip_path_ids)
|
| 342 |
+
return self._clip_path_ids[clippath]
|
| 343 |
+
|
| 344 |
+
def finalize(self):
|
| 345 |
+
self._write_clips()
|
| 346 |
+
self._write_hatches()
|
| 347 |
+
self.writer.close(self._start_id)
|
| 348 |
+
self.writer.flush()
|
| 349 |
+
|
| 350 |
+
def _write_metadata(self, metadata):
|
| 351 |
+
# Add metadata following the Dublin Core Metadata Initiative, and the
|
| 352 |
+
# Creative Commons Rights Expression Language. This is mainly for
|
| 353 |
+
# compatibility with Inkscape.
|
| 354 |
+
if metadata is None:
|
| 355 |
+
metadata = {}
|
| 356 |
+
metadata = {
|
| 357 |
+
'Format': 'image/svg+xml',
|
| 358 |
+
'Type': 'http://purl.org/dc/dcmitype/StillImage',
|
| 359 |
+
'Creator':
|
| 360 |
+
f'Matplotlib v{mpl.__version__}, https://matplotlib.org/',
|
| 361 |
+
**metadata
|
| 362 |
+
}
|
| 363 |
+
writer = self.writer
|
| 364 |
+
|
| 365 |
+
if 'Title' in metadata:
|
| 366 |
+
title = metadata['Title']
|
| 367 |
+
_check_is_str(title, 'Title')
|
| 368 |
+
writer.element('title', text=title)
|
| 369 |
+
|
| 370 |
+
# Special handling.
|
| 371 |
+
date = metadata.get('Date', None)
|
| 372 |
+
if date is not None:
|
| 373 |
+
if isinstance(date, str):
|
| 374 |
+
dates = [date]
|
| 375 |
+
elif isinstance(date, (datetime.datetime, datetime.date)):
|
| 376 |
+
dates = [date.isoformat()]
|
| 377 |
+
elif np.iterable(date):
|
| 378 |
+
dates = []
|
| 379 |
+
for d in date:
|
| 380 |
+
if isinstance(d, str):
|
| 381 |
+
dates.append(d)
|
| 382 |
+
elif isinstance(d, (datetime.datetime, datetime.date)):
|
| 383 |
+
dates.append(d.isoformat())
|
| 384 |
+
else:
|
| 385 |
+
raise TypeError(
|
| 386 |
+
f'Invalid type for Date metadata. '
|
| 387 |
+
f'Expected iterable of str, date, or datetime, '
|
| 388 |
+
f'not {type(d)}.')
|
| 389 |
+
else:
|
| 390 |
+
raise TypeError(f'Invalid type for Date metadata. '
|
| 391 |
+
f'Expected str, date, datetime, or iterable '
|
| 392 |
+
f'of the same, not {type(date)}.')
|
| 393 |
+
metadata['Date'] = '/'.join(dates)
|
| 394 |
+
elif 'Date' not in metadata:
|
| 395 |
+
# Do not add `Date` if the user explicitly set `Date` to `None`
|
| 396 |
+
# Get source date from SOURCE_DATE_EPOCH, if set.
|
| 397 |
+
# See https://reproducible-builds.org/specs/source-date-epoch/
|
| 398 |
+
date = os.getenv("SOURCE_DATE_EPOCH")
|
| 399 |
+
if date:
|
| 400 |
+
date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc)
|
| 401 |
+
metadata['Date'] = date.replace(tzinfo=UTC).isoformat()
|
| 402 |
+
else:
|
| 403 |
+
metadata['Date'] = datetime.datetime.today().isoformat()
|
| 404 |
+
|
| 405 |
+
mid = None
|
| 406 |
+
def ensure_metadata(mid):
|
| 407 |
+
if mid is not None:
|
| 408 |
+
return mid
|
| 409 |
+
mid = writer.start('metadata')
|
| 410 |
+
writer.start('rdf:RDF', attrib={
|
| 411 |
+
'xmlns:dc': "http://purl.org/dc/elements/1.1/",
|
| 412 |
+
'xmlns:cc': "http://creativecommons.org/ns#",
|
| 413 |
+
'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
|
| 414 |
+
})
|
| 415 |
+
writer.start('cc:Work')
|
| 416 |
+
return mid
|
| 417 |
+
|
| 418 |
+
uri = metadata.pop('Type', None)
|
| 419 |
+
if uri is not None:
|
| 420 |
+
mid = ensure_metadata(mid)
|
| 421 |
+
writer.element('dc:type', attrib={'rdf:resource': uri})
|
| 422 |
+
|
| 423 |
+
# Single value only.
|
| 424 |
+
for key in ['Title', 'Coverage', 'Date', 'Description', 'Format',
|
| 425 |
+
'Identifier', 'Language', 'Relation', 'Source']:
|
| 426 |
+
info = metadata.pop(key, None)
|
| 427 |
+
if info is not None:
|
| 428 |
+
mid = ensure_metadata(mid)
|
| 429 |
+
_check_is_str(info, key)
|
| 430 |
+
writer.element(f'dc:{key.lower()}', text=info)
|
| 431 |
+
|
| 432 |
+
# Multiple Agent values.
|
| 433 |
+
for key in ['Creator', 'Contributor', 'Publisher', 'Rights']:
|
| 434 |
+
agents = metadata.pop(key, None)
|
| 435 |
+
if agents is None:
|
| 436 |
+
continue
|
| 437 |
+
|
| 438 |
+
if isinstance(agents, str):
|
| 439 |
+
agents = [agents]
|
| 440 |
+
|
| 441 |
+
_check_is_iterable_of_str(agents, key)
|
| 442 |
+
# Now we know that we have an iterable of str
|
| 443 |
+
mid = ensure_metadata(mid)
|
| 444 |
+
writer.start(f'dc:{key.lower()}')
|
| 445 |
+
for agent in agents:
|
| 446 |
+
writer.start('cc:Agent')
|
| 447 |
+
writer.element('dc:title', text=agent)
|
| 448 |
+
writer.end('cc:Agent')
|
| 449 |
+
writer.end(f'dc:{key.lower()}')
|
| 450 |
+
|
| 451 |
+
# Multiple values.
|
| 452 |
+
keywords = metadata.pop('Keywords', None)
|
| 453 |
+
if keywords is not None:
|
| 454 |
+
if isinstance(keywords, str):
|
| 455 |
+
keywords = [keywords]
|
| 456 |
+
_check_is_iterable_of_str(keywords, 'Keywords')
|
| 457 |
+
# Now we know that we have an iterable of str
|
| 458 |
+
mid = ensure_metadata(mid)
|
| 459 |
+
writer.start('dc:subject')
|
| 460 |
+
writer.start('rdf:Bag')
|
| 461 |
+
for keyword in keywords:
|
| 462 |
+
writer.element('rdf:li', text=keyword)
|
| 463 |
+
writer.end('rdf:Bag')
|
| 464 |
+
writer.end('dc:subject')
|
| 465 |
+
|
| 466 |
+
if mid is not None:
|
| 467 |
+
writer.close(mid)
|
| 468 |
+
|
| 469 |
+
if metadata:
|
| 470 |
+
raise ValueError('Unknown metadata key(s) passed to SVG writer: ' +
|
| 471 |
+
','.join(metadata))
|
| 472 |
+
|
| 473 |
+
def _write_default_style(self):
|
| 474 |
+
writer = self.writer
|
| 475 |
+
default_style = _generate_css({
|
| 476 |
+
'stroke-linejoin': 'round',
|
| 477 |
+
'stroke-linecap': 'butt'})
|
| 478 |
+
writer.start('defs')
|
| 479 |
+
writer.element('style', type='text/css', text='*{%s}' % default_style)
|
| 480 |
+
writer.end('defs')
|
| 481 |
+
|
| 482 |
+
def _make_id(self, type, content):
|
| 483 |
+
salt = mpl.rcParams['svg.hashsalt']
|
| 484 |
+
if salt is None:
|
| 485 |
+
salt = str(uuid.uuid4())
|
| 486 |
+
m = hashlib.sha256()
|
| 487 |
+
m.update(salt.encode('utf8'))
|
| 488 |
+
m.update(str(content).encode('utf8'))
|
| 489 |
+
return f'{type}{m.hexdigest()[:10]}'
|
| 490 |
+
|
| 491 |
+
def _make_flip_transform(self, transform):
|
| 492 |
+
return transform + Affine2D().scale(1, -1).translate(0, self.height)
|
| 493 |
+
|
| 494 |
+
def _get_hatch(self, gc, rgbFace):
|
| 495 |
+
"""
|
| 496 |
+
Create a new hatch pattern
|
| 497 |
+
"""
|
| 498 |
+
if rgbFace is not None:
|
| 499 |
+
rgbFace = tuple(rgbFace)
|
| 500 |
+
edge = gc.get_hatch_color()
|
| 501 |
+
if edge is not None:
|
| 502 |
+
edge = tuple(edge)
|
| 503 |
+
lw = gc.get_hatch_linewidth()
|
| 504 |
+
dictkey = (gc.get_hatch(), rgbFace, edge, lw)
|
| 505 |
+
oid = self._hatchd.get(dictkey)
|
| 506 |
+
if oid is None:
|
| 507 |
+
oid = self._make_id('h', dictkey)
|
| 508 |
+
self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge, lw), oid)
|
| 509 |
+
else:
|
| 510 |
+
_, oid = oid
|
| 511 |
+
return oid
|
| 512 |
+
|
| 513 |
+
def _write_hatches(self):
|
| 514 |
+
if not len(self._hatchd):
|
| 515 |
+
return
|
| 516 |
+
HATCH_SIZE = 72
|
| 517 |
+
writer = self.writer
|
| 518 |
+
writer.start('defs')
|
| 519 |
+
for (path, face, stroke, lw), oid in self._hatchd.values():
|
| 520 |
+
writer.start(
|
| 521 |
+
'pattern',
|
| 522 |
+
id=oid,
|
| 523 |
+
patternUnits="userSpaceOnUse",
|
| 524 |
+
x="0", y="0", width=str(HATCH_SIZE),
|
| 525 |
+
height=str(HATCH_SIZE))
|
| 526 |
+
path_data = self._convert_path(
|
| 527 |
+
path,
|
| 528 |
+
Affine2D()
|
| 529 |
+
.scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE),
|
| 530 |
+
simplify=False)
|
| 531 |
+
if face is None:
|
| 532 |
+
fill = 'none'
|
| 533 |
+
else:
|
| 534 |
+
fill = rgb2hex(face)
|
| 535 |
+
writer.element(
|
| 536 |
+
'rect',
|
| 537 |
+
x="0", y="0", width=str(HATCH_SIZE+1),
|
| 538 |
+
height=str(HATCH_SIZE+1),
|
| 539 |
+
fill=fill)
|
| 540 |
+
hatch_style = {
|
| 541 |
+
'fill': rgb2hex(stroke),
|
| 542 |
+
'stroke': rgb2hex(stroke),
|
| 543 |
+
'stroke-width': str(lw),
|
| 544 |
+
'stroke-linecap': 'butt',
|
| 545 |
+
'stroke-linejoin': 'miter'
|
| 546 |
+
}
|
| 547 |
+
if stroke[3] < 1:
|
| 548 |
+
hatch_style['stroke-opacity'] = str(stroke[3])
|
| 549 |
+
writer.element(
|
| 550 |
+
'path',
|
| 551 |
+
d=path_data,
|
| 552 |
+
style=_generate_css(hatch_style)
|
| 553 |
+
)
|
| 554 |
+
writer.end('pattern')
|
| 555 |
+
writer.end('defs')
|
| 556 |
+
|
| 557 |
+
def _get_style_dict(self, gc, rgbFace):
|
| 558 |
+
"""Generate a style string from the GraphicsContext and rgbFace."""
|
| 559 |
+
attrib = {}
|
| 560 |
+
|
| 561 |
+
forced_alpha = gc.get_forced_alpha()
|
| 562 |
+
|
| 563 |
+
if gc.get_hatch() is not None:
|
| 564 |
+
attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})"
|
| 565 |
+
if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0
|
| 566 |
+
and not forced_alpha):
|
| 567 |
+
attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])
|
| 568 |
+
else:
|
| 569 |
+
if rgbFace is None:
|
| 570 |
+
attrib['fill'] = 'none'
|
| 571 |
+
else:
|
| 572 |
+
if tuple(rgbFace[:3]) != (0, 0, 0):
|
| 573 |
+
attrib['fill'] = rgb2hex(rgbFace)
|
| 574 |
+
if (len(rgbFace) == 4 and rgbFace[3] != 1.0
|
| 575 |
+
and not forced_alpha):
|
| 576 |
+
attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])
|
| 577 |
+
|
| 578 |
+
if forced_alpha and gc.get_alpha() != 1.0:
|
| 579 |
+
attrib['opacity'] = _short_float_fmt(gc.get_alpha())
|
| 580 |
+
|
| 581 |
+
offset, seq = gc.get_dashes()
|
| 582 |
+
if seq is not None:
|
| 583 |
+
attrib['stroke-dasharray'] = ','.join(
|
| 584 |
+
_short_float_fmt(val) for val in seq)
|
| 585 |
+
attrib['stroke-dashoffset'] = _short_float_fmt(float(offset))
|
| 586 |
+
|
| 587 |
+
linewidth = gc.get_linewidth()
|
| 588 |
+
if linewidth:
|
| 589 |
+
rgb = gc.get_rgb()
|
| 590 |
+
attrib['stroke'] = rgb2hex(rgb)
|
| 591 |
+
if not forced_alpha and rgb[3] != 1.0:
|
| 592 |
+
attrib['stroke-opacity'] = _short_float_fmt(rgb[3])
|
| 593 |
+
if linewidth != 1.0:
|
| 594 |
+
attrib['stroke-width'] = _short_float_fmt(linewidth)
|
| 595 |
+
if gc.get_joinstyle() != 'round':
|
| 596 |
+
attrib['stroke-linejoin'] = gc.get_joinstyle()
|
| 597 |
+
if gc.get_capstyle() != 'butt':
|
| 598 |
+
attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()]
|
| 599 |
+
|
| 600 |
+
return attrib
|
| 601 |
+
|
| 602 |
+
def _get_style(self, gc, rgbFace):
|
| 603 |
+
return _generate_css(self._get_style_dict(gc, rgbFace))
|
| 604 |
+
|
| 605 |
+
def _get_clip_attrs(self, gc):
|
| 606 |
+
cliprect = gc.get_clip_rectangle()
|
| 607 |
+
clippath, clippath_trans = gc.get_clip_path()
|
| 608 |
+
if clippath is not None:
|
| 609 |
+
clippath_trans = self._make_flip_transform(clippath_trans)
|
| 610 |
+
dictkey = (self._get_clippath_id(clippath), str(clippath_trans))
|
| 611 |
+
elif cliprect is not None:
|
| 612 |
+
x, y, w, h = cliprect.bounds
|
| 613 |
+
y = self.height-(y+h)
|
| 614 |
+
dictkey = (x, y, w, h)
|
| 615 |
+
else:
|
| 616 |
+
return {}
|
| 617 |
+
clip = self._clipd.get(dictkey)
|
| 618 |
+
if clip is None:
|
| 619 |
+
oid = self._make_id('p', dictkey)
|
| 620 |
+
if clippath is not None:
|
| 621 |
+
self._clipd[dictkey] = ((clippath, clippath_trans), oid)
|
| 622 |
+
else:
|
| 623 |
+
self._clipd[dictkey] = (dictkey, oid)
|
| 624 |
+
else:
|
| 625 |
+
_, oid = clip
|
| 626 |
+
return {'clip-path': f'url(#{oid})'}
|
| 627 |
+
|
| 628 |
+
def _write_clips(self):
|
| 629 |
+
if not len(self._clipd):
|
| 630 |
+
return
|
| 631 |
+
writer = self.writer
|
| 632 |
+
writer.start('defs')
|
| 633 |
+
for clip, oid in self._clipd.values():
|
| 634 |
+
writer.start('clipPath', id=oid)
|
| 635 |
+
if len(clip) == 2:
|
| 636 |
+
clippath, clippath_trans = clip
|
| 637 |
+
path_data = self._convert_path(
|
| 638 |
+
clippath, clippath_trans, simplify=False)
|
| 639 |
+
writer.element('path', d=path_data)
|
| 640 |
+
else:
|
| 641 |
+
x, y, w, h = clip
|
| 642 |
+
writer.element(
|
| 643 |
+
'rect',
|
| 644 |
+
x=_short_float_fmt(x),
|
| 645 |
+
y=_short_float_fmt(y),
|
| 646 |
+
width=_short_float_fmt(w),
|
| 647 |
+
height=_short_float_fmt(h))
|
| 648 |
+
writer.end('clipPath')
|
| 649 |
+
writer.end('defs')
|
| 650 |
+
|
| 651 |
+
def open_group(self, s, gid=None):
|
| 652 |
+
# docstring inherited
|
| 653 |
+
if gid:
|
| 654 |
+
self.writer.start('g', id=gid)
|
| 655 |
+
else:
|
| 656 |
+
self._groupd[s] = self._groupd.get(s, 0) + 1
|
| 657 |
+
self.writer.start('g', id=f"{s}_{self._groupd[s]:d}")
|
| 658 |
+
|
| 659 |
+
def close_group(self, s):
|
| 660 |
+
# docstring inherited
|
| 661 |
+
self.writer.end('g')
|
| 662 |
+
|
| 663 |
+
def option_image_nocomposite(self):
|
| 664 |
+
# docstring inherited
|
| 665 |
+
return not mpl.rcParams['image.composite_image']
|
| 666 |
+
|
| 667 |
+
def _convert_path(self, path, transform=None, clip=None, simplify=None,
|
| 668 |
+
sketch=None):
|
| 669 |
+
if clip:
|
| 670 |
+
clip = (0.0, 0.0, self.width, self.height)
|
| 671 |
+
else:
|
| 672 |
+
clip = None
|
| 673 |
+
return _path.convert_to_string(
|
| 674 |
+
path, transform, clip, simplify, sketch, 6,
|
| 675 |
+
[b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii')
|
| 676 |
+
|
| 677 |
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
| 678 |
+
# docstring inherited
|
| 679 |
+
trans_and_flip = self._make_flip_transform(transform)
|
| 680 |
+
clip = (rgbFace is None and gc.get_hatch_path() is None)
|
| 681 |
+
simplify = path.should_simplify and clip
|
| 682 |
+
path_data = self._convert_path(
|
| 683 |
+
path, trans_and_flip, clip=clip, simplify=simplify,
|
| 684 |
+
sketch=gc.get_sketch_params())
|
| 685 |
+
|
| 686 |
+
if gc.get_url() is not None:
|
| 687 |
+
self.writer.start('a', {'xlink:href': gc.get_url()})
|
| 688 |
+
self.writer.element('path', d=path_data, **self._get_clip_attrs(gc),
|
| 689 |
+
style=self._get_style(gc, rgbFace))
|
| 690 |
+
if gc.get_url() is not None:
|
| 691 |
+
self.writer.end('a')
|
| 692 |
+
|
| 693 |
+
def draw_markers(
|
| 694 |
+
self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
|
| 695 |
+
# docstring inherited
|
| 696 |
+
|
| 697 |
+
if not len(path.vertices):
|
| 698 |
+
return
|
| 699 |
+
|
| 700 |
+
writer = self.writer
|
| 701 |
+
path_data = self._convert_path(
|
| 702 |
+
marker_path,
|
| 703 |
+
marker_trans + Affine2D().scale(1.0, -1.0),
|
| 704 |
+
simplify=False)
|
| 705 |
+
style = self._get_style_dict(gc, rgbFace)
|
| 706 |
+
dictkey = (path_data, _generate_css(style))
|
| 707 |
+
oid = self._markers.get(dictkey)
|
| 708 |
+
style = _generate_css({k: v for k, v in style.items()
|
| 709 |
+
if k.startswith('stroke')})
|
| 710 |
+
|
| 711 |
+
if oid is None:
|
| 712 |
+
oid = self._make_id('m', dictkey)
|
| 713 |
+
writer.start('defs')
|
| 714 |
+
writer.element('path', id=oid, d=path_data, style=style)
|
| 715 |
+
writer.end('defs')
|
| 716 |
+
self._markers[dictkey] = oid
|
| 717 |
+
|
| 718 |
+
writer.start('g', **self._get_clip_attrs(gc))
|
| 719 |
+
if gc.get_url() is not None:
|
| 720 |
+
self.writer.start('a', {'xlink:href': gc.get_url()})
|
| 721 |
+
trans_and_flip = self._make_flip_transform(trans)
|
| 722 |
+
attrib = {'xlink:href': f'#{oid}'}
|
| 723 |
+
clip = (0, 0, self.width*72, self.height*72)
|
| 724 |
+
for vertices, code in path.iter_segments(
|
| 725 |
+
trans_and_flip, clip=clip, simplify=False):
|
| 726 |
+
if len(vertices):
|
| 727 |
+
x, y = vertices[-2:]
|
| 728 |
+
attrib['x'] = _short_float_fmt(x)
|
| 729 |
+
attrib['y'] = _short_float_fmt(y)
|
| 730 |
+
attrib['style'] = self._get_style(gc, rgbFace)
|
| 731 |
+
writer.element('use', attrib=attrib)
|
| 732 |
+
if gc.get_url() is not None:
|
| 733 |
+
self.writer.end('a')
|
| 734 |
+
writer.end('g')
|
| 735 |
+
|
| 736 |
+
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
|
| 737 |
+
offsets, offset_trans, facecolors, edgecolors,
|
| 738 |
+
linewidths, linestyles, antialiaseds, urls,
|
| 739 |
+
offset_position):
|
| 740 |
+
# Is the optimization worth it? Rough calculation:
|
| 741 |
+
# cost of emitting a path in-line is
|
| 742 |
+
# (len_path + 5) * uses_per_path
|
| 743 |
+
# cost of definition+use is
|
| 744 |
+
# (len_path + 3) + 9 * uses_per_path
|
| 745 |
+
len_path = len(paths[0].vertices) if len(paths) > 0 else 0
|
| 746 |
+
uses_per_path = self._iter_collection_uses_per_path(
|
| 747 |
+
paths, all_transforms, offsets, facecolors, edgecolors)
|
| 748 |
+
should_do_optimization = \
|
| 749 |
+
len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path
|
| 750 |
+
if not should_do_optimization:
|
| 751 |
+
return super().draw_path_collection(
|
| 752 |
+
gc, master_transform, paths, all_transforms,
|
| 753 |
+
offsets, offset_trans, facecolors, edgecolors,
|
| 754 |
+
linewidths, linestyles, antialiaseds, urls,
|
| 755 |
+
offset_position)
|
| 756 |
+
|
| 757 |
+
writer = self.writer
|
| 758 |
+
path_codes = []
|
| 759 |
+
writer.start('defs')
|
| 760 |
+
for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
|
| 761 |
+
master_transform, paths, all_transforms)):
|
| 762 |
+
transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
|
| 763 |
+
d = self._convert_path(path, transform, simplify=False)
|
| 764 |
+
oid = 'C{:x}_{:x}_{}'.format(
|
| 765 |
+
self._path_collection_id, i, self._make_id('', d))
|
| 766 |
+
writer.element('path', id=oid, d=d)
|
| 767 |
+
path_codes.append(oid)
|
| 768 |
+
writer.end('defs')
|
| 769 |
+
|
| 770 |
+
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
|
| 771 |
+
gc, path_codes, offsets, offset_trans,
|
| 772 |
+
facecolors, edgecolors, linewidths, linestyles,
|
| 773 |
+
antialiaseds, urls, offset_position):
|
| 774 |
+
url = gc0.get_url()
|
| 775 |
+
if url is not None:
|
| 776 |
+
writer.start('a', attrib={'xlink:href': url})
|
| 777 |
+
clip_attrs = self._get_clip_attrs(gc0)
|
| 778 |
+
if clip_attrs:
|
| 779 |
+
writer.start('g', **clip_attrs)
|
| 780 |
+
attrib = {
|
| 781 |
+
'xlink:href': f'#{path_id}',
|
| 782 |
+
'x': _short_float_fmt(xo),
|
| 783 |
+
'y': _short_float_fmt(self.height - yo),
|
| 784 |
+
'style': self._get_style(gc0, rgbFace)
|
| 785 |
+
}
|
| 786 |
+
writer.element('use', attrib=attrib)
|
| 787 |
+
if clip_attrs:
|
| 788 |
+
writer.end('g')
|
| 789 |
+
if url is not None:
|
| 790 |
+
writer.end('a')
|
| 791 |
+
|
| 792 |
+
self._path_collection_id += 1
|
| 793 |
+
|
| 794 |
+
def _draw_gouraud_triangle(self, transformed_points, colors):
|
| 795 |
+
# This uses a method described here:
|
| 796 |
+
#
|
| 797 |
+
# http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html
|
| 798 |
+
#
|
| 799 |
+
# that uses three overlapping linear gradients to simulate a
|
| 800 |
+
# Gouraud triangle. Each gradient goes from fully opaque in
|
| 801 |
+
# one corner to fully transparent along the opposite edge.
|
| 802 |
+
# The line between the stop points is perpendicular to the
|
| 803 |
+
# opposite edge. Underlying these three gradients is a solid
|
| 804 |
+
# triangle whose color is the average of all three points.
|
| 805 |
+
|
| 806 |
+
avg_color = np.average(colors, axis=0)
|
| 807 |
+
if avg_color[-1] == 0:
|
| 808 |
+
# Skip fully-transparent triangles
|
| 809 |
+
return
|
| 810 |
+
|
| 811 |
+
writer = self.writer
|
| 812 |
+
writer.start('defs')
|
| 813 |
+
for i in range(3):
|
| 814 |
+
x1, y1 = transformed_points[i]
|
| 815 |
+
x2, y2 = transformed_points[(i + 1) % 3]
|
| 816 |
+
x3, y3 = transformed_points[(i + 2) % 3]
|
| 817 |
+
rgba_color = colors[i]
|
| 818 |
+
|
| 819 |
+
if x2 == x3:
|
| 820 |
+
xb = x2
|
| 821 |
+
yb = y1
|
| 822 |
+
elif y2 == y3:
|
| 823 |
+
xb = x1
|
| 824 |
+
yb = y2
|
| 825 |
+
else:
|
| 826 |
+
m1 = (y2 - y3) / (x2 - x3)
|
| 827 |
+
b1 = y2 - (m1 * x2)
|
| 828 |
+
m2 = -(1.0 / m1)
|
| 829 |
+
b2 = y1 - (m2 * x1)
|
| 830 |
+
xb = (-b1 + b2) / (m1 - m2)
|
| 831 |
+
yb = m2 * xb + b2
|
| 832 |
+
|
| 833 |
+
writer.start(
|
| 834 |
+
'linearGradient',
|
| 835 |
+
id=f"GR{self._n_gradients:x}_{i:d}",
|
| 836 |
+
gradientUnits="userSpaceOnUse",
|
| 837 |
+
x1=_short_float_fmt(x1), y1=_short_float_fmt(y1),
|
| 838 |
+
x2=_short_float_fmt(xb), y2=_short_float_fmt(yb))
|
| 839 |
+
writer.element(
|
| 840 |
+
'stop',
|
| 841 |
+
offset='1',
|
| 842 |
+
style=_generate_css({
|
| 843 |
+
'stop-color': rgb2hex(avg_color),
|
| 844 |
+
'stop-opacity': _short_float_fmt(rgba_color[-1])}))
|
| 845 |
+
writer.element(
|
| 846 |
+
'stop',
|
| 847 |
+
offset='0',
|
| 848 |
+
style=_generate_css({'stop-color': rgb2hex(rgba_color),
|
| 849 |
+
'stop-opacity': "0"}))
|
| 850 |
+
|
| 851 |
+
writer.end('linearGradient')
|
| 852 |
+
|
| 853 |
+
writer.end('defs')
|
| 854 |
+
|
| 855 |
+
# triangle formation using "path"
|
| 856 |
+
dpath = (f"M {_short_float_fmt(x1)},{_short_float_fmt(y1)}"
|
| 857 |
+
f" L {_short_float_fmt(x2)},{_short_float_fmt(y2)}"
|
| 858 |
+
f" {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z")
|
| 859 |
+
|
| 860 |
+
writer.element(
|
| 861 |
+
'path',
|
| 862 |
+
attrib={'d': dpath,
|
| 863 |
+
'fill': rgb2hex(avg_color),
|
| 864 |
+
'fill-opacity': '1',
|
| 865 |
+
'shape-rendering': "crispEdges"})
|
| 866 |
+
|
| 867 |
+
writer.start(
|
| 868 |
+
'g',
|
| 869 |
+
attrib={'stroke': "none",
|
| 870 |
+
'stroke-width': "0",
|
| 871 |
+
'shape-rendering': "crispEdges",
|
| 872 |
+
'filter': "url(#colorMat)"})
|
| 873 |
+
|
| 874 |
+
writer.element(
|
| 875 |
+
'path',
|
| 876 |
+
attrib={'d': dpath,
|
| 877 |
+
'fill': f'url(#GR{self._n_gradients:x}_0)',
|
| 878 |
+
'shape-rendering': "crispEdges"})
|
| 879 |
+
|
| 880 |
+
writer.element(
|
| 881 |
+
'path',
|
| 882 |
+
attrib={'d': dpath,
|
| 883 |
+
'fill': f'url(#GR{self._n_gradients:x}_1)',
|
| 884 |
+
'filter': 'url(#colorAdd)',
|
| 885 |
+
'shape-rendering': "crispEdges"})
|
| 886 |
+
|
| 887 |
+
writer.element(
|
| 888 |
+
'path',
|
| 889 |
+
attrib={'d': dpath,
|
| 890 |
+
'fill': f'url(#GR{self._n_gradients:x}_2)',
|
| 891 |
+
'filter': 'url(#colorAdd)',
|
| 892 |
+
'shape-rendering': "crispEdges"})
|
| 893 |
+
|
| 894 |
+
writer.end('g')
|
| 895 |
+
|
| 896 |
+
self._n_gradients += 1
|
| 897 |
+
|
| 898 |
+
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
|
| 899 |
+
transform):
|
| 900 |
+
writer = self.writer
|
| 901 |
+
writer.start('g', **self._get_clip_attrs(gc))
|
| 902 |
+
transform = transform.frozen()
|
| 903 |
+
trans_and_flip = self._make_flip_transform(transform)
|
| 904 |
+
|
| 905 |
+
if not self._has_gouraud:
|
| 906 |
+
self._has_gouraud = True
|
| 907 |
+
writer.start(
|
| 908 |
+
'filter',
|
| 909 |
+
id='colorAdd')
|
| 910 |
+
writer.element(
|
| 911 |
+
'feComposite',
|
| 912 |
+
attrib={'in': 'SourceGraphic'},
|
| 913 |
+
in2='BackgroundImage',
|
| 914 |
+
operator='arithmetic',
|
| 915 |
+
k2="1", k3="1")
|
| 916 |
+
writer.end('filter')
|
| 917 |
+
# feColorMatrix filter to correct opacity
|
| 918 |
+
writer.start(
|
| 919 |
+
'filter',
|
| 920 |
+
id='colorMat')
|
| 921 |
+
writer.element(
|
| 922 |
+
'feColorMatrix',
|
| 923 |
+
attrib={'type': 'matrix'},
|
| 924 |
+
values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ')
|
| 925 |
+
writer.end('filter')
|
| 926 |
+
|
| 927 |
+
for points, colors in zip(triangles_array, colors_array):
|
| 928 |
+
self._draw_gouraud_triangle(trans_and_flip.transform(points), colors)
|
| 929 |
+
writer.end('g')
|
| 930 |
+
|
| 931 |
+
def option_scale_image(self):
|
| 932 |
+
# docstring inherited
|
| 933 |
+
return True
|
| 934 |
+
|
| 935 |
+
def get_image_magnification(self):
|
| 936 |
+
return self.image_dpi / 72.0
|
| 937 |
+
|
| 938 |
+
def draw_image(self, gc, x, y, im, transform=None):
|
| 939 |
+
# docstring inherited
|
| 940 |
+
|
| 941 |
+
h, w = im.shape[:2]
|
| 942 |
+
|
| 943 |
+
if w == 0 or h == 0:
|
| 944 |
+
return
|
| 945 |
+
|
| 946 |
+
clip_attrs = self._get_clip_attrs(gc)
|
| 947 |
+
if clip_attrs:
|
| 948 |
+
# Can't apply clip-path directly to the image because the image has
|
| 949 |
+
# a transformation, which would also be applied to the clip-path.
|
| 950 |
+
self.writer.start('g', **clip_attrs)
|
| 951 |
+
|
| 952 |
+
url = gc.get_url()
|
| 953 |
+
if url is not None:
|
| 954 |
+
self.writer.start('a', attrib={'xlink:href': url})
|
| 955 |
+
|
| 956 |
+
attrib = {}
|
| 957 |
+
oid = gc.get_gid()
|
| 958 |
+
if mpl.rcParams['svg.image_inline']:
|
| 959 |
+
buf = BytesIO()
|
| 960 |
+
Image.fromarray(im).save(buf, format="png")
|
| 961 |
+
oid = oid or self._make_id('image', buf.getvalue())
|
| 962 |
+
attrib['xlink:href'] = (
|
| 963 |
+
"data:image/png;base64,\n" +
|
| 964 |
+
base64.b64encode(buf.getvalue()).decode('ascii'))
|
| 965 |
+
else:
|
| 966 |
+
if self.basename is None:
|
| 967 |
+
raise ValueError("Cannot save image data to filesystem when "
|
| 968 |
+
"writing SVG to an in-memory buffer")
|
| 969 |
+
filename = f'{self.basename}.image{next(self._image_counter)}.png'
|
| 970 |
+
_log.info('Writing image file for inclusion: %s', filename)
|
| 971 |
+
Image.fromarray(im).save(filename)
|
| 972 |
+
oid = oid or 'Im_' + self._make_id('image', filename)
|
| 973 |
+
attrib['xlink:href'] = filename
|
| 974 |
+
attrib['id'] = oid
|
| 975 |
+
|
| 976 |
+
if transform is None:
|
| 977 |
+
w = 72.0 * w / self.image_dpi
|
| 978 |
+
h = 72.0 * h / self.image_dpi
|
| 979 |
+
|
| 980 |
+
self.writer.element(
|
| 981 |
+
'image',
|
| 982 |
+
transform=_generate_transform([
|
| 983 |
+
('scale', (1, -1)), ('translate', (0, -h))]),
|
| 984 |
+
x=_short_float_fmt(x),
|
| 985 |
+
y=_short_float_fmt(-(self.height - y - h)),
|
| 986 |
+
width=_short_float_fmt(w), height=_short_float_fmt(h),
|
| 987 |
+
attrib=attrib)
|
| 988 |
+
else:
|
| 989 |
+
alpha = gc.get_alpha()
|
| 990 |
+
if alpha != 1.0:
|
| 991 |
+
attrib['opacity'] = _short_float_fmt(alpha)
|
| 992 |
+
|
| 993 |
+
flipped = (
|
| 994 |
+
Affine2D().scale(1.0 / w, 1.0 / h) +
|
| 995 |
+
transform +
|
| 996 |
+
Affine2D()
|
| 997 |
+
.translate(x, y)
|
| 998 |
+
.scale(1.0, -1.0)
|
| 999 |
+
.translate(0.0, self.height))
|
| 1000 |
+
|
| 1001 |
+
attrib['transform'] = _generate_transform(
|
| 1002 |
+
[('matrix', flipped.frozen())])
|
| 1003 |
+
attrib['style'] = (
|
| 1004 |
+
'image-rendering:crisp-edges;'
|
| 1005 |
+
'image-rendering:pixelated')
|
| 1006 |
+
self.writer.element(
|
| 1007 |
+
'image',
|
| 1008 |
+
width=_short_float_fmt(w), height=_short_float_fmt(h),
|
| 1009 |
+
attrib=attrib)
|
| 1010 |
+
|
| 1011 |
+
if url is not None:
|
| 1012 |
+
self.writer.end('a')
|
| 1013 |
+
if clip_attrs:
|
| 1014 |
+
self.writer.end('g')
|
| 1015 |
+
|
| 1016 |
+
def _update_glyph_map_defs(self, glyph_map_new):
|
| 1017 |
+
"""
|
| 1018 |
+
Emit definitions for not-yet-defined glyphs, and record them as having
|
| 1019 |
+
been defined.
|
| 1020 |
+
"""
|
| 1021 |
+
writer = self.writer
|
| 1022 |
+
if glyph_map_new:
|
| 1023 |
+
writer.start('defs')
|
| 1024 |
+
for char_id, (vertices, codes) in glyph_map_new.items():
|
| 1025 |
+
char_id = self._adjust_char_id(char_id)
|
| 1026 |
+
# x64 to go back to FreeType's internal (integral) units.
|
| 1027 |
+
path_data = self._convert_path(
|
| 1028 |
+
Path(vertices * 64, codes), simplify=False)
|
| 1029 |
+
writer.element(
|
| 1030 |
+
'path', id=char_id, d=path_data,
|
| 1031 |
+
transform=_generate_transform([('scale', (1 / 64,))]))
|
| 1032 |
+
writer.end('defs')
|
| 1033 |
+
self._glyph_map.update(glyph_map_new)
|
| 1034 |
+
|
| 1035 |
+
def _adjust_char_id(self, char_id):
|
| 1036 |
+
return char_id.replace("%20", "_")
|
| 1037 |
+
|
| 1038 |
+
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None):
|
| 1039 |
+
# docstring inherited
|
| 1040 |
+
writer = self.writer
|
| 1041 |
+
|
| 1042 |
+
writer.comment(s)
|
| 1043 |
+
|
| 1044 |
+
glyph_map = self._glyph_map
|
| 1045 |
+
|
| 1046 |
+
text2path = self._text2path
|
| 1047 |
+
color = rgb2hex(gc.get_rgb())
|
| 1048 |
+
fontsize = prop.get_size_in_points()
|
| 1049 |
+
|
| 1050 |
+
style = {}
|
| 1051 |
+
if color != '#000000':
|
| 1052 |
+
style['fill'] = color
|
| 1053 |
+
alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]
|
| 1054 |
+
if alpha != 1:
|
| 1055 |
+
style['opacity'] = _short_float_fmt(alpha)
|
| 1056 |
+
font_scale = fontsize / text2path.FONT_SCALE
|
| 1057 |
+
attrib = {
|
| 1058 |
+
'style': _generate_css(style),
|
| 1059 |
+
'transform': _generate_transform([
|
| 1060 |
+
('translate', (x, y)),
|
| 1061 |
+
('rotate', (-angle,)),
|
| 1062 |
+
('scale', (font_scale, -font_scale))]),
|
| 1063 |
+
}
|
| 1064 |
+
writer.start('g', attrib=attrib)
|
| 1065 |
+
|
| 1066 |
+
if not ismath:
|
| 1067 |
+
font = text2path._get_font(prop)
|
| 1068 |
+
_glyphs = text2path.get_glyphs_with_font(
|
| 1069 |
+
font, s, glyph_map=glyph_map, return_new_glyphs_only=True)
|
| 1070 |
+
glyph_info, glyph_map_new, rects = _glyphs
|
| 1071 |
+
self._update_glyph_map_defs(glyph_map_new)
|
| 1072 |
+
|
| 1073 |
+
for glyph_id, xposition, yposition, scale in glyph_info:
|
| 1074 |
+
writer.element(
|
| 1075 |
+
'use',
|
| 1076 |
+
transform=_generate_transform([
|
| 1077 |
+
('translate', (xposition, yposition)),
|
| 1078 |
+
('scale', (scale,)),
|
| 1079 |
+
]),
|
| 1080 |
+
attrib={'xlink:href': f'#{glyph_id}'})
|
| 1081 |
+
|
| 1082 |
+
else:
|
| 1083 |
+
if ismath == "TeX":
|
| 1084 |
+
_glyphs = text2path.get_glyphs_tex(
|
| 1085 |
+
prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)
|
| 1086 |
+
else:
|
| 1087 |
+
_glyphs = text2path.get_glyphs_mathtext(
|
| 1088 |
+
prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)
|
| 1089 |
+
glyph_info, glyph_map_new, rects = _glyphs
|
| 1090 |
+
self._update_glyph_map_defs(glyph_map_new)
|
| 1091 |
+
|
| 1092 |
+
for char_id, xposition, yposition, scale in glyph_info:
|
| 1093 |
+
char_id = self._adjust_char_id(char_id)
|
| 1094 |
+
writer.element(
|
| 1095 |
+
'use',
|
| 1096 |
+
transform=_generate_transform([
|
| 1097 |
+
('translate', (xposition, yposition)),
|
| 1098 |
+
('scale', (scale,)),
|
| 1099 |
+
]),
|
| 1100 |
+
attrib={'xlink:href': f'#{char_id}'})
|
| 1101 |
+
|
| 1102 |
+
for verts, codes in rects:
|
| 1103 |
+
path = Path(verts, codes)
|
| 1104 |
+
path_data = self._convert_path(path, simplify=False)
|
| 1105 |
+
writer.element('path', d=path_data)
|
| 1106 |
+
|
| 1107 |
+
writer.end('g')
|
| 1108 |
+
|
| 1109 |
+
def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None):
|
| 1110 |
+
# NOTE: If you change the font styling CSS, then be sure the check for
|
| 1111 |
+
# svg.fonttype = none in `lib/matplotlib/testing/compare.py::convert` remains in
|
| 1112 |
+
# sync. Also be sure to re-generate any SVG using this mode, or else such tests
|
| 1113 |
+
# will fail to use the right converter for the expected images, and they will
|
| 1114 |
+
# fail strangely.
|
| 1115 |
+
writer = self.writer
|
| 1116 |
+
|
| 1117 |
+
color = rgb2hex(gc.get_rgb())
|
| 1118 |
+
font_style = {}
|
| 1119 |
+
color_style = {}
|
| 1120 |
+
if color != '#000000':
|
| 1121 |
+
color_style['fill'] = color
|
| 1122 |
+
|
| 1123 |
+
alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]
|
| 1124 |
+
if alpha != 1:
|
| 1125 |
+
color_style['opacity'] = _short_float_fmt(alpha)
|
| 1126 |
+
|
| 1127 |
+
if not ismath:
|
| 1128 |
+
attrib = {}
|
| 1129 |
+
|
| 1130 |
+
# Separate font style in their separate attributes
|
| 1131 |
+
if prop.get_style() != 'normal':
|
| 1132 |
+
font_style['font-style'] = prop.get_style()
|
| 1133 |
+
if prop.get_variant() != 'normal':
|
| 1134 |
+
font_style['font-variant'] = prop.get_variant()
|
| 1135 |
+
weight = fm.weight_dict[prop.get_weight()]
|
| 1136 |
+
if weight != 400:
|
| 1137 |
+
font_style['font-weight'] = f'{weight}'
|
| 1138 |
+
|
| 1139 |
+
def _normalize_sans(name):
|
| 1140 |
+
return 'sans-serif' if name in ['sans', 'sans serif'] else name
|
| 1141 |
+
|
| 1142 |
+
def _expand_family_entry(fn):
|
| 1143 |
+
fn = _normalize_sans(fn)
|
| 1144 |
+
# prepend generic font families with all configured font names
|
| 1145 |
+
if fn in fm.font_family_aliases:
|
| 1146 |
+
# get all of the font names and fix spelling of sans-serif
|
| 1147 |
+
# (we accept 3 ways CSS only supports 1)
|
| 1148 |
+
for name in fm.FontManager._expand_aliases(fn):
|
| 1149 |
+
yield _normalize_sans(name)
|
| 1150 |
+
# whether a generic name or a family name, it must appear at
|
| 1151 |
+
# least once
|
| 1152 |
+
yield fn
|
| 1153 |
+
|
| 1154 |
+
def _get_all_quoted_names(prop):
|
| 1155 |
+
# only quote specific names, not generic names
|
| 1156 |
+
return [name if name in fm.font_family_aliases else repr(name)
|
| 1157 |
+
for entry in prop.get_family()
|
| 1158 |
+
for name in _expand_family_entry(entry)]
|
| 1159 |
+
|
| 1160 |
+
font_style['font-size'] = f'{_short_float_fmt(prop.get_size())}px'
|
| 1161 |
+
# ensure expansion, quoting, and dedupe of font names
|
| 1162 |
+
font_style['font-family'] = ", ".join(
|
| 1163 |
+
dict.fromkeys(_get_all_quoted_names(prop))
|
| 1164 |
+
)
|
| 1165 |
+
|
| 1166 |
+
if prop.get_stretch() != 'normal':
|
| 1167 |
+
font_style['font-stretch'] = prop.get_stretch()
|
| 1168 |
+
attrib['style'] = _generate_css({**font_style, **color_style})
|
| 1169 |
+
|
| 1170 |
+
if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"):
|
| 1171 |
+
# If text anchoring can be supported, get the original
|
| 1172 |
+
# coordinates and add alignment information.
|
| 1173 |
+
|
| 1174 |
+
# Get anchor coordinates.
|
| 1175 |
+
transform = mtext.get_transform()
|
| 1176 |
+
ax, ay = transform.transform(mtext.get_unitless_position())
|
| 1177 |
+
ay = self.height - ay
|
| 1178 |
+
|
| 1179 |
+
# Don't do vertical anchor alignment. Most applications do not
|
| 1180 |
+
# support 'alignment-baseline' yet. Apply the vertical layout
|
| 1181 |
+
# to the anchor point manually for now.
|
| 1182 |
+
angle_rad = np.deg2rad(angle)
|
| 1183 |
+
dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)])
|
| 1184 |
+
v_offset = np.dot(dir_vert, [(x - ax), (y - ay)])
|
| 1185 |
+
ax = ax + v_offset * dir_vert[0]
|
| 1186 |
+
ay = ay + v_offset * dir_vert[1]
|
| 1187 |
+
|
| 1188 |
+
ha_mpl_to_svg = {'left': 'start', 'right': 'end',
|
| 1189 |
+
'center': 'middle'}
|
| 1190 |
+
font_style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()]
|
| 1191 |
+
|
| 1192 |
+
attrib['x'] = _short_float_fmt(ax)
|
| 1193 |
+
attrib['y'] = _short_float_fmt(ay)
|
| 1194 |
+
attrib['style'] = _generate_css({**font_style, **color_style})
|
| 1195 |
+
attrib['transform'] = _generate_transform([
|
| 1196 |
+
("rotate", (-angle, ax, ay))])
|
| 1197 |
+
|
| 1198 |
+
else:
|
| 1199 |
+
attrib['transform'] = _generate_transform([
|
| 1200 |
+
('translate', (x, y)),
|
| 1201 |
+
('rotate', (-angle,))])
|
| 1202 |
+
|
| 1203 |
+
writer.element('text', s, attrib=attrib)
|
| 1204 |
+
|
| 1205 |
+
else:
|
| 1206 |
+
writer.comment(s)
|
| 1207 |
+
|
| 1208 |
+
width, height, descent, glyphs, rects = \
|
| 1209 |
+
self._text2path.mathtext_parser.parse(s, 72, prop)
|
| 1210 |
+
|
| 1211 |
+
# Apply attributes to 'g', not 'text', because we likely have some
|
| 1212 |
+
# rectangles as well with the same style and transformation.
|
| 1213 |
+
writer.start('g',
|
| 1214 |
+
style=_generate_css({**font_style, **color_style}),
|
| 1215 |
+
transform=_generate_transform([
|
| 1216 |
+
('translate', (x, y)),
|
| 1217 |
+
('rotate', (-angle,))]),
|
| 1218 |
+
)
|
| 1219 |
+
|
| 1220 |
+
writer.start('text')
|
| 1221 |
+
|
| 1222 |
+
# Sort the characters by font, and output one tspan for each.
|
| 1223 |
+
spans = {}
|
| 1224 |
+
for font, fontsize, thetext, new_x, new_y in glyphs:
|
| 1225 |
+
entry = fm.ttfFontProperty(font)
|
| 1226 |
+
font_style = {}
|
| 1227 |
+
# Separate font style in its separate attributes
|
| 1228 |
+
if entry.style != 'normal':
|
| 1229 |
+
font_style['font-style'] = entry.style
|
| 1230 |
+
if entry.variant != 'normal':
|
| 1231 |
+
font_style['font-variant'] = entry.variant
|
| 1232 |
+
if entry.weight != 400:
|
| 1233 |
+
font_style['font-weight'] = f'{entry.weight}'
|
| 1234 |
+
font_style['font-size'] = f'{_short_float_fmt(fontsize)}px'
|
| 1235 |
+
font_style['font-family'] = f'{entry.name!r}' # ensure quoting
|
| 1236 |
+
if entry.stretch != 'normal':
|
| 1237 |
+
font_style['font-stretch'] = entry.stretch
|
| 1238 |
+
style = _generate_css({**font_style, **color_style})
|
| 1239 |
+
if thetext == 32:
|
| 1240 |
+
thetext = 0xa0 # non-breaking space
|
| 1241 |
+
spans.setdefault(style, []).append((new_x, -new_y, thetext))
|
| 1242 |
+
|
| 1243 |
+
for style, chars in spans.items():
|
| 1244 |
+
chars.sort() # Sort by increasing x position
|
| 1245 |
+
for x, y, t in chars: # Output one tspan for each character
|
| 1246 |
+
writer.element(
|
| 1247 |
+
'tspan',
|
| 1248 |
+
chr(t),
|
| 1249 |
+
x=_short_float_fmt(x),
|
| 1250 |
+
y=_short_float_fmt(y),
|
| 1251 |
+
style=style)
|
| 1252 |
+
|
| 1253 |
+
writer.end('text')
|
| 1254 |
+
|
| 1255 |
+
for x, y, width, height in rects:
|
| 1256 |
+
writer.element(
|
| 1257 |
+
'rect',
|
| 1258 |
+
x=_short_float_fmt(x),
|
| 1259 |
+
y=_short_float_fmt(-y-1),
|
| 1260 |
+
width=_short_float_fmt(width),
|
| 1261 |
+
height=_short_float_fmt(height)
|
| 1262 |
+
)
|
| 1263 |
+
|
| 1264 |
+
writer.end('g')
|
| 1265 |
+
|
| 1266 |
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
| 1267 |
+
# docstring inherited
|
| 1268 |
+
|
| 1269 |
+
clip_attrs = self._get_clip_attrs(gc)
|
| 1270 |
+
if clip_attrs:
|
| 1271 |
+
# Cannot apply clip-path directly to the text, because
|
| 1272 |
+
# it has a transformation
|
| 1273 |
+
self.writer.start('g', **clip_attrs)
|
| 1274 |
+
|
| 1275 |
+
if gc.get_url() is not None:
|
| 1276 |
+
self.writer.start('a', {'xlink:href': gc.get_url()})
|
| 1277 |
+
|
| 1278 |
+
if mpl.rcParams['svg.fonttype'] == 'path':
|
| 1279 |
+
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext)
|
| 1280 |
+
else:
|
| 1281 |
+
self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext)
|
| 1282 |
+
|
| 1283 |
+
if gc.get_url() is not None:
|
| 1284 |
+
self.writer.end('a')
|
| 1285 |
+
|
| 1286 |
+
if clip_attrs:
|
| 1287 |
+
self.writer.end('g')
|
| 1288 |
+
|
| 1289 |
+
def flipy(self):
|
| 1290 |
+
# docstring inherited
|
| 1291 |
+
return True
|
| 1292 |
+
|
| 1293 |
+
def get_canvas_width_height(self):
|
| 1294 |
+
# docstring inherited
|
| 1295 |
+
return self.width, self.height
|
| 1296 |
+
|
| 1297 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 1298 |
+
# docstring inherited
|
| 1299 |
+
return self._text2path.get_text_width_height_descent(s, prop, ismath)
|
| 1300 |
+
|
| 1301 |
+
|
| 1302 |
+
class FigureCanvasSVG(FigureCanvasBase):
|
| 1303 |
+
filetypes = {'svg': 'Scalable Vector Graphics',
|
| 1304 |
+
'svgz': 'Scalable Vector Graphics'}
|
| 1305 |
+
|
| 1306 |
+
fixed_dpi = 72
|
| 1307 |
+
|
| 1308 |
+
def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
|
| 1309 |
+
"""
|
| 1310 |
+
Parameters
|
| 1311 |
+
----------
|
| 1312 |
+
filename : str or path-like or file-like
|
| 1313 |
+
Output target; if a string, a file will be opened for writing.
|
| 1314 |
+
|
| 1315 |
+
metadata : dict[str, Any], optional
|
| 1316 |
+
Metadata in the SVG file defined as key-value pairs of strings,
|
| 1317 |
+
datetimes, or lists of strings, e.g., ``{'Creator': 'My software',
|
| 1318 |
+
'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}``.
|
| 1319 |
+
|
| 1320 |
+
The standard keys and their value types are:
|
| 1321 |
+
|
| 1322 |
+
* *str*: ``'Coverage'``, ``'Description'``, ``'Format'``,
|
| 1323 |
+
``'Identifier'``, ``'Language'``, ``'Relation'``, ``'Source'``,
|
| 1324 |
+
``'Title'``, and ``'Type'``.
|
| 1325 |
+
* *str* or *list of str*: ``'Contributor'``, ``'Creator'``,
|
| 1326 |
+
``'Keywords'``, ``'Publisher'``, and ``'Rights'``.
|
| 1327 |
+
* *str*, *date*, *datetime*, or *tuple* of same: ``'Date'``. If a
|
| 1328 |
+
non-*str*, then it will be formatted as ISO 8601.
|
| 1329 |
+
|
| 1330 |
+
Values have been predefined for ``'Creator'``, ``'Date'``,
|
| 1331 |
+
``'Format'``, and ``'Type'``. They can be removed by setting them
|
| 1332 |
+
to `None`.
|
| 1333 |
+
|
| 1334 |
+
Information is encoded as `Dublin Core Metadata`__.
|
| 1335 |
+
|
| 1336 |
+
.. _DC: https://www.dublincore.org/specifications/dublin-core/
|
| 1337 |
+
|
| 1338 |
+
__ DC_
|
| 1339 |
+
"""
|
| 1340 |
+
with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh:
|
| 1341 |
+
if not cbook.file_requires_unicode(fh):
|
| 1342 |
+
fh = codecs.getwriter('utf-8')(fh)
|
| 1343 |
+
dpi = self.figure.dpi
|
| 1344 |
+
self.figure.dpi = 72
|
| 1345 |
+
width, height = self.figure.get_size_inches()
|
| 1346 |
+
w, h = width * 72, height * 72
|
| 1347 |
+
renderer = MixedModeRenderer(
|
| 1348 |
+
self.figure, width, height, dpi,
|
| 1349 |
+
RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata),
|
| 1350 |
+
bbox_inches_restore=bbox_inches_restore)
|
| 1351 |
+
self.figure.draw(renderer)
|
| 1352 |
+
renderer.finalize()
|
| 1353 |
+
|
| 1354 |
+
def print_svgz(self, filename, **kwargs):
|
| 1355 |
+
with (cbook.open_file_cm(filename, "wb") as fh,
|
| 1356 |
+
gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter):
|
| 1357 |
+
return self.print_svg(gzipwriter, **kwargs)
|
| 1358 |
+
|
| 1359 |
+
def get_default_filetype(self):
|
| 1360 |
+
return 'svg'
|
| 1361 |
+
|
| 1362 |
+
def draw(self):
|
| 1363 |
+
self.figure.draw_without_rendering()
|
| 1364 |
+
return super().draw()
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
FigureManagerSVG = FigureManagerBase
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
svgProlog = """\
|
| 1371 |
+
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
| 1372 |
+
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
|
| 1373 |
+
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
| 1374 |
+
"""
|
| 1375 |
+
|
| 1376 |
+
|
| 1377 |
+
@_Backend.export
|
| 1378 |
+
class _BackendSVG(_Backend):
|
| 1379 |
+
backend_version = mpl.__version__
|
| 1380 |
+
FigureCanvas = FigureCanvasSVG
|