0
# Axes and Plotting
1
2
Enhanced axes classes with extended formatting capabilities, seamless integration with multiple coordinate systems, and comprehensive plotting methods for scientific visualization. Proplot provides specialized axes for Cartesian, polar, geographic, and 3D coordinate systems with consistent formatting APIs and enhanced plotting functionality.
3
4
## Capabilities
5
6
### Base Axes Class
7
8
Foundation class extending matplotlib.axes.Axes with universal formatting capabilities and enhanced visual control.
9
10
```python { .api }
11
class Axes:
12
"""
13
Base proplot axes class with enhanced formatting capabilities.
14
15
Enhanced replacement for matplotlib.axes.Axes providing:
16
- Universal format() method for all visual properties
17
- Physical unit support throughout
18
- Enhanced spine, tick, and grid control
19
- Integrated panel and inset management
20
"""
21
22
def format(self, **kwargs):
23
"""
24
Universal formatting method for all visual properties.
25
26
Parameters:
27
- title (str): Axes title
28
- xlabel (str): X-axis label
29
- ylabel (str): Y-axis label
30
- xlim (tuple): X-axis limits
31
- ylim (tuple): Y-axis limits
32
- color (color-spec): Universal color for spines, ticks, labels
33
- grid (bool): Grid visibility toggle
34
- **kwargs: Additional formatting parameters specific to axes type
35
"""
36
37
def panel_axes(self, side, **kwargs):
38
"""
39
Create panel axes for colorbars or legends.
40
41
Parameters:
42
- side (str): Panel location ('left', 'right', 'top', 'bottom')
43
- space (unit-spec): Space between panel and axes
44
- width (unit-spec): Panel width
45
- **kwargs: Additional panel parameters
46
47
Returns:
48
proplot.axes.Axes: Created panel axes
49
"""
50
51
def inset_axes(self, **kwargs):
52
"""
53
Create inset axes within current axes.
54
55
Parameters:
56
- bounds (tuple): Inset bounds as (x, y, width, height)
57
- loc (str/int): Inset location specification
58
- **kwargs: Additional inset parameters
59
60
Returns:
61
proplot.axes.Axes: Created inset axes
62
"""
63
```
64
65
### Enhanced Plotting Methods
66
67
Mixin class providing enhanced plotting methods with automatic color cycling, legend integration, and improved styling options.
68
69
```python { .api }
70
class PlotAxes:
71
"""
72
Mixin class providing enhanced plotting methods.
73
74
Enhancements over matplotlib include:
75
- Automatic color cycling with proplot colormaps
76
- Integrated colorbar and legend management
77
- Enhanced argument processing and validation
78
- Improved styling and formatting options
79
"""
80
81
def plot(self, *args, **kwargs):
82
"""
83
Enhanced line plotting with proplot features.
84
85
Parameters:
86
- *args: x, y data arrays or y data with automatic x
87
- color (color-spec): Line color with proplot color support
88
- cycle (str/Cycle): Color cycle for multiple lines
89
- legend (bool): Add to legend automatically
90
- legend_kw (dict): Legend formatting parameters
91
- **kwargs: Additional matplotlib plot parameters
92
93
Returns:
94
list: Line2D objects
95
"""
96
97
def scatter(self, *args, **kwargs):
98
"""
99
Enhanced scatter plots with additional options.
100
101
Parameters:
102
- x, y: Data point coordinates
103
- s (scalar/array): Marker size(s)
104
- c (color-spec/array): Marker color(s) with proplot support
105
- colorbar (bool): Create colorbar automatically
106
- colorbar_kw (dict): Colorbar formatting parameters
107
- **kwargs: Additional matplotlib scatter parameters
108
109
Returns:
110
matplotlib.collections.PathCollection: Scatter plot collection
111
"""
112
113
def bar(self, *args, **kwargs):
114
"""
115
Enhanced bar charts with styling improvements.
116
117
Parameters:
118
- x: Bar positions or categories
119
- height: Bar heights
120
- color (color-spec): Bar colors with proplot support
121
- cycle (str/Cycle): Color cycle for multiple series
122
- **kwargs: Additional matplotlib bar parameters
123
124
Returns:
125
matplotlib.container.BarContainer: Bar chart container
126
"""
127
128
def contour(self, *args, **kwargs):
129
"""
130
Enhanced contour plots with improved integration.
131
132
Parameters:
133
- X, Y, Z: 2D coordinate and data arrays
134
- levels (int/array): Contour levels
135
- cmap (colormap-spec): Colormap with proplot support
136
- colorbar (bool): Create colorbar automatically
137
- **kwargs: Additional matplotlib contour parameters
138
139
Returns:
140
matplotlib.contour.QuadContourSet: Contour set object
141
"""
142
143
def contourf(self, *args, **kwargs):
144
"""
145
Enhanced filled contour plots.
146
147
Parameters:
148
- X, Y, Z: 2D coordinate and data arrays
149
- levels (int/array): Contour levels
150
- cmap (colormap-spec): Colormap with proplot support
151
- colorbar (bool): Create colorbar automatically
152
- extend (str): Colorbar extension ('neither', 'both', 'min', 'max')
153
- **kwargs: Additional matplotlib contourf parameters
154
155
Returns:
156
matplotlib.contour.QuadContourSet: Filled contour set object
157
"""
158
159
def pcolormesh(self, *args, **kwargs):
160
"""
161
Enhanced pseudocolor mesh plots.
162
163
Parameters:
164
- X, Y, C: Coordinate and color arrays
165
- cmap (colormap-spec): Colormap with proplot support
166
- colorbar (bool): Create colorbar automatically
167
- **kwargs: Additional matplotlib pcolormesh parameters
168
169
Returns:
170
matplotlib.collections.QuadMesh: Mesh collection object
171
"""
172
173
def imshow(self, *args, **kwargs):
174
"""
175
Enhanced image display with proplot integration.
176
177
Parameters:
178
- X: Image data array
179
- cmap (colormap-spec): Colormap with proplot support
180
- colorbar (bool): Create colorbar automatically
181
- aspect (str/float): Image aspect ratio
182
- **kwargs: Additional matplotlib imshow parameters
183
184
Returns:
185
matplotlib.image.AxesImage: Image object
186
"""
187
```
188
189
### Cartesian Axes
190
191
Standard 2D plotting in Cartesian coordinates with comprehensive axis control, dual-axis support, and enhanced formatting.
192
193
```python { .api }
194
class CartesianAxes:
195
"""
196
Enhanced Cartesian coordinate axes with scientific formatting.
197
198
Provides comprehensive control over:
199
- X and Y axis limits, scales, and transformations
200
- Tick mark positioning and formatting
201
- Spine positioning and styling
202
- Grid customization and control
203
- Dual and twin axis creation
204
"""
205
206
def format(self, *,
207
# Aspect and labels
208
aspect=None, xlabel=None, ylabel=None,
209
xlabel_kw=None, ylabel_kw=None,
210
211
# Limits and scales
212
xlim=None, ylim=None, xmin=None, ymin=None, xmax=None, ymax=None,
213
xreverse=None, yreverse=None, xscale=None, yscale=None,
214
xscale_kw=None, yscale_kw=None,
215
xmargin=None, ymargin=None, xbounds=None, ybounds=None,
216
217
# Spine and tick locations
218
xloc=None, yloc=None, xspineloc=None, yspineloc=None,
219
xtickloc=None, ytickloc=None, xticklabelloc=None, yticklabelloc=None,
220
xlabelloc=None, ylabelloc=None, xoffsetloc=None, yoffsetloc=None,
221
222
# Tick properties
223
xtickdir=None, ytickdir=None, xrotation=None, yrotation=None,
224
xticks=None, yticks=None, xlocator=None, ylocator=None,
225
xminorticks=None, yminorticks=None, xminorlocator=None, yminorlocator=None,
226
xlocator_kw=None, ylocator_kw=None,
227
xminorlocator_kw=None, yminorlocator_kw=None,
228
229
# Tick labels and formatters
230
xticklabels=None, yticklabels=None,
231
xformatter=None, yformatter=None,
232
xformatter_kw=None, yformatter_kw=None,
233
xtickrange=None, ytickrange=None,
234
xwraprange=None, ywraprange=None,
235
236
# Colors and styling
237
xcolor=None, ycolor=None, color=None,
238
xlinewidth=None, ylinewidth=None, linewidth=None,
239
xtickcolor=None, ytickcolor=None, tickcolor=None,
240
xticklabelcolor=None, yticklabelcolor=None, ticklabelcolor=None,
241
xlabelcolor=None, ylabelcolor=None, labelcolor=None,
242
243
# Grid properties
244
xgrid=None, ygrid=None, grid=None,
245
xgridminor=None, ygridminor=None, gridminor=None,
246
xgridcolor=None, ygridcolor=None, gridcolor=None,
247
248
**kwargs):
249
"""
250
Format Cartesian axes with comprehensive control options.
251
252
Parameters:
253
- aspect (float/str): Axes aspect ratio ('equal', 'auto', numeric)
254
- xlabel/ylabel (str): Axis labels
255
- xlim/ylim (tuple): Axis limits as (min, max)
256
- xscale/yscale (str): Axis scales ('linear', 'log', 'symlog', etc.)
257
- xspineloc/yspineloc (str): Spine locations ('bottom', 'top', 'zero', etc.)
258
- xticks/yticks (array): Explicit tick positions
259
- xlocator/ylocator (Locator): Tick locator instances
260
- xformatter/yformatter (Formatter): Tick formatter instances
261
- xcolor/ycolor/color (color-spec): Axis colors
262
- xgrid/ygrid/grid (bool): Grid visibility
263
- **kwargs: Additional formatting parameters
264
"""
265
266
def altx(self, **kwargs):
267
"""
268
Create alternate x-axis with independent scale.
269
270
Parameters:
271
- **kwargs: Formatting parameters for alternate axis
272
273
Returns:
274
CartesianAxes: Alternate x-axis sharing y-axis
275
"""
276
277
def alty(self, **kwargs):
278
"""
279
Create alternate y-axis with independent scale.
280
281
Parameters:
282
- **kwargs: Formatting parameters for alternate axis
283
284
Returns:
285
CartesianAxes: Alternate y-axis sharing x-axis
286
"""
287
288
def twinx(self, **kwargs):
289
"""
290
Create twin x-axis (alias for alty).
291
292
Returns:
293
CartesianAxes: Twin x-axis instance
294
"""
295
296
def twiny(self, **kwargs):
297
"""
298
Create twin y-axis (alias for altx).
299
300
Returns:
301
CartesianAxes: Twin y-axis instance
302
"""
303
304
def dualx(self, funcscale, **kwargs):
305
"""
306
Create dual x-axis with unit conversion.
307
308
Parameters:
309
- funcscale (FuncScale/function): Scale transformation function
310
- **kwargs: Additional formatting parameters
311
312
Returns:
313
CartesianAxes: Dual x-axis with unit conversion
314
"""
315
316
def dualy(self, funcscale, **kwargs):
317
"""
318
Create dual y-axis with unit conversion.
319
320
Parameters:
321
- funcscale (FuncScale/function): Scale transformation function
322
- **kwargs: Additional formatting parameters
323
324
Returns:
325
CartesianAxes: Dual y-axis with unit conversion
326
"""
327
```
328
329
### Polar Axes
330
331
Polar coordinate plotting with enhanced theta/radius control, improved angular formatting, and seamless integration with proplot's styling system.
332
333
```python { .api }
334
class PolarAxes:
335
"""
336
Polar coordinate axes with improved angular formatting.
337
338
Enhanced polar plotting with:
339
- Configurable theta direction and origin
340
- Flexible radial scaling and limits
341
- Enhanced grid control for both angular and radial components
342
- Improved label positioning and formatting
343
"""
344
345
def format(self, *,
346
# Polar coordinate system
347
r0=None, theta0=None, thetadir=None,
348
thetamin=None, thetamax=None, thetalim=None,
349
rmin=None, rmax=None, rlim=None,
350
351
# Grid properties
352
thetagrid=None, rgrid=None,
353
thetagridminor=None, rgridminor=None,
354
thetagridcolor=None, rgridcolor=None,
355
356
# Locators and formatters
357
thetalocator=None, rlocator=None,
358
thetalines=None, rlines=None,
359
thetalocator_kw=None, rlocator_kw=None,
360
thetaminorlocator=None, rminorlocator=None,
361
thetaminorlines=None, rminorlines=None,
362
thetaminorlocator_kw=None, rminorlocator_kw=None,
363
364
# Label formatting
365
thetaformatter=None, rformatter=None,
366
thetalabels=None, rlabels=None,
367
thetaformatter_kw=None, rformatter_kw=None,
368
369
# Styling
370
rlabelpos=None, rscale=None, rborder=None,
371
labelpad=None, labelsize=None, labelcolor=None, labelweight=None,
372
**kwargs):
373
"""
374
Format polar axes with comprehensive control.
375
376
Parameters:
377
- r0 (float): Radial origin offset
378
- theta0 (str/float): Angular origin ('N', 'E', 'S', 'W', or degrees)
379
- thetadir (int): Angular direction (1 for counterclockwise, -1 for clockwise)
380
- thetalim (tuple): Angular limits in degrees
381
- rlim (tuple): Radial limits
382
- thetagrid/rgrid (bool): Grid visibility for angular/radial components
383
- thetalocator (Locator): Angular tick locator
384
- rlocator (Locator): Radial tick locator
385
- thetaformatter (Formatter): Angular label formatter
386
- rformatter (Formatter): Radial label formatter
387
- rlabelpos (float): Radial label position (angle in degrees)
388
- rscale (str): Radial axis scale ('linear', 'log', etc.)
389
- **kwargs: Additional formatting parameters
390
"""
391
```
392
393
### Geographic Axes
394
395
Geographic projection axes with cartopy integration, automatic coordinate transformations, and comprehensive map feature support.
396
397
```python { .api }
398
class GeoAxes:
399
"""
400
Geographic projection axes with cartopy integration.
401
402
Enhanced geographic plotting with:
403
- Automatic coordinate system transformations
404
- Comprehensive map feature integration
405
- Flexible longitude/latitude grid control
406
- Support for all cartopy and custom projections
407
"""
408
409
def format(self, *,
410
# Map extent
411
lonlim=None, latlim=None, boundinglat=None,
412
413
# Grid lines
414
longrid=None, latgrid=None,
415
longridminor=None, latgridminor=None,
416
417
# Locators
418
lonlocator=None, lonlines=None,
419
latlocator=None, latlines=None, latmax=None,
420
lonminorlocator=None, lonminorlines=None,
421
latminorlocator=None, latminorlines=None,
422
lonlocator_kw=None, lonlines_kw=None,
423
latlocator_kw=None, latlines_kw=None,
424
lonminorlocator_kw=None, lonminorlines_kw=None,
425
latminorlocator_kw=None, latminorlines_kw=None,
426
427
# Formatters and labels
428
lonformatter=None, latformatter=None,
429
lonformatter_kw=None, latformatter_kw=None,
430
labels=None, latlabels=None, lonlabels=None,
431
loninline=None, latinline=None, inlinelabels=None,
432
rotatelabels=None, labelpad=None, labelcolor=None,
433
labelsize=None, labelweight=None,
434
435
# Advanced options
436
dms=None, nsteps=None,
437
**kwargs):
438
"""
439
Format geographic axes with map-specific controls.
440
441
Parameters:
442
- lonlim (tuple): Longitude limits in degrees
443
- latlim (tuple): Latitude limits in degrees
444
- boundinglat (float): Bounding latitude for polar projections
445
- longrid/latgrid (bool): Grid line visibility
446
- lonlocator/latlocator (Locator): Coordinate grid locators
447
- lonformatter/latformatter (Formatter): Coordinate label formatters
448
- labels (bool): Enable coordinate labels
449
- loninline/latinline (bool): Inline coordinate labels
450
- rotatelabels (bool): Rotate labels to follow grid lines
451
- dms (bool): Use degrees-minutes-seconds formatting
452
- **kwargs: Additional formatting parameters
453
"""
454
455
# Geographic feature methods (configured via rc settings)
456
# Access via: ax.format(land=True, ocean=True, coast=True, etc.)
457
# Available features: land, ocean, coast, rivers, lakes, borders, innerborders
458
```
459
460
### 3D Axes
461
462
3D plotting capabilities with matplotlib's Axes3D integration and proplot's consistent formatting interface.
463
464
```python { .api }
465
class ThreeAxes:
466
"""
467
3D axes with matplotlib's Axes3D integration.
468
469
Provides 3D plotting capabilities while maintaining
470
proplot's consistent formatting interface and
471
enhanced styling options.
472
"""
473
474
def format(self, **kwargs):
475
"""
476
Format 3D axes with extended control options.
477
478
Parameters include all standard axes formatting
479
plus 3D-specific options for viewing angles,
480
axis limits, and 3D styling.
481
"""
482
```
483
484
## Spine Location Options
485
486
Flexible spine positioning system for enhanced visual control:
487
488
```python { .api }
489
SPINE_LOCATIONS = {
490
'left': "Left side of axes",
491
'right': "Right side of axes",
492
'bottom': "Bottom of axes",
493
'top': "Top of axes",
494
'both': "Both relevant sides",
495
'neither': "Hide spines",
496
'zero': "At coordinate zero",
497
'center': "At axes center"
498
}
499
```
500
501
## Scale Support
502
503
Comprehensive axis scaling with seamless integration of matplotlib and proplot scales:
504
505
```python { .api }
506
SUPPORTED_SCALES = {
507
'linear': "Linear scaling",
508
'log': "Logarithmic scaling",
509
'symlog': "Symmetric logarithmic scaling",
510
'logit': "Logit scaling",
511
'power': "Power law scaling",
512
'inverse': "Inverse scaling",
513
'exp': "Exponential scaling",
514
'cutoff': "Cutoff scaling with arbitrary points",
515
'sine': "Sine latitude scaling",
516
'mercator': "Mercator latitude scaling",
517
'func': "Custom function scaling"
518
}
519
```
520
521
## Projection Support
522
523
Complete projection system supporting multiple coordinate systems:
524
525
```python { .api }
526
PROJECTION_TYPES = {
527
# Cartesian
528
'cart': "Standard Cartesian coordinates",
529
'cartesian': "Standard Cartesian coordinates",
530
'rect': "Rectangular coordinates (alias)",
531
'rectilinear': "Rectilinear coordinates (alias)",
532
533
# Polar
534
'polar': "Polar coordinates (r, theta)",
535
536
# Geographic (Cartopy)
537
'platecarree': "Plate Carrée projection",
538
'mercator': "Mercator projection",
539
'lambert': "Lambert Conformal Conic",
540
'stereographic': "Stereographic projection",
541
'orthographic': "Orthographic projection",
542
'mollweide': "Mollweide projection",
543
'robinson': "Robinson projection",
544
'eckert4': "Eckert IV projection",
545
'hammer': "Hammer projection",
546
'aitoff': "Aitoff projection",
547
'winkel3': "Winkel Tripel projection",
548
# ... and many more cartopy projections
549
550
# 3D
551
'3d': "3D plotting with matplotlib's Axes3D",
552
'three': "3D plotting (alias)"
553
}
554
```
555
556
## Usage Examples
557
558
### Basic Cartesian Formatting
559
560
```python
561
import proplot as pplt
562
import numpy as np
563
564
# Create sample data
565
x = np.linspace(0, 10, 100)
566
y = np.sin(x)
567
568
# Basic formatting
569
fig, ax = pplt.subplots()
570
ax.plot(x, y)
571
ax.format(
572
xlabel='Time (seconds)',
573
ylabel='Amplitude',
574
title='Sine Wave',
575
grid=True,
576
xlim=(0, 10),
577
ylim=(-1.2, 1.2)
578
)
579
```
580
581
### Advanced Cartesian Features
582
583
```python
584
# Dual axes with unit conversion
585
fig, ax = pplt.subplots()
586
ax.plot(temp_celsius, pressure)
587
588
# Add Fahrenheit scale
589
ax2 = ax.dualx(lambda c: c * 9/5 + 32)
590
ax.format(
591
xlabel='Temperature (°C)',
592
ylabel='Pressure (hPa)',
593
grid=True
594
)
595
ax2.format(xlabel='Temperature (°F)')
596
597
# Twin axes for multiple datasets
598
ax3 = ax.twinx()
599
ax3.plot(temp_celsius, humidity, color='red')
600
ax3.format(ylabel='Humidity (%)', ycolor='red')
601
```
602
603
### Polar Coordinate Plotting
604
605
```python
606
# Enhanced polar plotting
607
fig, ax = pplt.subplots(proj='polar')
608
theta = np.linspace(0, 2*np.pi, 100)
609
r = 1 + 0.3 * np.cos(5*theta)
610
611
ax.plot(theta, r)
612
ax.format(
613
theta0='N', # North at top
614
thetadir=1, # Counterclockwise
615
rlim=(0, 2), # Radial limits
616
thetagrid=True, # Angular grid
617
rgrid=True, # Radial grid
618
title='Polar Rose'
619
)
620
```
621
622
### Geographic Projection
623
624
```python
625
# Geographic plotting with features
626
fig, ax = pplt.subplots(proj='robinson')
627
ax.contourf(lon, lat, temperature, cmap='RdBu_r')
628
ax.format(
629
# Map features
630
land=True, ocean=True, coast=True,
631
632
# Grid and labels
633
longrid=True, latgrid=True,
634
lonlines=np.arange(-180, 181, 60),
635
latlines=np.arange(-90, 91, 30),
636
labels=True,
637
638
title='Global Temperature'
639
)
640
```
641
642
### Enhanced Plotting Integration
643
644
```python
645
# Automatic colorbar and legend
646
fig, ax = pplt.subplots()
647
648
# Contour plot with automatic colorbar
649
cs = ax.contourf(X, Y, Z, levels=10, cmap='viridis')
650
ax.colorbar(cs, loc='right', label='Values')
651
652
# Line plots with automatic legend
653
ax.plot(x, y1, label='Dataset 1')
654
ax.plot(x, y2, label='Dataset 2')
655
ax.legend(loc='upper left')
656
657
ax.format(
658
xlabel='X coordinate',
659
ylabel='Y coordinate',
660
title='Combined Plot'
661
)
662
```
663
664
### Comprehensive Styling
665
666
```python
667
# Complete visual customization
668
fig, axes = pplt.subplots(ncols=2)
669
for i, ax in enumerate(axes):
670
ax.plot(x, data[i])
671
ax.format(
672
# Limits and scales
673
xlim=(0, 100), xscale='linear',
674
ylim=(0.1, 1000), yscale='log',
675
676
# Tick customization
677
xticks=[0, 25, 50, 75, 100],
678
xticklabels=['Zero', 'Quarter', 'Half', 'Three-Quarter', 'Full'],
679
yformatter='log',
680
681
# Grid and spines
682
grid=True, gridminor=True,
683
xspineloc='bottom', yspineloc='left',
684
685
# Colors and styling
686
color='navy', gridcolor='gray',
687
labelcolor='black', titlecolor='darkblue',
688
689
# Labels
690
xlabel='Progress (%)',
691
ylabel='Response (units)',
692
title=f'Experiment {i+1}'
693
)
694
```
695
696
This comprehensive axes system provides powerful and consistent formatting capabilities across all coordinate systems while maintaining the flexibility to handle specialized requirements for each projection type.