mapelements 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mapelements/__init__.py +50 -0
- mapelements/api.py +114 -0
- mapelements/artists.py +335 -0
- mapelements/export.py +153 -0
- mapelements/geom.py +101 -0
- mapelements/py.typed +0 -0
- mapelements/style.py +71 -0
- mapelements-0.1.0.dist-info/METADATA +198 -0
- mapelements-0.1.0.dist-info/RECORD +12 -0
- mapelements-0.1.0.dist-info/WHEEL +5 -0
- mapelements-0.1.0.dist-info/licenses/LICENSE +21 -0
- mapelements-0.1.0.dist-info/top_level.txt +1 -0
mapelements/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""mapelements — journal-quality vector map elements for matplotlib.
|
|
3
|
+
|
|
4
|
+
Scale bars, north arrows and graticules implemented as matplotlib ``Artist``
|
|
5
|
+
subclasses. Add them with ``ax.add_artist(...)`` like any other artist; they are
|
|
6
|
+
built from ``Patch`` / ``Line2D`` / ``Text`` only, so PDF/SVG exports keep
|
|
7
|
+
editable paths and live text.
|
|
8
|
+
|
|
9
|
+
Three ways to use the package::
|
|
10
|
+
|
|
11
|
+
# 1) artist style
|
|
12
|
+
from mapelements import ScaleBar, NorthArrow, Graticule
|
|
13
|
+
ax.add_artist(ScaleBar(length=500, crs=CRS))
|
|
14
|
+
ax.add_artist(NorthArrow(crs=CRS, loc="upper right"))
|
|
15
|
+
|
|
16
|
+
# 2) function style
|
|
17
|
+
import mapelements
|
|
18
|
+
mapelements.scale_bar(ax, length=500, crs=CRS)
|
|
19
|
+
|
|
20
|
+
# 3) one call for the whole map furniture
|
|
21
|
+
mapelements.finish(ax, crs=CRS, data=gdf)
|
|
22
|
+
mapelements.save(fig, "Fig1")
|
|
23
|
+
"""
|
|
24
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
25
|
+
|
|
26
|
+
from .api import finish, fit
|
|
27
|
+
from .artists import (Graticule, NorthArrow, ScaleBar, graticule,
|
|
28
|
+
north_arrow, scale_bar)
|
|
29
|
+
from .export import NotVectorError, check_vector, save
|
|
30
|
+
from .geom import CN_ALBERS, map_width_km, nice_length
|
|
31
|
+
from .style import DOUBLE_COLUMN, MM, SINGLE_COLUMN, figure, pub_style
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
__version__ = version("mapelements")
|
|
35
|
+
except PackageNotFoundError: # 直接从源码目录运行
|
|
36
|
+
__version__ = "0.1.0"
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
# artist 类
|
|
40
|
+
"ScaleBar", "NorthArrow", "Graticule",
|
|
41
|
+
# 函数封装
|
|
42
|
+
"scale_bar", "north_arrow", "graticule",
|
|
43
|
+
# 收尾与导出
|
|
44
|
+
"finish", "fit", "save", "check_vector", "NotVectorError",
|
|
45
|
+
# 版式
|
|
46
|
+
"pub_style", "figure", "MM", "SINGLE_COLUMN", "DOUBLE_COLUMN",
|
|
47
|
+
# 常量 / 工具
|
|
48
|
+
"CN_ALBERS", "nice_length", "map_width_km",
|
|
49
|
+
"__version__",
|
|
50
|
+
]
|
mapelements/api.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""One-call helpers: finish() for the map furniture, fit() for the layout."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .artists import Graticule, NorthArrow, ScaleBar
|
|
6
|
+
from .geom import as_pyproj, extent_from_axes, project_extent
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def fit(ax):
|
|
10
|
+
"""Make a single-panel map fill the canvas.
|
|
11
|
+
|
|
12
|
+
Removes the subplot margins and adjusts the figure height to the data aspect
|
|
13
|
+
ratio. It only acts when the figure contains exactly one Axes; multi-panel
|
|
14
|
+
figures are left untouched. Call it after setting the limits and aspect, and
|
|
15
|
+
before adding the map elements.
|
|
16
|
+
"""
|
|
17
|
+
fig = ax.figure
|
|
18
|
+
if len(fig.axes) != 1:
|
|
19
|
+
return ax
|
|
20
|
+
ax.set_position([0, 0, 1, 1])
|
|
21
|
+
x0, x1 = ax.get_xlim()
|
|
22
|
+
y0, y1 = ax.get_ylim()
|
|
23
|
+
w_in = fig.get_size_inches()[0]
|
|
24
|
+
fig.set_size_inches(w_in, w_in * (y1 - y0) / (x1 - x0))
|
|
25
|
+
return ax
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def finish(ax, crs=None, data=None, extent=None,
|
|
29
|
+
graticule=5.0, scalebar="auto", north="upper right",
|
|
30
|
+
scalebar_loc=None, pad=0.02, legend=False, fill=True, zorder=30):
|
|
31
|
+
"""Add the map furniture in one call.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
ax : matplotlib.axes.Axes
|
|
36
|
+
A plain projected Axes or a cartopy GeoAxes.
|
|
37
|
+
crs : CRS-like, optional
|
|
38
|
+
Projection; defaults to ``ax.projection``.
|
|
39
|
+
data : geopandas.GeoDataFrame, optional
|
|
40
|
+
Used to derive the extent from ``total_bounds`` after ``to_crs(crs)``.
|
|
41
|
+
extent : (lon0, lon1, lat0, lat1), optional
|
|
42
|
+
Explicit geographic box; takes precedence over ``data``.
|
|
43
|
+
graticule : float or None
|
|
44
|
+
Spacing in degrees; ``None`` or ``False`` disables the graticule.
|
|
45
|
+
scalebar : float, "auto" or None
|
|
46
|
+
Bar length in km; ``"auto"`` rounds to a 1/2/5 x 10^n value.
|
|
47
|
+
north : str, tuple or None
|
|
48
|
+
Position alias ("upper right", ...), axes-fraction tuple, or disabled.
|
|
49
|
+
scalebar_loc : tuple, optional
|
|
50
|
+
Bar position; defaults to the corner opposite the north arrow.
|
|
51
|
+
pad : float
|
|
52
|
+
Fractional padding around the extent (default 2 %).
|
|
53
|
+
legend : bool
|
|
54
|
+
Place a borderless legend in the upper-left corner.
|
|
55
|
+
fill : bool
|
|
56
|
+
Call :func:`fit` for single-panel figures (ignored otherwise).
|
|
57
|
+
|
|
58
|
+
Returns
|
|
59
|
+
-------
|
|
60
|
+
matplotlib.axes.Axes
|
|
61
|
+
The same axes, for chaining.
|
|
62
|
+
"""
|
|
63
|
+
if crs is None:
|
|
64
|
+
crs = getattr(ax, "projection", None)
|
|
65
|
+
if crs is None:
|
|
66
|
+
raise ValueError("finish() needs crs=: pass the projected CRS explicitly for plain Axes")
|
|
67
|
+
crs = as_pyproj(crs)
|
|
68
|
+
|
|
69
|
+
# 1) 范围
|
|
70
|
+
if extent is not None:
|
|
71
|
+
x0, x1, y0, y1 = project_extent(crs, extent)
|
|
72
|
+
ax.set_xlim(x0, x1)
|
|
73
|
+
ax.set_ylim(y0, y1)
|
|
74
|
+
elif data is not None:
|
|
75
|
+
b = data.to_crs(crs).total_bounds
|
|
76
|
+
ax.set_xlim(b[0], b[2])
|
|
77
|
+
ax.set_ylim(b[1], b[3])
|
|
78
|
+
|
|
79
|
+
x0, x1 = ax.get_xlim()
|
|
80
|
+
y0, y1 = ax.get_ylim()
|
|
81
|
+
ax.set_xlim(x0 - pad * (x1 - x0), x1 + pad * (x1 - x0))
|
|
82
|
+
ax.set_ylim(y0 - pad * (y1 - y0), y1 + pad * (y1 - y0))
|
|
83
|
+
ax.set_aspect("equal")
|
|
84
|
+
ax.set_axis_off()
|
|
85
|
+
|
|
86
|
+
# 1.5) 单幅地图铺满画布(多子图时自动跳过)
|
|
87
|
+
if fill:
|
|
88
|
+
fit(ax)
|
|
89
|
+
|
|
90
|
+
# 2) 经纬网范围
|
|
91
|
+
if extent is None:
|
|
92
|
+
extent = extent_from_axes(ax, crs)
|
|
93
|
+
if graticule:
|
|
94
|
+
ax.add_artist(Graticule(crs=crs, extent=extent, step=graticule))
|
|
95
|
+
|
|
96
|
+
# 3) 比例尺(默认放在指北针的斜对角)
|
|
97
|
+
if scalebar_loc is None:
|
|
98
|
+
up = isinstance(north, str) and north.startswith("upper")
|
|
99
|
+
scalebar_loc = (0.05, 0.06) if up else (0.05, 0.90)
|
|
100
|
+
if scalebar:
|
|
101
|
+
ax.add_artist(ScaleBar(length=scalebar, crs=crs,
|
|
102
|
+
loc=scalebar_loc, zorder=zorder))
|
|
103
|
+
|
|
104
|
+
# 4) 指北针
|
|
105
|
+
if north:
|
|
106
|
+
ax.add_artist(NorthArrow(crs=crs, loc=north, zorder=zorder))
|
|
107
|
+
|
|
108
|
+
# 5) 图例
|
|
109
|
+
if legend:
|
|
110
|
+
ax.legend(loc="upper left", bbox_to_anchor=(0.012, 0.988),
|
|
111
|
+
fontsize=6.5, frameon=False, borderaxespad=0.2,
|
|
112
|
+
handlelength=1.2, borderpad=0.3, labelspacing=0.35)
|
|
113
|
+
|
|
114
|
+
return ax
|
mapelements/artists.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Vector map elements implemented as matplotlib Artist subclasses.
|
|
3
|
+
|
|
4
|
+
Use them like any other artist::
|
|
5
|
+
|
|
6
|
+
from mapelements import ScaleBar, NorthArrow, Graticule
|
|
7
|
+
|
|
8
|
+
ax.add_artist(ScaleBar(length=500, crs=CRS))
|
|
9
|
+
ax.add_artist(NorthArrow(crs=CRS, loc="upper right"))
|
|
10
|
+
ax.add_artist(Graticule(crs=CRS, extent=(94, 121, 26, 43), step=5))
|
|
11
|
+
|
|
12
|
+
Or build one object and copy it onto several panels::
|
|
13
|
+
|
|
14
|
+
sb = ScaleBar(length=500, crs=CRS)
|
|
15
|
+
ax1.add_artist(sb.copy())
|
|
16
|
+
ax2.add_artist(sb.copy())
|
|
17
|
+
|
|
18
|
+
Every child artist is a Patch, LineCollection or Text. Geometry is rebuilt at
|
|
19
|
+
draw time from the current axis limits and figure size, so the elements stay
|
|
20
|
+
correct after zooming, resizing or re-layout, and they remain vector in PDF/SVG.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import math
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
from matplotlib.artist import Artist
|
|
28
|
+
from matplotlib.collections import LineCollection
|
|
29
|
+
from matplotlib.patches import FancyArrow, Rectangle
|
|
30
|
+
from matplotlib.text import Text
|
|
31
|
+
from matplotlib.transforms import Bbox
|
|
32
|
+
|
|
33
|
+
from .geom import (GEOD, NORTH_LOCS, as_pyproj, data_per_pt, frac_per_pt,
|
|
34
|
+
map_width_km, nice_length, transformers)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ------------------------------------------------------------------ 基类
|
|
38
|
+
class _VectorArtist(Artist):
|
|
39
|
+
"""Base class for composite vector artists.
|
|
40
|
+
|
|
41
|
+
``draw()`` rebuilds the child primitives and renders them one by one. No
|
|
42
|
+
offsetbox and no rasterisation is involved.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, zorder=30):
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.set_zorder(zorder)
|
|
48
|
+
self.set_clip_on(False)
|
|
49
|
+
self._kids = []
|
|
50
|
+
|
|
51
|
+
# 子类实现:向 self._kids 追加 Patch / LineCollection / Text
|
|
52
|
+
def _build(self, renderer): # pragma: no cover - 抽象
|
|
53
|
+
raise NotImplementedError
|
|
54
|
+
|
|
55
|
+
def draw(self, renderer, *args, **kwargs):
|
|
56
|
+
if not self.get_visible():
|
|
57
|
+
return
|
|
58
|
+
self._kids = []
|
|
59
|
+
self._build(renderer)
|
|
60
|
+
for kid in self._kids:
|
|
61
|
+
kid.set_figure(self.figure)
|
|
62
|
+
kid.draw(renderer)
|
|
63
|
+
|
|
64
|
+
def get_window_extent(self, renderer=None):
|
|
65
|
+
if self.figure is None:
|
|
66
|
+
return Bbox.null()
|
|
67
|
+
if renderer is None:
|
|
68
|
+
try:
|
|
69
|
+
renderer = self.figure.canvas.get_renderer()
|
|
70
|
+
except Exception:
|
|
71
|
+
return Bbox.null()
|
|
72
|
+
self._kids = []
|
|
73
|
+
self._build(renderer)
|
|
74
|
+
if not self._kids:
|
|
75
|
+
return Bbox.null()
|
|
76
|
+
for kid in self._kids:
|
|
77
|
+
kid.set_figure(self.figure)
|
|
78
|
+
return Bbox.union([k.get_window_extent(renderer) for k in self._kids])
|
|
79
|
+
|
|
80
|
+
def copy(self):
|
|
81
|
+
"""Return a copy that can be added to another Axes."""
|
|
82
|
+
return type(self)(**dict(self._params))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _prop(name):
|
|
86
|
+
"""Build a read/write property backed by ``self._params``."""
|
|
87
|
+
def getter(self):
|
|
88
|
+
return self._params[name]
|
|
89
|
+
|
|
90
|
+
def setter(self, value):
|
|
91
|
+
self._params[name] = value
|
|
92
|
+
|
|
93
|
+
return property(getter, setter)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ------------------------------------------------------------------ 比例尺
|
|
97
|
+
class ScaleBar(_VectorArtist):
|
|
98
|
+
"""Segmented scale bar with alternating black and white blocks.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
length : float or "auto"
|
|
103
|
+
Bar length in kilometres; ``"auto"`` takes 18 % of the map width and snaps
|
|
104
|
+
it to a 1/2/5 x 10^n value.
|
|
105
|
+
crs : CRS-like, optional
|
|
106
|
+
Projection of the axes; falls back to ``ax.projection`` (cartopy).
|
|
107
|
+
loc : (float, float)
|
|
108
|
+
Lower-left corner of the bar in axes fraction.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
length = _prop("length")
|
|
112
|
+
loc = _prop("loc")
|
|
113
|
+
divisions = _prop("divisions")
|
|
114
|
+
height_frac = _prop("height_frac")
|
|
115
|
+
colors = _prop("colors")
|
|
116
|
+
fontsize = _prop("fontsize")
|
|
117
|
+
unit_label = _prop("unit_label")
|
|
118
|
+
show_mid = _prop("show_mid")
|
|
119
|
+
crs = _prop("crs")
|
|
120
|
+
|
|
121
|
+
def __init__(self, length="auto", crs=None, loc=(0.05, 0.06),
|
|
122
|
+
height_frac=0.010, divisions=4, colors=("black", "white"),
|
|
123
|
+
lw=0.5, fontsize=7, unit_label="km", show_mid=False,
|
|
124
|
+
ref_lon=None, ref_lat=None, zorder=30):
|
|
125
|
+
super().__init__(zorder)
|
|
126
|
+
self._params = dict(
|
|
127
|
+
length=length, crs=crs, loc=loc, height_frac=height_frac,
|
|
128
|
+
divisions=divisions, colors=tuple(colors), lw=lw,
|
|
129
|
+
fontsize=fontsize, unit_label=unit_label, show_mid=show_mid,
|
|
130
|
+
ref_lon=ref_lon, ref_lat=ref_lat, zorder=zorder,
|
|
131
|
+
)
|
|
132
|
+
self.resolved_length = None
|
|
133
|
+
|
|
134
|
+
def _build(self, renderer):
|
|
135
|
+
ax = self.axes
|
|
136
|
+
p = self._params
|
|
137
|
+
crs = p["crs"] or getattr(ax, "projection", None)
|
|
138
|
+
if crs is None:
|
|
139
|
+
raise ValueError("ScaleBar needs crs= (a projected CRS)")
|
|
140
|
+
crs = as_pyproj(crs)
|
|
141
|
+
|
|
142
|
+
length = p["length"]
|
|
143
|
+
if length == "auto":
|
|
144
|
+
length = nice_length(0.18 * map_width_km(ax, crs))
|
|
145
|
+
self.resolved_length = float(length)
|
|
146
|
+
|
|
147
|
+
x0, x1 = ax.get_xlim()
|
|
148
|
+
y0, y1 = ax.get_ylim()
|
|
149
|
+
span_x, span_y = x1 - x0, y1 - y0
|
|
150
|
+
fwd, inv = transformers(crs)
|
|
151
|
+
|
|
152
|
+
loc = p["loc"]
|
|
153
|
+
ref_lon, ref_lat = p["ref_lon"], p["ref_lat"]
|
|
154
|
+
if ref_lon is None or ref_lat is None:
|
|
155
|
+
ref_lon, ref_lat = inv.transform(x0 + loc[0] * span_x,
|
|
156
|
+
y0 + loc[1] * span_y)
|
|
157
|
+
|
|
158
|
+
# 参考纬度处正东 1 km 的测地线,投影后取水平分量
|
|
159
|
+
lon2, lat2, _ = GEOD.fwd(ref_lon, ref_lat, 90.0, self.resolved_length * 1000.0)
|
|
160
|
+
xa, _ = fwd.transform(ref_lon, ref_lat)
|
|
161
|
+
xb, _ = fwd.transform(lon2, lat2)
|
|
162
|
+
width_frac = abs(xb - xa) / span_x
|
|
163
|
+
|
|
164
|
+
_, fy_pt = frac_per_pt(ax)
|
|
165
|
+
seg = width_frac / p["divisions"]
|
|
166
|
+
h = p["height_frac"]
|
|
167
|
+
z = self.get_zorder()
|
|
168
|
+
|
|
169
|
+
for i in range(p["divisions"]):
|
|
170
|
+
self._kids.append(Rectangle(
|
|
171
|
+
(loc[0] + i * seg, loc[1]), seg, h,
|
|
172
|
+
transform=ax.transAxes,
|
|
173
|
+
facecolor=p["colors"][i % 2], edgecolor="black",
|
|
174
|
+
linewidth=p["lw"], zorder=z))
|
|
175
|
+
self._kids.append(Rectangle(
|
|
176
|
+
(loc[0], loc[1]), width_frac, h, transform=ax.transAxes,
|
|
177
|
+
facecolor="none", edgecolor="black", linewidth=p["lw"], zorder=z + 1))
|
|
178
|
+
|
|
179
|
+
from matplotlib.lines import Line2D
|
|
180
|
+
for i in (0, p["divisions"]):
|
|
181
|
+
xx = loc[0] + i * seg
|
|
182
|
+
self._kids.append(Line2D(
|
|
183
|
+
[xx, xx], [loc[1], loc[1] - 2.5 * fy_pt],
|
|
184
|
+
transform=ax.transAxes, color="black", linewidth=p["lw"],
|
|
185
|
+
zorder=z + 1, solid_capstyle="butt"))
|
|
186
|
+
|
|
187
|
+
marks = [(0, "0"), (p["divisions"], f"{self.resolved_length:g}")]
|
|
188
|
+
if p["show_mid"] and p["divisions"] % 2 == 0:
|
|
189
|
+
marks.insert(1, (p["divisions"] // 2,
|
|
190
|
+
f"{self.resolved_length / 2:g}"))
|
|
191
|
+
if p["unit_label"]:
|
|
192
|
+
i, txt = marks[-1]
|
|
193
|
+
marks[-1] = (i, f"{txt} {p['unit_label']}")
|
|
194
|
+
for i, txt in marks:
|
|
195
|
+
self._kids.append(Text(
|
|
196
|
+
loc[0] + i * seg, loc[1] - 3.5 * fy_pt, txt,
|
|
197
|
+
transform=ax.transAxes, ha="center" if i else "left",
|
|
198
|
+
va="top", fontsize=p["fontsize"], zorder=z + 1))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ------------------------------------------------------------------ 指北针
|
|
202
|
+
class NorthArrow(_VectorArtist):
|
|
203
|
+
"""True-north arrow.
|
|
204
|
+
|
|
205
|
+
The direction comes from the projection's meridian convergence, so the arrow
|
|
206
|
+
leans correctly near the edges of a conic map. ``loc`` accepts a position alias
|
|
207
|
+
("upper right", "lower left", ...) or an ``(fx, fy)`` tuple in axes fraction.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
loc = _prop("loc")
|
|
211
|
+
length_pts = _prop("length_pts")
|
|
212
|
+
label = _prop("label")
|
|
213
|
+
crs = _prop("crs")
|
|
214
|
+
|
|
215
|
+
def __init__(self, crs=None, loc="upper right", length_pts=14, lw=0.6,
|
|
216
|
+
fontsize=8, label="N", weight="normal", lon=None, lat=None,
|
|
217
|
+
zorder=30):
|
|
218
|
+
super().__init__(zorder)
|
|
219
|
+
self._params = dict(
|
|
220
|
+
crs=crs, loc=loc, length_pts=length_pts, lw=lw,
|
|
221
|
+
fontsize=fontsize, label=label, weight=weight,
|
|
222
|
+
lon=lon, lat=lat, zorder=zorder,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
def _build(self, renderer):
|
|
226
|
+
ax = self.axes
|
|
227
|
+
p = self._params
|
|
228
|
+
crs = p["crs"] or getattr(ax, "projection", None)
|
|
229
|
+
if crs is None:
|
|
230
|
+
raise ValueError("NorthArrow needs crs= (a projected CRS)")
|
|
231
|
+
crs = as_pyproj(crs)
|
|
232
|
+
|
|
233
|
+
loc = p["loc"]
|
|
234
|
+
fx, fy = NORTH_LOCS[loc] if isinstance(loc, str) else loc
|
|
235
|
+
|
|
236
|
+
x0, x1 = ax.get_xlim()
|
|
237
|
+
y0, y1 = ax.get_ylim()
|
|
238
|
+
fwd, inv = transformers(crs)
|
|
239
|
+
|
|
240
|
+
ax_x = x0 + fx * (x1 - x0)
|
|
241
|
+
ax_y = y0 + fy * (y1 - y0)
|
|
242
|
+
lon, lat = p["lon"], p["lat"]
|
|
243
|
+
if lon is None or lat is None:
|
|
244
|
+
lon, lat = inv.transform(ax_x, ax_y)
|
|
245
|
+
|
|
246
|
+
lon2, lat2, _ = GEOD.fwd(lon, lat, 0.0, 1000.0)
|
|
247
|
+
xa, ya = fwd.transform(lon, lat)
|
|
248
|
+
xb, yb = fwd.transform(lon2, lat2)
|
|
249
|
+
theta = math.atan2(xb - xa, yb - ya)
|
|
250
|
+
|
|
251
|
+
L = p["length_pts"] * data_per_pt(ax)
|
|
252
|
+
dx, dy = L * math.sin(theta), L * math.cos(theta)
|
|
253
|
+
z = self.get_zorder()
|
|
254
|
+
|
|
255
|
+
self._kids.append(FancyArrow(
|
|
256
|
+
ax_x, ax_y, dx, dy,
|
|
257
|
+
width=0.09 * L, head_width=0.40 * L, head_length=0.36 * L,
|
|
258
|
+
length_includes_head=True, facecolor="black", edgecolor="black",
|
|
259
|
+
linewidth=p["lw"], transform=ax.transData, zorder=z))
|
|
260
|
+
self._kids.append(Text(
|
|
261
|
+
ax_x + dx * 1.22, ax_y + dy * 1.22, p["label"],
|
|
262
|
+
transform=ax.transData, ha="center", va="center",
|
|
263
|
+
fontsize=p["fontsize"], fontweight=p["weight"], zorder=z + 1))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ------------------------------------------------------------------ 经纬网
|
|
267
|
+
class Graticule(_VectorArtist):
|
|
268
|
+
"""Latitude/longitude graticule drawn as a single LineCollection.
|
|
269
|
+
|
|
270
|
+
``extent = (lon0, lon1, lat0, lat1)`` selects which meridians and parallels are
|
|
271
|
+
drawn; the lines are sampled in lon/lat and reprojected into the map CRS.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
step = _prop("step")
|
|
275
|
+
color = _prop("color")
|
|
276
|
+
extent = _prop("extent")
|
|
277
|
+
|
|
278
|
+
def __init__(self, crs=None, extent=None, step=5.0, color="0.55",
|
|
279
|
+
lw=0.35, ls=":", npts=120, zorder=1):
|
|
280
|
+
super().__init__(zorder)
|
|
281
|
+
self._params = dict(
|
|
282
|
+
crs=crs, extent=extent, step=step, color=color, lw=lw, ls=ls,
|
|
283
|
+
npts=npts, zorder=zorder,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def _build(self, renderer):
|
|
287
|
+
ax = self.axes
|
|
288
|
+
p = self._params
|
|
289
|
+
crs = p["crs"] or getattr(ax, "projection", None)
|
|
290
|
+
if crs is None:
|
|
291
|
+
raise ValueError("Graticule needs crs= (a projected CRS)")
|
|
292
|
+
if p["extent"] is None:
|
|
293
|
+
raise ValueError("Graticule 需要 extent=(lon0, lon1, lat0, lat1)")
|
|
294
|
+
fwd, _ = transformers(crs)
|
|
295
|
+
|
|
296
|
+
lon_min, lon_max, lat_min, lat_max = p["extent"]
|
|
297
|
+
step, npts = p["step"], p["npts"]
|
|
298
|
+
segs = []
|
|
299
|
+
for lon in np.arange(np.ceil(lon_min / step) * step,
|
|
300
|
+
lon_max + 1e-6, step):
|
|
301
|
+
la = np.linspace(lat_min, lat_max, npts)
|
|
302
|
+
x, y = fwd.transform(np.full_like(la, lon), la)
|
|
303
|
+
segs.append(np.column_stack([x, y]))
|
|
304
|
+
for lat in np.arange(np.ceil(lat_min / step) * step,
|
|
305
|
+
lat_max + 1e-6, step):
|
|
306
|
+
lo = np.linspace(lon_min, lon_max, npts)
|
|
307
|
+
x, y = fwd.transform(lo, np.full_like(lo, lat))
|
|
308
|
+
segs.append(np.column_stack([x, y]))
|
|
309
|
+
|
|
310
|
+
self._kids.append(LineCollection(
|
|
311
|
+
segs, colors=p["color"], linewidths=p["lw"],
|
|
312
|
+
linestyles=p["ls"], transform=ax.transData,
|
|
313
|
+
zorder=self.get_zorder()))
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ------------------------------------------------------------------ 函数封装
|
|
317
|
+
def scale_bar(ax, **kwargs):
|
|
318
|
+
"""Create a scale bar, add it to ``ax`` and return the artist."""
|
|
319
|
+
artist = ScaleBar(**kwargs)
|
|
320
|
+
ax.add_artist(artist)
|
|
321
|
+
return artist
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def north_arrow(ax, **kwargs):
|
|
325
|
+
"""Create a north arrow, add it to ``ax`` and return the artist."""
|
|
326
|
+
artist = NorthArrow(**kwargs)
|
|
327
|
+
ax.add_artist(artist)
|
|
328
|
+
return artist
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def graticule(ax, **kwargs):
|
|
332
|
+
"""Create a graticule, add it to ``ax`` and return the artist."""
|
|
333
|
+
artist = Graticule(**kwargs)
|
|
334
|
+
ax.add_artist(artist)
|
|
335
|
+
return artist
|
mapelements/export.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Export helpers: save() writes the artwork, check_vector() audits it."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import zlib
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class NotVectorError(RuntimeError):
|
|
12
|
+
"""Raised when the exported artwork is not editable vector graphics."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _pdf_streams(raw: bytes):
|
|
16
|
+
for m in re.finditer(rb"stream\r?\n", raw):
|
|
17
|
+
start = m.end()
|
|
18
|
+
end = raw.find(b"endstream", start)
|
|
19
|
+
if end == -1:
|
|
20
|
+
continue
|
|
21
|
+
try:
|
|
22
|
+
yield zlib.decompress(raw[start:end])
|
|
23
|
+
except zlib.error:
|
|
24
|
+
continue
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_vector(path, expect_text=None, allow_images=False) -> bool:
|
|
28
|
+
"""
|
|
29
|
+
Inspect a PDF/SVG for editable vector content and print a report.
|
|
30
|
+
|
|
31
|
+
PDF passes when there is no Type 3 font, at least one Tj/TJ operator and
|
|
32
|
+
no image XObject (unless ``allow_images``).
|
|
33
|
+
SVG passes when it contains <text> and no <image>.
|
|
34
|
+
"""
|
|
35
|
+
path = Path(path)
|
|
36
|
+
raw = path.read_bytes()
|
|
37
|
+
ok = True
|
|
38
|
+
print(f"\n=== {path.name} ===")
|
|
39
|
+
|
|
40
|
+
if path.suffix.lower() == ".pdf":
|
|
41
|
+
fonts = [f.decode() for f in re.findall(
|
|
42
|
+
rb"/Subtype\s*/(Type3|TrueType|Type1|Type0|CIDFontType0|"
|
|
43
|
+
rb"CIDFontType2|OpenType|MMType1)", raw)]
|
|
44
|
+
cnt = Counter(fonts)
|
|
45
|
+
print("font subtypes:", dict(cnt) or "none")
|
|
46
|
+
if cnt.get("Type3"):
|
|
47
|
+
ok = False
|
|
48
|
+
print(" x Type 3 font: glyphs are outlines, text is not editable"
|
|
49
|
+
" (set pdf.fonttype=42)")
|
|
50
|
+
|
|
51
|
+
text_ops, samples = 0, []
|
|
52
|
+
for s in _pdf_streams(raw):
|
|
53
|
+
text_ops += s.count(b"Tj") + s.count(b"TJ")
|
|
54
|
+
for m in re.finditer(rb"\(([^()\\]{1,80})\)\s*Tj", s):
|
|
55
|
+
samples.append(m.group(1).decode("latin-1", "ignore"))
|
|
56
|
+
print("text operators Tj/TJ:", text_ops)
|
|
57
|
+
if text_ops == 0:
|
|
58
|
+
ok = False
|
|
59
|
+
print(" x no text operators: the page is a bitmap or fully outlined")
|
|
60
|
+
|
|
61
|
+
n_img = len(re.findall(rb"/Subtype\s*/Image", raw))
|
|
62
|
+
print("image XObjects:", n_img)
|
|
63
|
+
if n_img and not allow_images:
|
|
64
|
+
ok = False
|
|
65
|
+
print(" x image object found (pass allow_images=True for imagery basemaps)")
|
|
66
|
+
|
|
67
|
+
if expect_text:
|
|
68
|
+
joined = "".join(samples)
|
|
69
|
+
missing = [t for t in expect_text if t not in joined]
|
|
70
|
+
if missing:
|
|
71
|
+
print(" ! not found in literal strings:", missing,
|
|
72
|
+
"(CJK text is CID-encoded and cannot be matched literally; "
|
|
73
|
+
"double-click the text in Illustrator to verify)")
|
|
74
|
+
|
|
75
|
+
elif path.suffix.lower() == ".svg":
|
|
76
|
+
svg = raw.decode("utf-8", "ignore")
|
|
77
|
+
n_text = len(re.findall(r"<text[\s>]", svg))
|
|
78
|
+
n_path = len(re.findall(r"<path[\s>]", svg))
|
|
79
|
+
n_img = len(re.findall(r"<image[\s>]", svg))
|
|
80
|
+
print(f"<text>: {n_text} <path>: {n_path} <image>: {n_img}")
|
|
81
|
+
if n_text == 0:
|
|
82
|
+
ok = False
|
|
83
|
+
print(" x no <text>: text was converted to paths (set svg.fonttype='none')")
|
|
84
|
+
if n_img and not allow_images:
|
|
85
|
+
ok = False
|
|
86
|
+
print(" x contains a raster <image>")
|
|
87
|
+
else:
|
|
88
|
+
print(" not a PDF/SVG file, check manually")
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
print("result:", "PASS" if ok else "FAIL")
|
|
92
|
+
return ok
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def save(fig, stem, outdir="figs", formats=("pdf", "svg", "png"),
|
|
96
|
+
dpi=600, allow_images=False, expect_text=None, strict=True):
|
|
97
|
+
"""Write the figure and audit the result.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
fig : matplotlib.figure.Figure
|
|
102
|
+
stem : str
|
|
103
|
+
File name without extension; use the figure number.
|
|
104
|
+
outdir : str or pathlib.Path
|
|
105
|
+
Output directory, created if missing.
|
|
106
|
+
formats : tuple of str
|
|
107
|
+
Formats to write; defaults to ``("pdf", "svg", "png")``.
|
|
108
|
+
dpi : int
|
|
109
|
+
Resolution of the PNG preview only.
|
|
110
|
+
allow_images : bool
|
|
111
|
+
Permit raster objects, e.g. an imagery basemap.
|
|
112
|
+
expect_text : list of str, optional
|
|
113
|
+
Substrings that should appear in the PDF (ASCII only).
|
|
114
|
+
strict : bool
|
|
115
|
+
Raise :class:`NotVectorError` when the audit fails (default ``True``).
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
-------
|
|
119
|
+
dict
|
|
120
|
+
Mapping ``{format: pathlib.Path}``.
|
|
121
|
+
"""
|
|
122
|
+
outdir = Path(outdir)
|
|
123
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
124
|
+
|
|
125
|
+
pdf_meta = {"Creator": "mapelements", "Producer": "matplotlib",
|
|
126
|
+
"CreationDate": None, "ModDate": None}
|
|
127
|
+
|
|
128
|
+
paths = {}
|
|
129
|
+
for fmt in formats:
|
|
130
|
+
fmt = fmt.lower().lstrip(".")
|
|
131
|
+
p = outdir / f"{stem}.{fmt}"
|
|
132
|
+
kw = {}
|
|
133
|
+
if fmt == "pdf":
|
|
134
|
+
kw["metadata"] = pdf_meta
|
|
135
|
+
elif fmt == "svg":
|
|
136
|
+
kw["metadata"] = {"Creator": "mapelements", "Date": None}
|
|
137
|
+
elif fmt == "png":
|
|
138
|
+
kw["dpi"] = dpi
|
|
139
|
+
fig.savefig(p, format=fmt, **kw)
|
|
140
|
+
paths[fmt] = p
|
|
141
|
+
print(f"[saved] {p} ({p.stat().st_size / 1024:.1f} KB)")
|
|
142
|
+
|
|
143
|
+
if "pdf" in paths:
|
|
144
|
+
ok = check_vector(paths["pdf"], expect_text=expect_text,
|
|
145
|
+
allow_images=allow_images)
|
|
146
|
+
if not ok and strict:
|
|
147
|
+
raise NotVectorError(
|
|
148
|
+
f"{paths['pdf']} failed the vector check; fix the figure or "
|
|
149
|
+
f"pass strict=False to only warn.")
|
|
150
|
+
if "svg" in paths:
|
|
151
|
+
check_vector(paths["svg"], allow_images=allow_images)
|
|
152
|
+
|
|
153
|
+
return paths
|
mapelements/geom.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Projection and geodesy helpers. No drawing code lives here."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from pyproj import Geod, Transformer
|
|
9
|
+
|
|
10
|
+
GEOD = Geod(ellps="WGS84")
|
|
11
|
+
|
|
12
|
+
# 中国常用 Albers:标准纬线 25°N / 47°N,中央经线 105°E
|
|
13
|
+
CN_ALBERS = ("+proj=aea +lat_1=25 +lat_2=47 +lat_0=0 "
|
|
14
|
+
"+lon_0=105 +datum=WGS84 +units=m +no_defs")
|
|
15
|
+
|
|
16
|
+
# 指北针位置别名 -> axes fraction
|
|
17
|
+
NORTH_LOCS = {
|
|
18
|
+
"upper right": (0.93, 0.86),
|
|
19
|
+
"upper left": (0.07, 0.86),
|
|
20
|
+
"lower right": (0.93, 0.10),
|
|
21
|
+
"lower left": (0.07, 0.10),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def as_pyproj(crs):
|
|
26
|
+
"""Accept a PROJ string, a pyproj CRS or a cartopy CRS."""
|
|
27
|
+
return crs.proj4_init if hasattr(crs, "proj4_init") else crs
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def transformers(crs):
|
|
31
|
+
crs = as_pyproj(crs)
|
|
32
|
+
fwd = Transformer.from_crs("EPSG:4326", crs, always_xy=True)
|
|
33
|
+
inv = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)
|
|
34
|
+
return fwd, inv
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def axes_size_inch(ax):
|
|
38
|
+
fig = ax.figure
|
|
39
|
+
pos = ax.get_position()
|
|
40
|
+
return (fig.get_size_inches()[0] * pos.width,
|
|
41
|
+
fig.get_size_inches()[1] * pos.height)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def frac_per_pt(ax):
|
|
45
|
+
"""Axes fraction occupied by one point (x and y separately)."""
|
|
46
|
+
w, h = axes_size_inch(ax)
|
|
47
|
+
return 1.0 / (w * 72.0), 1.0 / (h * 72.0)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def data_per_pt(ax):
|
|
51
|
+
"""Data units per point; requires ``set_aspect('equal')``."""
|
|
52
|
+
x0, x1 = ax.get_xlim()
|
|
53
|
+
w, _ = axes_size_inch(ax)
|
|
54
|
+
return (x1 - x0) / (w * 72.0)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def nice_length(km):
|
|
58
|
+
"""Round up to the next 1/2/5 x 10^n value (473 -> 500)."""
|
|
59
|
+
if km <= 0:
|
|
60
|
+
return 1.0
|
|
61
|
+
exp = math.floor(math.log10(km))
|
|
62
|
+
base = km / 10 ** exp
|
|
63
|
+
for cand in (1, 2, 5, 10):
|
|
64
|
+
if base <= cand + 1e-9:
|
|
65
|
+
v = cand * 10 ** exp
|
|
66
|
+
return int(v) if v >= 1 else round(v, 6)
|
|
67
|
+
return km
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def map_width_km(ax, crs):
|
|
71
|
+
"""Geodesic width of the current axis at its central latitude, in km."""
|
|
72
|
+
_, inv = transformers(crs)
|
|
73
|
+
x0, x1 = ax.get_xlim()
|
|
74
|
+
y0, y1 = ax.get_ylim()
|
|
75
|
+
lon_a, lat_a = inv.transform(x0, (y0 + y1) / 2)
|
|
76
|
+
lon_b, lat_b = inv.transform(x1, (y0 + y1) / 2)
|
|
77
|
+
_, _, d = GEOD.inv(lon_a, lat_a, lon_b, lat_b)
|
|
78
|
+
return d / 1000.0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def project_extent(crs, extent, n=12):
|
|
82
|
+
"""Geographic extent -> projected bounds, sampled on an n x n grid."""
|
|
83
|
+
fwd, _ = transformers(crs)
|
|
84
|
+
lon0, lon1, lat0, lat1 = extent
|
|
85
|
+
lo, la = np.meshgrid(np.linspace(lon0, lon1, n), np.linspace(lat0, lat1, n))
|
|
86
|
+
x, y = fwd.transform(lo.ravel(), la.ravel())
|
|
87
|
+
return float(np.min(x)), float(np.max(x)), float(np.min(y)), float(np.max(y))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def extent_from_axes(ax, crs):
|
|
91
|
+
"""Approximate geographic extent of the current projected limits."""
|
|
92
|
+
_, inv = transformers(crs)
|
|
93
|
+
x0, x1 = ax.get_xlim()
|
|
94
|
+
y0, y1 = ax.get_ylim()
|
|
95
|
+
lons, lats = [], []
|
|
96
|
+
for x in (x0, x1):
|
|
97
|
+
for y in (y0, y1):
|
|
98
|
+
lon, lat = inv.transform(x, y)
|
|
99
|
+
lons.append(lon)
|
|
100
|
+
lats.append(lat)
|
|
101
|
+
return (min(lons), max(lons), min(lats), max(lats))
|
mapelements/py.typed
ADDED
|
File without changes
|
mapelements/style.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Journal defaults and millimetre-based figure sizing."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import matplotlib as mpl
|
|
6
|
+
|
|
7
|
+
MM = 1 / 25.4
|
|
8
|
+
|
|
9
|
+
SINGLE_COLUMN = 85.0 # mm,单栏
|
|
10
|
+
DOUBLE_COLUMN = 170.0 # mm,双栏
|
|
11
|
+
|
|
12
|
+
RC = {
|
|
13
|
+
# 文字保持为文字,而不是 Type3 轮廓 / <path>
|
|
14
|
+
"pdf.fonttype": 42,
|
|
15
|
+
"ps.fonttype": 42,
|
|
16
|
+
"svg.fonttype": "none",
|
|
17
|
+
# 字体
|
|
18
|
+
"font.family": "sans-serif",
|
|
19
|
+
"font.sans-serif": ["Arial", "Helvetica", "Times New Roman",
|
|
20
|
+
"Microsoft YaHei", "SimHei",
|
|
21
|
+
"Noto Sans CJK SC", "DejaVu Sans"],
|
|
22
|
+
"mathtext.fontset": "dejavusans",
|
|
23
|
+
"mathtext.default": "regular",
|
|
24
|
+
"axes.unicode_minus": False,
|
|
25
|
+
# 印刷字号 / 线宽(pt)
|
|
26
|
+
"font.size": 8,
|
|
27
|
+
"axes.labelsize": 8,
|
|
28
|
+
"axes.titlesize": 9,
|
|
29
|
+
"xtick.labelsize": 7,
|
|
30
|
+
"ytick.labelsize": 7,
|
|
31
|
+
"legend.fontsize": 7,
|
|
32
|
+
"legend.frameon": False,
|
|
33
|
+
"axes.linewidth": 0.8,
|
|
34
|
+
"xtick.major.width": 0.8,
|
|
35
|
+
"ytick.major.width": 0.8,
|
|
36
|
+
"xtick.major.size": 3,
|
|
37
|
+
"ytick.major.size": 3,
|
|
38
|
+
"lines.linewidth": 1.0,
|
|
39
|
+
"patch.linewidth": 0.5,
|
|
40
|
+
# 尺寸控制:禁止 tight 自动裁切
|
|
41
|
+
"savefig.bbox": "standard",
|
|
42
|
+
"savefig.pad_inches": 0.02,
|
|
43
|
+
"savefig.facecolor": "white",
|
|
44
|
+
"savefig.transparent": False,
|
|
45
|
+
"figure.facecolor": "white",
|
|
46
|
+
"figure.dpi": 150,
|
|
47
|
+
"savefig.dpi": 600,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def pub_style(extra: dict | None = None) -> None:
|
|
52
|
+
"""Apply the journal defaults; call once before creating figures."""
|
|
53
|
+
rc = dict(RC)
|
|
54
|
+
if extra:
|
|
55
|
+
rc.update(extra)
|
|
56
|
+
mpl.rcParams.update(rc)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def figure(width: float | str = DOUBLE_COLUMN, height: float = 90,
|
|
60
|
+
**kwargs):
|
|
61
|
+
"""Create ``(fig, ax)`` with a millimetre size.
|
|
62
|
+
|
|
63
|
+
``width`` accepts ``"single"`` (85 mm), ``"double"`` (170 mm) or a number of
|
|
64
|
+
millimetres; ``height`` is always in millimetres.
|
|
65
|
+
"""
|
|
66
|
+
import matplotlib.pyplot as plt
|
|
67
|
+
|
|
68
|
+
if isinstance(width, str):
|
|
69
|
+
width = {"single": SINGLE_COLUMN, "double": DOUBLE_COLUMN}[width.lower()]
|
|
70
|
+
fig, ax = plt.subplots(figsize=(width * MM, height * MM), **kwargs)
|
|
71
|
+
return fig, ax
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mapelements
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Journal-quality vector map elements for matplotlib: scale bars, north arrows and graticules that stay editable in PDF/SVG.
|
|
5
|
+
Author: zhangbo
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zhangbo/mapelements
|
|
8
|
+
Project-URL: Repository, https://github.com/zhangbo/mapelements
|
|
9
|
+
Project-URL: Issues, https://github.com/zhangbo/mapelements/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/zhangbo/mapelements/tree/main/docs
|
|
11
|
+
Project-URL: Changelog, https://github.com/zhangbo/mapelements/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: matplotlib,cartopy,geopandas,cartography,scale-bar,north-arrow,graticule,vector-graphics,publication
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.9
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Requires-Dist: matplotlib>=3.6
|
|
31
|
+
Requires-Dist: numpy>=1.22
|
|
32
|
+
Requires-Dist: pyproj>=3.4
|
|
33
|
+
Provides-Extra: geo
|
|
34
|
+
Requires-Dist: geopandas>=0.13; extra == "geo"
|
|
35
|
+
Provides-Extra: cartopy
|
|
36
|
+
Requires-Dist: cartopy>=0.22; extra == "cartopy"
|
|
37
|
+
Provides-Extra: test
|
|
38
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
39
|
+
Provides-Extra: dev
|
|
40
|
+
Requires-Dist: geopandas>=0.13; extra == "dev"
|
|
41
|
+
Requires-Dist: cartopy>=0.22; extra == "dev"
|
|
42
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
43
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
44
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
45
|
+
Provides-Extra: docs
|
|
46
|
+
Requires-Dist: mkdocs>=1.5; extra == "docs"
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# mapelements
|
|
50
|
+
|
|
51
|
+
[](https://pypi.org/project/mapelements/)
|
|
52
|
+
[](https://pypi.org/project/mapelements/)
|
|
53
|
+
[](LICENSE)
|
|
54
|
+
[](https://github.com/zhangbo/mapelements/actions/workflows/ci.yml)
|
|
55
|
+
|
|
56
|
+
**矢量**地图要素,专为期刊插图:比例尺、指北针、经纬网。
|
|
57
|
+
|
|
58
|
+
全部用 matplotlib 的 `Patch` / `Line2D` / `Text` 绘制,不产生任何位图。
|
|
59
|
+
导出 PDF/SVG 后线条仍是路径、文字仍是文字,在 Illustrator 里可以直接改。
|
|
60
|
+
配合 `pdf.fonttype = 42`(`pub_style()` 会自动设置),满足"图中文字可修改"
|
|
61
|
+
的投稿要求。
|
|
62
|
+
|
|
63
|
+
## 文档
|
|
64
|
+
|
|
65
|
+
| 语言 | 内容 |
|
|
66
|
+
|---|---|
|
|
67
|
+
| [English](docs/en/index.md) | installation, quickstart, elements, projections, layout, export, API, cookbook, FAQ |
|
|
68
|
+
| [中文](docs/zh/index.md) | 安装、快速开始、地图要素、投影、版式、投稿导出、API、实用配方、常见问题 |
|
|
69
|
+
|
|
70
|
+
本地预览:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install -e ".[docs]"
|
|
74
|
+
mkdocs serve -f mkdocs.en.yml # http://127.0.0.1:8000
|
|
75
|
+
mkdocs serve -f mkdocs.zh.yml
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
在线站点(推送 `main` 后由 `.github/workflows/docs.yml` 自动发布):
|
|
79
|
+
<https://zhangbo.github.io/mapelements/>
|
|
80
|
+
|
|
81
|
+
文档自检(链接、锚点、图片、代码块语法):
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
python check_docs.py
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
文档里的插图由 [`docs/make_figures.py`](docs/make_figures.py) 生成:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
python docs/make_figures.py
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## 安装
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pip install mapelements
|
|
97
|
+
|
|
98
|
+
# 需要 geopandas / cartopy 时
|
|
99
|
+
pip install "mapelements[geo,cartopy]"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## 快速开始
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import matplotlib.pyplot as plt
|
|
106
|
+
import mapelements
|
|
107
|
+
|
|
108
|
+
mapelements.pub_style() # 刊物版式:Type42、7-8 pt
|
|
109
|
+
fig, ax = mapelements.figure("double", 110) # 170 mm 宽
|
|
110
|
+
|
|
111
|
+
gdf.to_crs(mapelements.CN_ALBERS).plot(ax=ax, column="value", cmap="YlGnBu")
|
|
112
|
+
|
|
113
|
+
mapelements.finish(ax, crs=mapelements.CN_ALBERS, data=gdf)
|
|
114
|
+
mapelements.save(fig, "Fig1") # figs/Fig1.pdf + .svg + .png
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## 三种用法
|
|
118
|
+
|
|
119
|
+
**Artist 方式**(和 matplotlib 原生写法一致,可 `remove()`、可 `copy()`)
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from mapelements import ScaleBar, NorthArrow, Graticule
|
|
123
|
+
|
|
124
|
+
ax.add_artist(Graticule(crs=CRS, extent=(94, 121, 26, 43), step=5))
|
|
125
|
+
ax.add_artist(ScaleBar(length=500, crs=CRS, loc=(0.05, 0.06)))
|
|
126
|
+
ax.add_artist(NorthArrow(crs=CRS, loc="upper right"))
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**函数方式**
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
mapelements.scale_bar(ax, length=500, crs=CRS)
|
|
133
|
+
mapelements.north_arrow(ax, crs=CRS)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
**一站式**
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
mapelements.finish(ax, crs=CRS, data=gdf, scalebar="auto", north="upper right")
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## 多子图复用
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
sb = ScaleBar(length=500, crs=CRS)
|
|
146
|
+
nw = NorthArrow(crs=CRS)
|
|
147
|
+
for ax in axs.flat:
|
|
148
|
+
ax.add_artist(sb.copy()) # 每个 Axes 需要一份副本
|
|
149
|
+
ax.add_artist(nw.copy())
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## 为什么不用现成的包
|
|
153
|
+
|
|
154
|
+
| | `matplotlib_scalebar` | `matplotlib_map_utils` | **mapelements** |
|
|
155
|
+
|---|---|---|---|
|
|
156
|
+
| 矢量 | 是 | **否**(整条渲染成位图) | 是 |
|
|
157
|
+
| 文字可编辑 | 是 | 否 | 是 |
|
|
158
|
+
| 黑白分段 | 否 | 是 | 是 |
|
|
159
|
+
| 指北针 / 经纬网 | 否 | 是 / 否 | 是 |
|
|
160
|
+
| 依赖 | 额外一个包 | 额外一个包 + 临时 figure 渲染 | 只要 matplotlib + pyproj |
|
|
161
|
+
|
|
162
|
+
## API
|
|
163
|
+
|
|
164
|
+
| 对象 | 说明 |
|
|
165
|
+
|---|---|
|
|
166
|
+
| `ScaleBar(length="auto", crs=None, loc=(0.05, 0.06), divisions=4, colors=("black", "white"), height_frac=0.010, fontsize=7, unit_label="km", show_mid=False, ref_lon=None, ref_lat=None)` | 黑白分段比例尺;`"auto"` 按图幅取 1/2/5×10ⁿ |
|
|
167
|
+
| `NorthArrow(crs=None, loc="upper right", length_pts=14, label="N", weight="normal")` | 真北指北针(按经线收敛定向) |
|
|
168
|
+
| `Graticule(crs=None, extent=(lon0, lon1, lat0, lat1), step=5, color="0.55", lw=0.35, ls=":")` | 经纬网 |
|
|
169
|
+
| `scale_bar(ax, **kw)` / `north_arrow(ax, **kw)` / `graticule(ax, **kw)` | 构造并添加,返回 artist |
|
|
170
|
+
| `finish(ax, crs, data=None, extent=None, graticule=5, scalebar="auto", north="upper right", fill=True, legend=False)` | 一站式收尾 |
|
|
171
|
+
| `fit(ax)` | 单幅地图铺满画布(多子图自动跳过) |
|
|
172
|
+
| `save(fig, "Fig1", outdir="figs", formats=("pdf", "svg", "png"))` | 导出并自检,不通过抛 `NotVectorError` |
|
|
173
|
+
| `check_vector(path)` | 检查已有 PDF/SVG 是否可编辑矢量 |
|
|
174
|
+
| `pub_style(extra=None)` / `figure(width, height_mm)` | 刊物版式 / 按 mm 建图 |
|
|
175
|
+
|
|
176
|
+
常量:`CN_ALBERS`(Albers 25/47,中央经线 105°E)、`MM`、`SINGLE_COLUMN`、`DOUBLE_COLUMN`。
|
|
177
|
+
|
|
178
|
+
## 设计要点
|
|
179
|
+
|
|
180
|
+
- **绘制时才计算几何**:`draw()` 中按当前 `xlim`、轴尺寸构建子图元,改了范围或
|
|
181
|
+
画布大小后自动重排,不需要重新添加;先 `add_artist` 再 `set_xlim` 也可以。
|
|
182
|
+
- **比例尺精度**:按参考纬度处正东方向的测地线长度换算,自动吸收投影尺度因子。
|
|
183
|
+
- **指北针精度**:按投影的经线收敛角旋转,锥形投影边缘不会指偏。
|
|
184
|
+
- **cartopy 兼容**:`crs=ax.projection` 即可(内部取 `proj4_init` 交给 pyproj)。
|
|
185
|
+
- **不栅格化**:没有 `OffsetImage`、没有临时 figure 渲染。
|
|
186
|
+
|
|
187
|
+
## 开发
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
git clone https://github.com/zhangbo/mapelements
|
|
191
|
+
cd mapelements
|
|
192
|
+
pip install -e ".[dev]"
|
|
193
|
+
pytest
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## 许可证
|
|
197
|
+
|
|
198
|
+
MIT,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
mapelements/__init__.py,sha256=20mBKKw8CFyr3iS1ARQCjKLEuZl-iJ7-7SEWJAaSo14,1772
|
|
2
|
+
mapelements/api.py,sha256=ZkI14JWR-bi3luEN0kOEeqIi_c9QEVNAPXVauYR9BG8,4109
|
|
3
|
+
mapelements/artists.py,sha256=1MbwZN3pdkXZlDlFxkYQaIqhkkLkEzvksmYFp_2Nee0,12498
|
|
4
|
+
mapelements/export.py,sha256=nYOx0VYQzVbI7neHHxQtUOKD4d7Y04b5r2ojQfYWD10,5510
|
|
5
|
+
mapelements/geom.py,sha256=r5U1LrQrhSNQ8Z0VlbiSJlV7gxCywOvJQiuB6aw5Gpo,3105
|
|
6
|
+
mapelements/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
mapelements/style.py,sha256=CVJhRS29ToiLhS_lFYeHM7bOGADeof3luKPNsQi0Tx8,2189
|
|
8
|
+
mapelements-0.1.0.dist-info/licenses/LICENSE,sha256=PnZImtfsW7Au5fPhEUa8316GrCIOaQTbFbVGai3VtAM,1080
|
|
9
|
+
mapelements-0.1.0.dist-info/METADATA,sha256=YIP-k84QvSifzQHdhjNZZSNpm54I8T8lsar6-E4Py5E,7673
|
|
10
|
+
mapelements-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
mapelements-0.1.0.dist-info/top_level.txt,sha256=EIJ7tAYdODxGfqIlOH1mYbKubmDcnvFTDm6-0kFAVPs,12
|
|
12
|
+
mapelements-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The mapelements authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mapelements
|