or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

coordinate-systems.mddata-io.mdgeodesic.mdgeographic-features.mdindex.mdmatplotlib-integration.mdtransformations.md

matplotlib-integration.mddocs/

0

# Matplotlib Integration

1

2

Enhanced matplotlib axes with cartographic projection support. Provides specialized plotting functions, coordinate transformations, and gridline management for geographic data visualization.

3

4

## Capabilities

5

6

### GeoAxes

7

8

Enhanced matplotlib Axes subclass with geographic projection support and cartographic plotting methods.

9

10

```python { .api }

11

class GeoAxes:

12

"""Matplotlib axes subclass for cartographic projections."""

13

def __init__(self, fig, rect, projection, **kwargs): ...

14

15

# Extent and boundaries

16

def set_global(self): ...

17

def set_extent(self, extents, crs=None): ...

18

@property

19

def extent(self): ...

20

21

# Geographic features

22

def add_feature(self, feature, **kwargs): ...

23

def coastlines(self, resolution='auto', color='black', **kwargs): ...

24

def stock_img(self): ...

25

26

# Gridlines and labels

27

def gridlines(self, crs=None, draw_labels=False, **kwargs): ...

28

29

# Coordinate transformations

30

def transform_point(self, x, y, src_crs): ...

31

def transform_points(self, src_crs, x, y, z=None): ...

32

33

# Plotting with transformations

34

def plot(self, *args, transform=None, **kwargs): ...

35

def scatter(self, x, y, transform=None, **kwargs): ...

36

def contour(self, x, y, z, transform=None, **kwargs): ...

37

def contourf(self, x, y, z, transform=None, **kwargs): ...

38

def pcolormesh(self, x, y, z, transform=None, **kwargs): ...

39

def quiver(self, x, y, u, v, transform=None, **kwargs): ...

40

def streamplot(self, x, y, u, v, transform=None, **kwargs): ...

41

def imshow(self, img, extent=None, transform=None, **kwargs): ...

42

43

# Tissot's indicatrix

44

def tissot(self, rad_km, lons, lats, n_samples=80, **kwargs): ...

45

46

# Web map tiles

47

def add_image(self, tile_source, level, **kwargs): ...

48

def add_wmts(self, wmts, layer_name, **kwargs): ...

49

def add_wms(self, wms, layers, **kwargs): ...

50

def add_raster(self, raster_source, **kwargs): ...

51

52

# Background and stock imagery

53

def background_img(self, name='ne_shaded', resolution='low', extent=None, cache=False): ...

54

def stock_img(self): ...

55

56

# View and coordinate utilities

57

def autoscale_view(self, tight=None, scalex=True, scaley=True): ...

58

def format_coord(self, x, y): ...

59

def get_tightbbox(self, renderer, call_axes_locator=True, bbox_extra_artists=None): ...

60

```

61

62

### Gridlines and Labels

63

64

Sophisticated gridline and label management for geographic maps.

65

66

```python { .api }

67

class Gridliner:

68

"""Grid line and label management for GeoAxes."""

69

def __init__(self, axes, crs, draw_labels=False, **kwargs): ...

70

71

# Style properties

72

xlabel_style: dict # X-axis label styling

73

ylabel_style: dict # Y-axis label styling

74

xlines: bool # Whether to draw longitude lines

75

ylines: bool # Whether to draw latitude lines

76

xlabels_top: bool # Top longitude labels

77

xlabels_bottom: bool # Bottom longitude labels

78

ylabels_left: bool # Left latitude labels

79

ylabels_right: bool # Right latitude labels

80

81

# Locators and formatters

82

xlocator: Any # Longitude tick locator

83

ylocator: Any # Latitude tick locator

84

xformatter: Any # Longitude label formatter

85

yformatter: Any # Latitude label formatter

86

87

class Label:

88

"""Individual grid label representation."""

89

def __init__(self, x, y, text, **kwargs): ...

90

@property

91

def x(self): ...

92

@property

93

def y(self): ...

94

@property

95

def text(self): ...

96

```

97

98

### Coordinate Formatters and Locators

99

100

Specialized tick locators and formatters for geographic coordinates.

101

102

