0
# Visualization
1
2
Tools for creating astronomical plots and visualizations with matplotlib integration and astronomy-specific features.
3
4
## Core Imports
5
6
```python
7
from astropy.visualization import quantity_support
8
from astropy.visualization import ImageNormalize, MinMaxInterval, ZScaleInterval
9
from astropy.visualization import LogStretch, SqrtStretch, AsinhStretch, LinearStretch
10
from astropy.visualization import make_lupton_rgb
11
```
12
13
## Capabilities
14
15
### Matplotlib Integration
16
17
Functions to enable matplotlib to work seamlessly with astropy objects and quantities.
18
19
```python { .api }
20
def quantity_support(format='latex'):
21
"""
22
Enable matplotlib to work with astropy Quantity objects.
23
24
Parameters:
25
- format: format for unit display ('latex', 'unicode', 'console')
26
27
This function allows matplotlib to automatically handle Quantity objects
28
for axis labels and formatting.
29
"""
30
```
31
32
### Image Normalization
33
34
Classes for normalizing astronomical image data with appropriate scaling and clipping.
35
36
```python { .api }
37
class ImageNormalize:
38
"""
39
Normalization class for astronomical images.
40
41
Parameters:
42
- data: image data for determining normalization (optional)
43
- interval: interval method for data clipping
44
- vmin: minimum value for normalization
45
- vmax: maximum value for normalization
46
- stretch: stretch function to apply
47
- clip: whether to clip values outside [0,1]
48
"""
49
def __init__(self, data=None, interval=None, vmin=None, vmax=None, stretch=LinearStretch(), clip=True): ...
50
51
def __call__(self, values, clip=None):
52
"""Apply normalization to values."""
53
54
def inverse(self, values):
55
"""Apply inverse normalization."""
56
57
class ManualInterval:
58
"""
59
Manually specified interval for normalization.
60
61
Parameters:
62
- vmin: minimum value
63
- vmax: maximum value
64
"""
65
def __init__(self, vmin, vmax): ...
66
67
class MinMaxInterval:
68
"""Interval from minimum to maximum values in data."""
69
def __init__(self): ...
70
71
class PercentileInterval:
72
"""
73
Interval based on percentiles of the data.
74
75
Parameters:
76
- percentile: percentile value (e.g., 95 for 2.5% to 97.5%)
77
- n_samples: number of samples for percentile calculation
78
"""
79
def __init__(self, percentile, n_samples=None): ...
80
81
class AsymmetricPercentileInterval:
82
"""
83
Interval with different lower and upper percentiles.
84
85
Parameters:
86
- lower_percentile: lower percentile
87
- upper_percentile: upper percentile
88
- n_samples: number of samples
89
"""
90
def __init__(self, lower_percentile, upper_percentile, n_samples=None): ...
91
92
class ZScaleInterval:
93
"""
94
Interval using IRAF's zscale algorithm.
95
96
Parameters:
97
- nsamples: number of sample points
98
- contrast: contrast parameter
99
- max_reject: maximum fraction of pixels to reject
100
- min_npixels: minimum number of pixels for fitting
101
- krej: k-sigma rejection threshold
102
- max_iterations: maximum iterations for rejection
103
"""
104
def __init__(self, nsamples=1000, contrast=0.25, max_reject=0.5, min_npixels=5, krej=2.5, max_iterations=5): ...
105
```
106
107
### Stretch Functions
108
109
Functions for applying different stretch algorithms to image data.
110
111
```python { .api }
112
class LinearStretch:
113
"""Linear stretch (no transformation)."""
114
def __init__(self): ...
115
116
class LogStretch:
117
"""
118
Logarithmic stretch.
119
120
Parameters:
121
- a: stretch parameter (default 1000)
122
"""
123
def __init__(self, a=1000): ...
124
125
class SqrtStretch:
126
"""Square root stretch."""
127
def __init__(self): ...
128
129
class SquaredStretch:
130
"""Squared stretch."""
131
def __init__(self): ...
132
133
class AsinhStretch:
134
"""
135
Inverse hyperbolic sine stretch.
136
137
Parameters:
138
- a: stretch parameter
139
"""
140
def __init__(self, a=0.1): ...
141
142
class SinhStretch:
143
"""
144
Hyperbolic sine stretch.
145
146
Parameters:
147
- a: stretch parameter
148
"""
149
def __init__(self, a=0.33): ...
150
151
class PowerStretch:
152
"""
153
Power law stretch.
154
155
Parameters:
156
- a: power law index
157
"""
158
def __init__(self, a=1.0): ...
159
160
class PowerDistStretch:
161
"""
162
Power distribution stretch.
163
164
Parameters:
165
- a: power parameter
166
"""
167
def __init__(self, a=1000): ...
168
169
class ContrastBiasStretch:
170
"""
171
Contrast-bias stretch.
172
173
Parameters:
174
- contrast: contrast parameter
175
- bias: bias parameter
176
"""
177
def __init__(self, contrast, bias): ...
178
179
class HistEqStretch:
180
"""
181
Histogram equalization stretch.
182
183
Parameters:
184
- data: data for computing histogram
185
- values: values to stretch
186
"""
187
def __init__(self, data, values=None): ...
188
```
189
190
### Color Image Creation
191
192
Functions for creating color composite images from multiple bands.
193
194
```python { .api }
195
def make_lupton_rgb(image_r, image_g, image_b, minimum=0, stretch=5, Q=8, filename=None):
196
"""
197
Create RGB color image using Lupton et al. algorithm.
198
199
Parameters:
200
- image_r: red channel image data
201
- image_g: green channel image data
202
- image_b: blue channel image data
203
- minimum: minimum value for scaling
204
- stretch: stretch parameter
205
- Q: asinh scaling parameter
206
- filename: output filename (optional)
207
208
Returns:
209
array: RGB image array
210
"""
211
212
def lupton_rgb(image_r, image_g, image_b, minimum=0, stretch=5, Q=8):
213
"""
214
Apply Lupton RGB scaling to images.
215
216
Parameters: (same as make_lupton_rgb)
217
218
Returns:
219
tuple: (scaled_r, scaled_g, scaled_b) arrays
220
"""
221
```
222
223
### Plotting Utilities
224
225
Utility functions for astronomical plotting and data visualization.
226
227
```python { .api }
228
def simple_norm(data, stretch='linear', power=1.0, asinh_a=0.1, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None, clip=True):
229
"""
230
Simple image normalization function.
231
232
Parameters:
233
- data: image data
234
- stretch: stretch type ('linear', 'sqrt', 'log', 'asinh', 'power')
235
- power: power for power stretch
236
- asinh_a: parameter for asinh stretch
237
- min_cut: minimum cut value
238
- max_cut: maximum cut value
239
- min_percent: minimum percentile cut
240
- max_percent: maximum percentile cut
241
- percent: symmetric percentile cut
242
- clip: whether to clip values
243
244
Returns:
245
ImageNormalize: normalization object
246
"""
247
248
def hist(x, bins=10, ax=None, max_bins=1e6, **kwargs):
249
"""
250
Enhanced histogram function with automatic binning.
251
252
Parameters:
253
- x: data to histogram
254
- bins: number of bins or bin edges
255
- ax: matplotlib axes object
256
- max_bins: maximum number of bins
257
- **kwargs: additional arguments for matplotlib.hist
258
259
Returns:
260
tuple: (n, bins, patches) from matplotlib.hist
261
"""
262
```
263
264
## Usage Examples
265
266
### Basic Image Display
267
268
```python
269
import numpy as np
270
import matplotlib.pyplot as plt
271
from astropy.visualization import ImageNormalize, ZScaleInterval, LogStretch
272
273
# Create sample image data
274
data = np.random.random((100, 100)) * 1000 + np.random.exponential(100, (100, 100))
275
276
# Apply zscale normalization with log stretch
277
norm = ImageNormalize(data, interval=ZScaleInterval(), stretch=LogStretch())
278
279
# Display image
280
plt.figure(figsize=(8, 6))
281
plt.imshow(data, norm=norm, cmap='viridis', origin='lower')
282
plt.colorbar()
283
plt.title('Astronomical Image with ZScale + Log Stretch')
284
plt.show()
285
```
286
287
### Quantity Support for Plots
288
289
```python
290
from astropy.visualization import quantity_support
291
import astropy.units as u
292
293
# Enable quantity support
294
quantity_support()
295
296
# Create data with units
297
time = np.linspace(0, 10, 100) * u.day
298
flux = 1000 + 100 * np.sin(2 * np.pi * time / (2 * u.day)) * u.Jy
299
300
# Plot with automatic unit formatting
301
plt.figure(figsize=(8, 5))
302
plt.plot(time, flux)
303
plt.xlabel('Time') # Will automatically show "(day)"
304
plt.ylabel('Flux') # Will automatically show "(Jy)"
305
plt.title('Light Curve')
306
plt.show()
307
```
308
309
### Creating RGB Images
310
311
```python
312
from astropy.visualization import make_lupton_rgb
313
314
# Simulate three-band image data
315
r_band = np.random.exponential(50, (200, 200))
316
g_band = np.random.exponential(40, (200, 200))
317
b_band = np.random.exponential(30, (200, 200))
318
319
# Create RGB image
320
rgb_image = make_lupton_rgb(r_band, g_band, b_band,
321
minimum=0, stretch=0.5, Q=10)
322
323
# Display RGB image
324
plt.figure(figsize=(8, 8))
325
plt.imshow(rgb_image, origin='lower')
326
plt.title('RGB Composite Image')
327
plt.axis('off')
328
plt.show()
329
```
330
331
### Custom Stretch Applications
332
333
```python
334
from astropy.visualization import AsinhStretch, PercentileInterval
335
336
# Apply asinh stretch with percentile interval
337
interval = PercentileInterval(99.5)
338
stretch = AsinhStretch(a=0.1)
339
norm = ImageNormalize(data, interval=interval, stretch=stretch)
340
341
plt.figure(figsize=(12, 4))
342
343
# Original data
344
plt.subplot(1, 3, 1)
345
plt.imshow(data, origin='lower', cmap='gray')
346
plt.title('Original')
347
348
# Linear stretch
349
plt.subplot(1, 3, 2)
350
plt.imshow(data, norm=ImageNormalize(data, interval=interval),
351
origin='lower', cmap='gray')
352
plt.title('Linear Stretch')
353
354
# Asinh stretch
355
plt.subplot(1, 3, 3)
356
plt.imshow(data, norm=norm, origin='lower', cmap='gray')
357
plt.title('Asinh Stretch')
358
359
plt.tight_layout()
360
plt.show()
361
```
362
363
## Types
364
365
```python { .api }
366
# Normalization types
367
ImageNormalize = astropy.visualization.ImageNormalize
368
369
# Interval types
370
ManualInterval = astropy.visualization.ManualInterval
371
MinMaxInterval = astropy.visualization.MinMaxInterval
372
PercentileInterval = astropy.visualization.PercentileInterval
373
ZScaleInterval = astropy.visualization.ZScaleInterval
374
375
# Stretch types
376
LinearStretch = astropy.visualization.LinearStretch
377
LogStretch = astropy.visualization.LogStretch
378
SqrtStretch = astropy.visualization.SqrtStretch
379
AsinhStretch = astropy.visualization.AsinhStretch
380
```