0
# Visualization
1
2
matplotlib-based visualization functions for parameter profiles, confidence contours, and model-data agreement. These functions help visualize fit results, parameter uncertainties, and correlations.
3
4
## Capabilities
5
6
### Profile Plots
7
8
1D profiles showing how the cost function varies with individual parameters.
9
10
```python { .api }
11
def profile(self, vname, size=100, bound=2, grid=None, subtract_min=False):
12
"""
13
Calculate 1D cost function profile over a range.
14
15
Args:
16
vname: Parameter name or index to profile
17
size: Number of points in profile (int, default: 100)
18
bound: Range specification (float or UserBound):
19
- float: symmetric range in units of parameter error
20
- UserBound: explicit (min, max) range
21
grid: Custom grid points (array-like, optional)
22
subtract_min: If True, subtract minimum value from profile
23
24
Returns:
25
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
26
"""
27
28
def draw_profile(self, vname, band=True, text=True, **kwargs):
29
"""
30
Draw 1D cost function profile over a range (requires matplotlib).
31
32
Args:
33
vname: Parameter name or index to profile
34
band: Whether to show confidence band (bool, default: True)
35
text: Whether to show parameter information text (bool, default: True)
36
**kwargs: Additional arguments passed to matplotlib plotting functions
37
38
Returns:
39
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
40
"""
41
```
42
43
### Minos Profiles
44
45
1D Minos profiles showing asymmetric confidence intervals.
46
47
```python { .api }
48
def mnprofile(self, vname, size=30, bound=2, grid=None, subtract_min=False,
49
ncall=0, iterate=5, use_simplex=True):
50
"""
51
Get Minos profile over a specified interval.
52
53
Args:
54
vname: Parameter name or index to profile
55
size: Number of points in profile (int, default: 30)
56
bound: Range specification (float or UserBound)
57
grid: Custom grid points (array-like, optional)
58
subtract_min: If True, subtract minimum value from profile
59
ncall: Maximum function calls per point (int, default: 0 = no limit)
60
iterate: Number of iterations if convergence fails
61
use_simplex: Whether to use Simplex if MIGRAD fails
62
63
Returns:
64
Tuple[np.ndarray, np.ndarray, np.ndarray]:
65
(parameter_values, cost_values, valid_points)
66
"""
67
68
def draw_mnprofile(self, vname, band=True, text=True, **kwargs):
69
"""
70
Draw Minos profile over a specified interval (requires matplotlib).
71
72
Args:
73
vname: Parameter name or index to profile
74
band: Whether to show confidence band (bool, default: True)
75
text: Whether to show parameter information text (bool, default: True)
76
**kwargs: Additional arguments passed to matplotlib plotting functions
77
78
Returns:
79
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
80
"""
81
```
82
83
### Contour Plots
84
85
2D contours showing parameter correlations and confidence regions.
86
87
```python { .api }
88
def contour(self, x, y, size=50, bound=2, grid=None, subtract_min=False):
89
"""
90
Get a 2D contour of the function around the minimum.
91
92
Args:
93
x: First parameter name or index
94
y: Second parameter name or index
95
size: Number of points per dimension (int, default: 50)
96
bound: Range specification (float or sequence of 2 tuples)
97
grid: Custom grid (tuple of 2 arrays, optional)
98
subtract_min: If True, subtract minimum value from contour
99
100
Returns:
101
Tuple[np.ndarray, np.ndarray, np.ndarray]:
102
(x_values, y_values, cost_values_2d)
103
"""
104
105
def draw_contour(self, x, y, **kwargs):
106
"""
107
Draw 2D contour around minimum (requires matplotlib).
108
109
Args:
110
x: First parameter name or index
111
y: Second parameter name or index
112
**kwargs: Additional arguments passed to matplotlib contour functions
113
114
Returns:
115
Tuple[np.ndarray, np.ndarray, np.ndarray]:
116
(x_values, y_values, cost_values_2d)
117
"""
118
```
119
120
### Minos Contours
121
122
2D Minos confidence regions with proper statistical interpretation.
123
124
```python { .api }
125
def mncontour(self, x, y, cl=None, size=100, interpolated=0, experimental=False,
126
ncall=0, iterate=5, use_simplex=True):
127
"""
128
Get 2D Minos confidence region.
129
130
Args:
131
x: First parameter name or index
132
y: Second parameter name or index
133
cl: Confidence level (float, optional, uses errordef if None)
134
size: Number of points on contour (int, default: 100)
135
interpolated: Interpolation level (int, default: 0)
136
experimental: Use experimental algorithm (bool, default: False)
137
ncall: Maximum function calls (int, default: 0 = no limit)
138
iterate: Number of iterations if convergence fails
139
use_simplex: Whether to use Simplex if MIGRAD fails
140
141
Returns:
142
np.ndarray: Array of (x, y) points on confidence contour
143
"""
144
145
def draw_mncontour(self, x, y, cl=None, size=100, interpolated=0, experimental=False):
146
"""
147
Draw 2D Minos confidence region (requires matplotlib).
148
149
Args:
150
x: First parameter name or index
151
y: Second parameter name or index
152
cl: Confidence level(s) (float or array-like, optional)
153
size: Number of points on contour (int, default: 100)
154
interpolated: Interpolation level (int, default: 0)
155
experimental: Use experimental algorithm (bool, default: False)
156
157
Returns:
158
Matplotlib artist objects
159
"""
160
```
161
162
### Matrix Visualization
163
164
Visualization of parameter correlation and error matrices.
165
166
```python { .api }
167
def draw_mnmatrix(self, cl=None, size=100, experimental=False, figsize=None):
168
"""
169
Draw matrix of Minos scans (requires matplotlib).
170
171
Args:
172
cl: Confidence level(s) (float or array-like, optional)
173
size: Number of points per profile (int, default: 100)
174
experimental: Use experimental algorithm (bool, default: False)
175
figsize: Figure size tuple (optional)
176
177
Returns:
178
Matplotlib figure object
179
"""
180
```
181
182
### Model Visualization
183
184
Visualization of model-data agreement for cost functions that support it.
185
186
```python { .api }
187
def visualize(self, plot=None, **kwargs):
188
"""
189
Visualize agreement of current model with data (requires matplotlib).
190
191
Args:
192
plot: Custom plotting function (callable, optional)
193
Signature: plot(x, y, y_model, **kwargs)
194
**kwargs: Additional arguments passed to plotting functions
195
196
Note:
197
Only works with cost functions that provide visualization support
198
(LeastSquares, BinnedNLL, etc.)
199
"""
200
```
201
202
### Interactive Fitting
203
204
Interactive GUI widgets for parameter adjustment and live fitting.
205
206
```python { .api }
207
def interactive(self, plot=None, raise_on_exception=False, **kwargs):
208
"""
209
Interactive GUI for fitting (requires ipywidgets in Jupyter).
210
211
Args:
212
plot: Custom plotting function (callable, optional)
213
raise_on_exception: Whether to raise exceptions or show warnings
214
**kwargs: Additional arguments passed to plotting functions
215
216
Note:
217
Creates interactive sliders for parameter adjustment with live updates
218
of fit results and visualizations.
219
"""
220
```
221
222
## Usage Examples
223
224
### Basic Profile Plot
225
226
```python
227
from iminuit import Minuit
228
import matplotlib.pyplot as plt
229
230
# After fitting
231
m.migrad()
232
m.hesse()
233
234
# Draw parameter profile
235
x, y = m.draw_profile('slope')
236
plt.show()
237
238
# Or get profile data without plotting
239
x_vals, cost_vals = m.profile('slope', size=200)
240
plt.plot(x_vals, cost_vals)
241
plt.xlabel('slope')
242
plt.ylabel('Cost function')
243
plt.show()
244
```
245
246
### Minos Profile with Custom Range
247
248
```python
249
from iminuit.typing import UserBound
250
251
# Minos profile over custom range
252
x, y = m.draw_mnprofile('slope', bound=UserBound(-1, 5))
253
plt.title('Minos Profile for Slope Parameter')
254
plt.show()
255
```
256
257
### 2D Contour Plot
258
259
```python
260
# Draw contour between two parameters
261
x, y, z = m.draw_contour('slope', 'intercept')
262
plt.colorbar(label='Cost function')
263
plt.show()
264
265
# Multiple confidence levels
266
m.draw_mncontour('slope', 'intercept', cl=[0.68, 0.95])
267
plt.legend(['68% CL', '95% CL'])
268
plt.show()
269
```
270
271
### Custom Plotting Style
272
273
```python
274
# Customize plot appearance
275
m.draw_profile('slope',
276
band=True, # Show confidence band
277
text=False, # Hide parameter text
278
color='red', # Line color
279
linewidth=2, # Line width
280
alpha=0.7) # Transparency
281
plt.title('Custom Profile Plot')
282
plt.show()
283
```
284
285
### Model Visualization
286
287
```python
288
from iminuit.cost import LeastSquares
289
290
# For cost functions that support visualization
291
cost = LeastSquares(x_data, y_data, y_errors, model_func)
292
m = Minuit(cost, param1=1, param2=2)
293
m.migrad()
294
295
# Visualize model vs data
296
m.visualize()
297
plt.show()
298
299
# Custom visualization function
300
def my_plot(x, y, y_model):
301
plt.errorbar(x, y, yerr=y_errors, fmt='o', label='Data')
302
plt.plot(x, y_model, '-', label='Model')
303
plt.legend()
304
305
m.visualize(plot=my_plot)
306
plt.show()
307
```
308
309
### Matrix of Profiles
310
311
```python
312
# Draw matrix showing all parameter profiles
313
fig = m.draw_mnmatrix(cl=[0.68, 0.95], size=50)
314
fig.suptitle('Parameter Correlation Matrix')
315
plt.show()
316
```
317
318
### Interactive Fitting (Jupyter)
319
320
```python
321
# Interactive parameter adjustment in Jupyter notebook
322
m.interactive()
323
324
# With custom plot function
325
def custom_plot(x, y, y_model):
326
plt.figure(figsize=(10, 6))
327
plt.subplot(2, 1, 1)
328
plt.errorbar(x, y, yerr=y_errors, fmt='o')
329
plt.plot(x, y_model, '-')
330
plt.ylabel('Data')
331
332
plt.subplot(2, 1, 2)
333
plt.plot(x, y - y_model, 'o')
334
plt.ylabel('Residuals')
335
plt.xlabel('x')
336
337
m.interactive(plot=custom_plot)
338
```
339
340
### Saving Plots
341
342
```python
343
# Save profile plot
344
x, y = m.draw_profile('slope')
345
plt.savefig('parameter_profile.png', dpi=300)
346
plt.close()
347
348
# Save contour plot
349
m.draw_contour('slope', 'intercept')
350
plt.savefig('parameter_contour.pdf')
351
plt.close()
352
```
353
354
### Subplots and Multiple Profiles
355
356
```python
357
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
358
359
# Profile for first parameter
360
plt.sca(axes[0])
361
m.draw_profile('slope', text=False)
362
plt.title('Slope Profile')
363
364
# Profile for second parameter
365
plt.sca(axes[1])
366
m.draw_profile('intercept', text=False)
367
plt.title('Intercept Profile')
368
369
plt.tight_layout()
370
plt.show()
371
```
372
373
### Advanced Contour Customization
374
375
```python
376
# Custom contour levels and styling
377
x, y, z = m.contour('slope', 'intercept', size=100)
378
379
# Create custom contour plot
380
plt.figure(figsize=(8, 6))
381
levels = [0.5, 2.0, 4.5, 8.0] # Custom confidence levels
382
cs = plt.contour(x, y, z, levels=levels, colors=['blue', 'green', 'orange', 'red'])
383
plt.clabel(cs, inline=True, fontsize=10)
384
plt.scatter(m.values['slope'], m.values['intercept'],
385
marker='*', s=100, color='black', label='Best fit')
386
plt.xlabel('Slope')
387
plt.ylabel('Intercept')
388
plt.legend()
389
plt.show()
390
```
391
392
## Requirements
393
394
All visualization functions require matplotlib to be installed:
395
```bash
396
pip install matplotlib
397
```
398
399
Interactive fitting additionally requires ipywidgets:
400
```bash
401
pip install ipywidgets
402
```