```python { .api }

103

class LatitudeFormatter:

104

"""Format latitude tick labels with N/S indicators."""

105

def __init__(self, degree_symbol='°', number_format='g',

106

southern_hemisphere='S', northern_hemisphere='N'): ...

107

def __call__(self, value, pos=None): ...

108

109

class LongitudeFormatter:

110

"""Format longitude tick labels with E/W indicators."""

111

def __init__(self, degree_symbol='°', number_format='g',

112

eastern_hemisphere='E', western_hemisphere='W',

113

dateline_direction_label=False, zero_direction_label=False): ...

114

def __call__(self, value, pos=None): ...

115

116

class LatitudeLocator:

117

"""Locate latitude tick positions."""

118

def __init__(self, nbins='auto'): ...

119

def tick_values(self, vmin, vmax): ...

120

121

class LongitudeLocator:

122

"""Locate longitude tick positions."""

123

def __init__(self, nbins='auto'): ...

124

def tick_values(self, vmin, vmax): ...

125

```

126

127

### Path and Geometry Utilities

128

129

Convert between matplotlib paths and shapely geometries.

130

131

```python { .api }

132

def shapely_to_path(shape):

133

"""

134

Convert shapely geometry to matplotlib path.

135

136

Parameters:

137

- shape: shapely geometry

138

139

Returns:

140

matplotlib.path.Path

141

"""

142

143

def path_to_shapely(path):

144

"""

145

Convert matplotlib path to shapely geometry.

146

147

Parameters:

148

- path: matplotlib.path.Path

149

150

Returns:

151

shapely geometry

152

"""

153

154

def geos_to_path(shape):

155

"""

156

Convert GEOS geometry to matplotlib path.

157

158

Parameters:

159

- shape: GEOS geometry

160

161

Returns:

162

matplotlib.path.Path

163

"""

164

```

165

166

### Feature Artists

167

168

Specialized artists for rendering cartographic features.

169

170

```python { .api }

171

class FeatureArtist:

172

"""Artist for rendering cartopy features."""

173

def __init__(self, feature, **kwargs): ...

174

def draw(self, renderer): ...

175

176

class SlippyImageArtist:

177

"""Artist for rendering slippy map tiles."""

178

def __init__(self, tile_source, **kwargs): ...

179

def draw(self, renderer): ...

180

```

181

182

### Collections and Specialized Plots

183

184

Geographic-aware matplotlib collections and specialized plotting utilities.

185

186

```python { .api }

187

class GeoQuadMesh:

188

"""Geographic quadrilateral mesh for pcolormesh plots."""

189

def __init__(self, x, y, **kwargs): ...

190

191

class GeoContourSet:

192

"""Geographic contour set with projection awareness."""

193

def __init__(self, ax, *args, **kwargs): ...

194

```

195

196

## Usage Examples

197

198

### Basic Map Creation

199

200

```python

201

import matplotlib.pyplot as plt

202

import cartopy.crs as ccrs

203

import cartopy.feature as cfeature

204

205

# Create figure with GeoAxes

206

fig = plt.figure(figsize=(12, 8))

207

ax = plt.axes(projection=ccrs.PlateCarree())

208

209

# Set up map

210

ax.set_global()

211

ax.add_feature(cfeature.LAND)

212

ax.add_feature(cfeature.OCEAN)

213

ax.coastlines()

214

215

# Add gridlines with labels

216

gl = ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)

217

gl.xlabel_style = {'size': 12, 'color': 'blue'}

218

gl.ylabel_style = {'size': 12, 'color': 'red'}

219

220

plt.title('World Map with Custom Gridlines')

221

plt.show()

222

```

223

224

### Plotting Data with Transformations

225

226

```python

227

import numpy as np

228

import matplotlib.pyplot as plt

229

import cartopy.crs as ccrs

230

231

# Sample data

232

lons = np.linspace(-180, 180, 360)

233

lats = np.linspace(-90, 90, 180)

234

lon_grid, lat_grid = np.meshgrid(lons, lats)

235

data = np.sin(np.radians(lat_grid)) * np.cos(np.radians(lon_grid))

236

237

# Plot with different projection

238

fig = plt.figure(figsize=(15, 10))

239

240

# PlateCarree data projection

241

ax1 = plt.subplot(2, 2, 1, projection=ccrs.PlateCarree())

242

ax1.contourf(lon_grid, lat_grid, data, transform=ccrs.PlateCarree())

243

ax1.coastlines()

244

ax1.set_title('PlateCarree Projection')

245

246

# Orthographic projection

247

ax2 = plt.subplot(2, 2, 2, projection=ccrs.Orthographic(-90, 45))

248

ax2.contourf(lon_grid, lat_grid, data, transform=ccrs.PlateCarree())

249

ax2.coastlines()

250

ax2.set_global()

251

ax2.set_title('Orthographic Projection')

252

253

plt.tight_layout()

254

plt.show()

255

```

256

257

### Custom Gridline Formatting

258

259

```python

260

import matplotlib.pyplot as plt

261

import cartopy.crs as ccrs

262

from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

263

264

fig = plt.figure(figsize=(12, 8))

265

ax = plt.axes(projection=ccrs.PlateCarree())

266

267

# Add features

268

ax.coastlines()

269

ax.set_global()

270

271

# Custom gridlines with formatters

272

gl = ax.gridlines(draw_labels=True)

273

gl.xformatter = LongitudeFormatter(zero_direction_label=True)

274

gl.yformatter = LatitudeFormatter()

275

gl.xlabel_style = {'size': 10, 'rotation': 45}

276

gl.ylabel_style = {'size': 10}

277

278

plt.show()

279

```

280

281

### Vector Field Plotting

282

283

```python

284

import numpy as np

285

import matplotlib.pyplot as plt

286

import cartopy.crs as ccrs

287

288

# Create vector field data

289

lons = np.arange(-120, -60, 5)

290

lats = np.arange(25, 65, 5)

291

lon_grid, lat_grid = np.meshgrid(lons, lats)

292

293

# Sample wind field

294

u = 10 * np.sin(np.radians(lat_grid))

295

v = 5 * np.cos(np.radians(lon_grid))

296

297

fig = plt.figure(figsize=(12, 8))

298

ax = plt.axes(projection=ccrs.PlateCarree())

299

300

# Plot vector field

301

ax.quiver(lon_grid, lat_grid, u, v, transform=ccrs.PlateCarree(),

302

regrid_shape=20, alpha=0.7)

303

304

# Add map features

305

ax.coastlines()

306

ax.add_feature(cfeature.BORDERS)

307

ax.set_extent([-125, -55, 20, 70])

308

ax.gridlines(draw_labels=True)

309

310

plt.title('Wind Vector Field')

311

plt.show()

312

```

313

314

### Adding Web Map Tiles

315

316

```python

317

import matplotlib.pyplot as plt

318

import cartopy.crs as ccrs

319

from cartopy.io import img_tiles

320

321

# Create map with OpenStreetMap tiles

322

fig = plt.figure(figsize=(12, 8))

323

324

# Use the same CRS as the tile source

325

osm_tiles = img_tiles.OSM()

326

ax = plt.axes(projection=osm_tiles.crs)

327

328

# Add tiles at zoom level 10

329

ax.add_image(osm_tiles, 10)

330

331

# Set extent for London

332

ax.set_extent([-0.2, 0.1, 51.4, 51.6])

333

334

# Add some data points

335

lons = [-0.1, 0.0, 0.05]

336

lats = [51.5, 51.52, 51.48]

337

ax.scatter(lons, lats, color='red', s=100, transform=ccrs.PlateCarree())

338

339

plt.title('London with OpenStreetMap Background')

340

plt.show()

341

```

342

343

### Tissot's Indicatrix

344

345

```python

346

import matplotlib.pyplot as plt

347

import cartopy.crs as ccrs

348

349

# Show projection distortion with Tissot's indicatrix

350

fig, axes = plt.subplots(1, 2, figsize=(15, 6),

351

subplot_kw={'projection': ccrs.PlateCarree()})

352

353

projections = [ccrs.PlateCarree(), ccrs.Mercator()]

354

titles = ['PlateCarree', 'Mercator']

355

356

for ax, proj, title in zip(axes, projections, titles):

357

ax = plt.axes(projection=proj)

358

ax.coastlines()

359

ax.set_global()

360

361

# Add Tissot's indicatrix circles

362

ax.tissot(rad_km=1000, lons=range(-180, 181, 30),

363

lats=range(-90, 91, 30), alpha=0.5)

364

365

ax.set_title(f'{title} - Tissot Indicatrix')

366

367

plt.tight_layout()

368

plt.show()

369

```

370

371

## Style Utilities

372

373

```python { .api }

374

def merge(*style_dicts):

375

"""

376

Merge matplotlib style dictionaries.

377

378

Parameters:

379

- *style_dicts: variable number of style dictionaries

380

381

Returns:

382

Merged style dictionary

383

"""

384

385

def finalize(style):

386

"""

387

Finalize style dictionary for matplotlib use.

388

389

Parameters:

390

- style: dict, style parameters

391

392

Returns:

393

Finalized style dictionary

394

"""

395

```