Debian Codegraph @

skrf/plotting.py

raw symbols SCIP
1 """
2 plotting (:mod:`skrf.plotting`)
3 ========================================
4
5
6 This module provides general plotting functions.
7
8 Plots and Charts
9 ------------------
10
11 .. autosummary::
12 :toctree: generated/
13
14 smith
15 plot_smith
16 plot_rectangular
17 plot_polar
18 plot_complex_rectangular
19 plot_complex_polar
20 plot_it_all
21
22 plot_minmax_bounds_component
23 plot_minmax_bounds_s_db
24 plot_minmax_bounds_s_db10
25 plot_minmax_bounds_s_time_db
26
27 plot_uncertainty_bounds_component
28 plot_uncertainty_bounds_s_db
29 plot_uncertainty_bounds_s_time_db
30
31 plot_passivity
32 plot_logsigma
33
34 plot_contour
35
36 Convenience plotting functions
37 -------------------------------
38 .. autosummary::
39 :toctree: generated/
40
41 stylely
42 subplot_params
43 shade_bands
44 save_all_figs
45 scale_frequency_ticks
46 add_markers_to_lines
47 legend_off
48 func_on_all_figs
49 scrape_legend
50 signature
51
52 """
53 from __future__ import annotations
54
55 import os
56 import warnings
57 from collections.abc import Callable
58 from numbers import Number
59 from typing import TYPE_CHECKING
60
61 try:
62 import matplotlib as mpl
63 import matplotlib.pyplot as plt
64 import matplotlib.tri as tri
65 from matplotlib import rcParams, ticker
66 from matplotlib.dates import date2num
67 from matplotlib.patches import Circle # for drawing smith chart
68 from matplotlib.pyplot import quiver
69 except ImportError:
70 pass
71
72 import numpy as np
73
74 from . import mathFunctions as mf
75 from .constants import NumberLike, PrimaryPropertiesT
76 from .frequency import Frequency
77 from .util import axes_kwarg, now_string_2_dt
78
79 if TYPE_CHECKING:
80 from . import Network, NetworkSet
81
82 SI_PREFIXES_ASCII = 'yzafpnum kMGTPEZY'
83 SI_CONVERSION = {key: 10**((8-i)*3) for i, key in enumerate(SI_PREFIXES_ASCII)}
84
85 def _get_label_str(netw: Network, param: str, m: int, n: int) -> str:
86 label_string = ""
87 if netw.name is not None:
88 label_string += f"{netw.name}, "
89
90 if plt.rcParams['text.usetex']:
91 label_string += f"${param}_{{{netw._fmt_trace_name(m,n)}}}$"
92 else:
93 label_string += f"{param}{netw._fmt_trace_name(m,n)}"
94 return label_string
95
96
97 def scale_frequency_ticks(ax: plt.Axes, funit: str):
98 """
99 Scale frequency axis ticks.
100
101 Parameters
102 ----------
103 ax : plt.Axes
104 Matplotlib figure axe
105 funit : str
106 frequency unit string as in :data:`~skrf.frequency.Frequency.unit`
107
108 Raises
109 ------
110 ValueError
111 if invalid unit is passed
112 """
113 if funit.lower() == "hz":
114 prefix = " "
115 scale = 1
116 elif len(funit) == 3:
117 prefix = funit[0]
118 scale = SI_CONVERSION[prefix]
119 else:
120 raise ValueError(f"invalid funit {funit}")
121 ticks_x = ticker.FuncFormatter(lambda x, pos: f'{x * scale:g}')
122 ax.xaxis.set_major_formatter(ticks_x)
123
124 @axes_kwarg
125 def smith(smithR: Number = 1, chart_type: str = 'z', draw_labels: bool = False,
126 border: bool = False, ax: plt.Axes | None = None, ref_imm: float = 1.0,
127 draw_vswr: list | bool | None = None):
128 """
129 Plot the Smith chart of a given radius.
130
131 The Smith chart is used to assist in solving problems with transmission lines
132 and matching circuits. It can be used to simultaneously display multiple
133 parameters including impedances, admittances, reflection coefficients,
134 scattering parameters, noise figure circles, etc. [#]_
135
136 Parameters
137 ----------
138 smithR : number, optional
139 radius of smith chart. Default is 1.
140 chart_type : str, optional
141 Contour type. Default is 'z'. Possible values are:
142
143 * *'z'* : lines of constant impedance
144 * *'y'* : lines of constant admittance
145 * *'zy'* : lines of constant impedance stronger than admittance
146 * *'yz'* : lines of constant admittance stronger than impedance
147 draw_labels : Boolean, optional
148 annotate real and imaginary parts of impedance on the
149 chart (only if smithR=1).
150 Default is False.
151 border : Boolean, optional.
152 draw a rectangular border with axis ticks, around the perimeter
153 of the figure. Not used if draw_labels = True.
154 Default is False.
155 ax : :class:`matplotlib.pyplot.Axes` or None, optional
156 existing axes to draw smith chart on.
157 Default is None (creates a new figure)
158 ref_imm : number, optional
159 Reference immittance for center of Smith chart. Only changes
160 labels, if printed.
161 Default is 1.0.
162 draw_vswr : list of numbers, Boolean or None, optional
163 draw VSWR circles. If True, default values are used.
164 Default is None.
165
166 References
167 ----------
168 .. [#] https://en.wikipedia.org/wiki/Smith_chart
169
170 """
171
172 # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which
173 # are the contours on the smith chart
174 contour = []
175
176 # these are hard-coded on purpose,as they should always be present
177 rHeavyList = [0,1]
178 xHeavyList = [1,-1]
179
180 #TODO: fix this
181 # these could be dynamically coded in the future, but work good'nuff for now
182 if not draw_labels:
183 rLightList = np.logspace(3,-5,9,base=.5)
184 xLightList = np.hstack([np.logspace(2,-5,8,base=.5), -1*np.logspace(2,-5,8,base=.5)])
185 else:
186 rLightList = np.array( [ 0.2, 0.5, 1.0, 2.0, 5.0 ] )
187 xLightList = np.array( [ 0.2, 0.5, 1.0, 2.0 , 5.0, -0.2, -0.5, -1.0, -2.0, -5.0 ] )
188
189 # vswr lines
190 if isinstance(draw_vswr, (tuple,list)):
191 vswrVeryLightList = draw_vswr
192 elif draw_vswr is True:
193 # use the default I like
194 vswrVeryLightList = [1.5, 2.0, 3.0, 5.0]
195 else:
196 vswrVeryLightList = []
197
198 # cheap way to make a ok-looking smith chart at larger than 1 radii
199 if smithR > 1:
200 rMax = (1.+smithR)/(1.-smithR)
201 rLightList = np.hstack([ np.linspace(0,rMax,11) , rLightList ])
202
203 if chart_type.startswith('y'):
204 y_flip_sign = -1
205 else:
206 y_flip_sign = 1
207
208 # draw impedance and/or admittance
209 both_charts = chart_type in ('zy', 'yz')
210
211
212 # loops through Verylight, Light and Heavy lists and draws circles using patches
213 # for analysis of this see R.M. Weikles Microwave II notes (from uva)
214
215 superLightColor = dict(ec='whitesmoke', fc='none')
216 veryLightColor = dict(ec='lightgrey', fc='none')
217 lightColor = dict(ec='grey', fc='none')
218 heavyColor = dict(ec='black', fc='none')
219
220 # vswr circles verylight
221 for vswr in vswrVeryLightList:
222 radius = (vswr-1.0) / (vswr+1.0)
223 contour.append( Circle((0, 0), radius, **veryLightColor))
224
225 # impedance/admittance circles
226 for r in rLightList:
227 center = (r/(1.+r)*y_flip_sign,0 )
228 radius = 1./(1+r)
229 if both_charts:
230 contour.insert(0, Circle((-center[0], center[1]), radius, **superLightColor))
231 contour.append(Circle(center, radius, **lightColor))
232 for x in xLightList:
233 center = (1*y_flip_sign,1./x)
234 radius = 1./x
235 if both_charts:
236 contour.insert(0, Circle( (-center[0], center[1]), radius, **superLightColor))
237 contour.append(Circle(center, radius, **lightColor))
238
239 for r in rHeavyList:
240 center = (r/(1.+r)*y_flip_sign,0 )
241 radius = 1./(1+r)
242 contour.append(Circle(center, radius, **heavyColor))
243 for x in xHeavyList:
244 center = (1*y_flip_sign,1./x)
245 radius = 1./x
246 contour.append(Circle(center, radius, **heavyColor))
247
248 # clipping circle
249 clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True)
250 ax.add_patch( clipc)
251
252 #draw x and y axis
253 ax.axhline(0, color='k', lw=.1, clip_path=clipc)
254 ax.axvline(1*y_flip_sign, color='k', clip_path=clipc)
255 ax.grid(0)
256 # Set axis limits by plotting white points so zooming works properly
257 ax.plot(smithR*np.array([-1.1, 1.1]), smithR*np.array([-1.1, 1.1]), 'w.', markersize = 0)
258 ax.axis('image') # Combination of 'equal' and 'tight'
259
260
261 if not border:
262 ax.yaxis.set_ticks([])
263 ax.xaxis.set_ticks([])
264 for spine in ax.spines.values():
265 spine.set_color('none')
266
267
268 if draw_labels:
269 #Clear axis
270 ax.yaxis.set_ticks([])
271 ax.xaxis.set_ticks([])
272 for spine in ax.spines.values():
273 spine.set_color('none')
274
275 # Make annotations only if the radius is 1
276 if smithR == 1:
277 #Make room for annotation
278 ax.plot(np.array([-1.25, 1.25]), np.array([-1.1, 1.1]), 'w.', markersize = 0)
279 ax.axis('image')
280
281 #Annotate real part
282 for value in rLightList:
283 # Set radius of real part's label; offset slightly left (Z
284 # chart, y_flip_sign == 1) or right (Y chart, y_flip_sign == -1)
285 # so label doesn't overlap chart's circles
286 rho = (value - 1)/(value + 1) - y_flip_sign*0.01
287 if y_flip_sign == 1:
288 halignstyle = "right"
289 else:
290 halignstyle = "left"
291 if y_flip_sign == -1: # 'y' and 'yz' charts
292 value = 1/value
293 ax.annotate(str(value*ref_imm), xy=(rho*smithR, 0.01),
294 xytext=(rho*smithR, 0.01), ha = halignstyle, va = "baseline")
295
296 #Annotate imaginary part
297 radialScaleFactor = 1.01 # Scale radius of label position by this
298 # factor. Making it >1 places the label
299 # outside the Smith chart's circle
300 for value in xLightList:
301 #Transforms from complex to cartesian
302 S = (1j*value - 1) / (1j*value + 1)
303 S *= smithR * radialScaleFactor
304 rhox = S.real
305 rhoy = S.imag * y_flip_sign
306
307 # Choose alignment anchor point based on label's value
308 if ((value == 1.0) or (value == -1.0)):
309 halignstyle = "center"
310 elif (rhox < 0.0):
311 halignstyle = "right"
312 else:
313 halignstyle = "left"
314
315 if (rhoy < 0):
316 valignstyle = "top"
317 else:
318 valignstyle = "bottom"
319 if y_flip_sign == -1: # 'y' and 'yz' charts
320 value = 1/value
321 #Annotate value
322 ax.annotate(str(value*ref_imm) + 'j', xy=(rhox, rhoy),
323 xytext=(rhox, rhoy), ha = halignstyle, va = valignstyle)
324
325 #Annotate 0 and inf
326 if y_flip_sign == 1: # z and zy charts
327 label_left, label_right = '0.0', r'$\infty$'
328 else: # y and yz charts
329 label_left, label_right = r'$\infty$', '0.0'
330 ax.annotate(label_left, xy=(-1.02, 0), xytext=(-1.02, 0),
331 ha = "right", va = "center")
332 ax.annotate(label_right, xy=(radialScaleFactor, 0), xytext=(radialScaleFactor, 0),
333 ha = "left", va = "center")
334
335 # annotate vswr circles
336 for vswr in vswrVeryLightList:
337 rhoy = (vswr-1.0) / (vswr+1.0)
338
339 ax.annotate(str(vswr), xy=(0, rhoy*smithR),
340 xytext=(0, rhoy*smithR), ha="center", va="bottom",
341 color='grey', size='smaller')
342
343 # loop though contours and draw them on the given axes
344 for currentContour in contour:
345 cc=ax.add_patch(currentContour)
346 cc.set_clip_path(clipc)
347
348
349 def plot_rectangular(x: NumberLike, y: NumberLike,
350 x_label: str | None = None, y_label: str | None = None,
351 title: str | None = None, show_legend: bool = True,
352 axis: str = 'tight', ax: plt.Axes | None = None,
353 *args, **kwargs):
354 r"""
355 Plot rectangular data and optionally label axes.
356
357 Parameters
358 ----------
359 x : array-like, of complex data
360 data to plot
361 y : array-like, of complex data
362 data to plot
363 x_label : string or None, optional.
364 x-axis label. Default is None.
365 y_label : string or None, optional.
366 y-axis label. Default is None.
367 title : string or None, optional.
368 plot title. Default is None.
369 show_legend : Boolean, optional.
370 controls the drawing of the legend. Default is True.
371 axis : str, optional
372 whether or not to autoscale the axis. Default is 'tight'
373 ax : :class:`matplotlib.axes.AxesSubplot` object or None, optional.
374 axes to draw on. Default is None (creates a new figure)
375 \*args, \*\*kwargs : passed to pylab.plot
376
377 """
378 if ax is None:
379 ax = plt.gca()
380
381 my_plot = ax.plot(x, y, *args, **kwargs)
382
383 if x_label is not None:
384 ax.set_xlabel(x_label)
385
386 if y_label is not None:
387 ax.set_ylabel(y_label)
388
389 if title is not None:
390 ax.set_title(title)
391
392 if show_legend:
393 # only show legend if they provide a label
394 if 'label' in kwargs:
395 ax.legend()
396
397 if axis is not None:
398 ax.autoscale(True, 'x', True)
399 ax.autoscale(True, 'y', False)
400
401 if plt.isinteractive():
402 plt.draw()
403
404 return my_plot
405
406
407 def plot_polar(theta: NumberLike, r: NumberLike,
408 x_label: str | None = None, y_label: str | None = None,
409 title: str | None = None, show_legend: bool = True,
410 axis_equal: bool = False, ax: plt.Axes | None = None,
411 *args, **kwargs):
412 r"""
413 Plot polar data on a polar plot and optionally label axes.
414
415 Parameters
416 ----------
417 theta : array-like
418 angular data to plot
419 r : array-like
420 radial data to plot
421 x_label : string or None, optional
422 x-axis label. Default is None.
423 y_label : string or None, optional.
424 y-axis label. Default is None
425 title : string or None, optional.
426 plot title. Default is None.
427 show_legend : Boolean, optional.
428 controls the drawing of the legend. Default is True.
429 ax : :class:`matplotlib.axes.AxesSubplot` object or None.
430 axes to draw on. Default is None (creates a new figure).
431 \*args, \*\*kwargs : passed to pylab.plot
432
433 See Also
434 --------
435 plot_rectangular : plots rectangular data
436 plot_complex_rectangular : plot complex data on complex plane
437 plot_polar : plot polar data
438 plot_complex_polar : plot complex data on polar plane
439 plot_smith : plot complex data on smith chart
440
441 """
442 if ax is None:
443 # no Axes passed
444 # if an existing (polar) plot is already present, grab and use its Axes
445 # otherwise, create a new polar plot and use that Axes
446 if not plt.get_fignums() or not plt.gcf().axes or plt.gca().name != 'polar':
447 ax = plt.figure().add_subplot(projection='polar')
448 else:
449 ax = plt.gca()
450 else:
451 if ax.name != 'polar':
452 # The projection of an existing axes can't be changed,
453 # since specifying a projection when creating an axes determines the
454 # axes class you get, which is different for each projection type.
455 # So, passing a axe projection not polar is probably undesired
456 warnings.warn(
457 f"Projection of the Axes passed as `ax` is not 'polar' but is {ax.name}." +
458 "See Matplotlib documentation to create a polar plot or call this function without the `ax` parameter."
459 , stacklevel=2
460 )
461
462 ax.plot(theta, r, *args, **kwargs)
463
464 if x_label is not None:
465 ax.set_xlabel(x_label)
466
467 if y_label is not None:
468 ax.set_ylabel(y_label)
469
470 if title is not None:
471 ax.set_title(title)
472
473 if show_legend:
474 # only show legend if they provide a label
475 if 'label' in kwargs:
476 ax.legend()
477
478 if axis_equal:
479 ax.axis('equal')
480
481 if plt.isinteractive():
482 plt.draw()
483
484
485 def plot_complex_rectangular(z: NumberLike,
486 x_label: str = 'Real', y_label: str = 'Imag',
487 title: str = 'Complex Plane', show_legend: bool = True,
488 axis: str = 'equal', ax: plt.Axes | None = None,
489 **kwargs):
490 r"""
491 Plot complex data on the complex plane.
492
493 Parameters
494 ----------
495 z : array-like, of complex data
496 data to plot
497 x_label : string, optional.
498 x-axis label. Default is 'Real'.
499 y_label : string, optional.
500 y-axis label. Default is 'Imag'.
501 title : string, optional.
502 plot title. Default is 'Complex Plane'
503 show_legend : Boolean, optional.
504 controls the drawing of the legend. Default is True.
505 ax : :class:`matplotlib.axes.AxesSubplot` object or None.
506 axes to draw on. Default is None (creates a new figure)
507 \*\*kwargs : passed to pylab.plot
508
509 See Also
510 --------
511 plot_rectangular : plots rectangular data
512 plot_complex_rectangular : plot complex data on complex plane
513 plot_polar : plot polar data
514 plot_complex_polar : plot complex data on polar plane
515 plot_smith : plot complex data on smith chart
516
517 """
518 x = np.real(z)
519 y = np.imag(z)
520 plot_rectangular(x=x, y=y, x_label=x_label, y_label=y_label,
521 title=title, show_legend=show_legend, axis=axis,
522 ax=ax, **kwargs)
523
524
525 def plot_complex_polar(z: NumberLike,
526 x_label: str | None = None, y_label: str | None = None,
527 title: str | None = None, show_legend: bool = True,
528 axis_equal: bool = False, ax: plt.Axes | None = None,
529 **kwargs):
530 r"""
531 Plot complex data in polar format.
532
533 Parameters
534 ----------
535 z : array-like, of complex data
536 data to plot
537 x_label : string or None, optional
538 x-axis label. Default is None.
539 y_label : string or None, optional.
540 y-axis label. Default is None
541 title : string or None, optional.
542 plot title. Default is None.
543 show_legend : Boolean, optional.
544 controls the drawing of the legend. Default is True.
545 ax : :class:`matplotlib.axes.AxesSubplot` object or None.
546 axes to draw on. Default is None (creates a new figure).
547 \*\*kwargs : passed to pylab.plot
548
549 See Also
550 --------
551 plot_rectangular : plots rectangular data
552 plot_complex_rectangular : plot complex data on complex plane
553 plot_polar : plot polar data
554 plot_complex_polar : plot complex data on polar plane
555 plot_smith : plot complex data on smith chart
556 """
557 theta = np.angle(z)
558 r = np.abs(z)
559 plot_polar(theta=theta, r=r, x_label=x_label, y_label=y_label,
560 title=title, show_legend=show_legend, axis_equal=axis_equal,
561 ax=ax, **kwargs)
562
563
564 def plot_smith(s: NumberLike, smith_r: float = 1, chart_type: str = 'z',
565 x_label: str = 'Real', y_label: str = 'Imaginary', title: str = 'Complex Plane',
566 show_legend: bool = True, axis: str = 'equal', ax: plt.Axes | None = None,
567 force_chart: bool = False, draw_vswr: list | bool | None = None, draw_labels: bool = False,
568 **kwargs):
569 r"""
570 Plot complex data on smith chart.
571
572 Parameters
573 ------------
574 s : complex array-like
575 reflection-coefficient-like data to plot
576 smith_r : number
577 radius of smith chart
578 chart_type : str in ['z','y']
579 Contour type for chart.
580 * *'z'* : lines of constant impedance
581 * *'y'* : lines of constant admittance
582 x_label : string, optional.
583 x-axis label. Default is 'Real'.
584 y_label : string, optional.
585 y-axis label. Default is 'Imaginary'
586 title : string, optional.
587 plot title, Default is 'Complex Plane'.
588 show_legend : Boolean, optional.
589 controls the drawing of the legend. Default is True.
590 axis_equal: Boolean, optional.
591 sets axis to be equal increments. Default is 'equal'.
592 ax : :class:`matplotlib.axes.AxesSubplot` object or None.
593 axes to draw on. Default is None (creates a new figure).
594 force_chart : Boolean, optional.
595 forces the re-drawing of smith chart. Default is False.
596 draw_vswr : list of numbers, Boolean or None, optional
597 draw VSWR circles. If True, default values are used.
598 Default is None.
599 draw_labels : Boolean
600 annotate chart with impedance values
601 \*\*kwargs : passed to pylab.plot
602
603 See Also
604 ----------
605 plot_rectangular : plots rectangular data
606 plot_complex_rectangular : plot complex data on complex plane
607 plot_polar : plot polar data
608 plot_complex_polar : plot complex data on polar plane
609 plot_smith : plot complex data on smith chart
610 """
611
612 if ax is None:
613 ax = plt.gca()
614
615 # test if smith chart is already drawn
616 if not force_chart:
617 if len(ax.patches) == 0:
618 smith(ax=ax, smithR = smith_r, chart_type=chart_type, draw_vswr=draw_vswr, draw_labels=draw_labels)
619
620 plot_complex_rectangular(s, x_label=x_label, y_label=y_label,
621 title=title, show_legend=show_legend, axis=axis,
622 ax=ax, **kwargs)
623
624 ax.axis(smith_r*np.array([-1.1, 1.1, -1.1, 1.1]))
625 if plt.isinteractive():
626 plt.draw()
627
628
629 def subplot_params(ntwk: Network, param: str = 's', proj: str = 'db',
630 size_per_port: int = 4, newfig: bool = True,
631 add_titles: bool = True, keep_it_tight: bool = True,
632 subplot_kw: dict = None,
633 **kwargs):
634 """
635 Plot all networks parameters individually on subplots.
636
637 Parameters
638 ----------
639 ntwk : :class:`~skrf.network.Network`
640 Network to get data from.
641 param : str, optional
642 Parameter to plot, by default 's'
643 proj : str, optional
644 Projection type, by default 'db'
645 size_per_port : int, optional
646 by default 4
647 newfig : bool, optional
648 by default True
649 add_titles : bool, optional
650 by default True
651 keep_it_tight : bool, optional
652 by default True
653 subplot_kw : dict, optional
654 by default {}
655
656 Returns
657 -------
658 f : :class:`matplotlib.pyplot.Figure`
659 Matplotlib Figure
660 ax : :class:`matplotlib.pyplot.Axes`
661 Matplotlib Axes
662
663 """
664 subplot_kw = subplot_kw if subplot_kw else {}
665 if newfig:
666 f,axs= plt.subplots(ntwk.nports,ntwk.nports,
667 figsize =(size_per_port*ntwk.nports,
668 size_per_port*ntwk.nports ),
669 **subplot_kw)
670 else:
671 f = plt.gcf()
672 axs = np.array(f.get_axes())
673
674 for ports,ax in zip(ntwk.port_tuples, axs.flatten()):
675 plot_func = ntwk.__getattribute__(f'plot_{param}_{proj}')
676 plot_func(m=ports[0], n=ports[1], ax=ax, **kwargs)
677 if add_titles:
678 ax.set_title(f"{param.upper()}{ntwk._fmt_trace_name(ports[0], ports[1])}")
679 if keep_it_tight:
680 plt.tight_layout()
681 return f, axs
682
683
684 def shade_bands(edges: NumberLike, y_range: tuple | None = None,
685 cmap: str = 'prism', **kwargs):
686 r"""
687 Shades frequency bands.
688
689 When plotting data over a set of frequency bands it is nice to
690 have each band visually separated from the other. The kwarg `alpha`
691 is useful.
692
693 Parameters
694 ----------
695 edges : array-like
696 x-values separating regions of a given shade
697 y_range : tuple or None, optional.
698 y-values to shade in. Default is None.
699 cmap : str, optional.
700 see matplotlib.cm or matplotlib.colormaps for acceptable values.
701 Default is 'prism'.
702 \*\*kwargs : key word arguments
703 passed to `matplotlib.fill_between`
704
705 Examples
706 --------
707 >>> rf.shade_bands([325,500,750,1100], alpha=.2)
708 """
709 cmap = plt.cm.get_cmap(cmap)
710 if not isinstance(y_range, (tuple, list)) or (len(y_range) != 2):
711 y_range=plt.gca().get_ylim()
712 axis = plt.axis()
713 for k in range(len(edges)-1):
714 plt.fill_between(
715 [edges[k],edges[k+1]],
716 y_range[0], y_range[1],
717 color = cmap(1.0*k/len(edges)),
718 **kwargs)
719 plt.axis(axis)
720
721
722 def save_all_figs(dir: str = './', format: None | list[str] = None,
723 replace_spaces: bool = True, echo: bool = True):
724 """
725 Save all open Figures to disk.
726
727 Parameters
728 ----------
729 dir : string, optional.
730 path to save figures into. Default is './'
731 format : None or list of strings, optional.
732 the types of formats to save figures as. The elements of this
733 list are passed to :func:`matplotlib.pyplot.savefig`. This is a list so that
734 you can save each figure in multiple formats. Default is None.
735 replace_spaces : bool, optional
736 default is True.
737 echo : bool, optional.
738 True prints filenames as they are saved. Default is True.
739 """
740 if dir[-1] != '/':
741 dir = dir + '/'
742 for fignum in plt.get_fignums():
743 fileName = plt.figure(fignum).get_axes()[0].get_title()
744 if replace_spaces:
745 fileName = fileName.replace(' ','_')
746 if fileName == '':
747 fileName = 'unnamedPlot'
748 if format is None:
749 plt.savefig(dir+fileName)
750 if echo:
751 print(dir+fileName)
752 else:
753 for fmt in format:
754 plt.savefig(dir+fileName+'.'+fmt, format=fmt)
755 if echo:
756 print(dir+fileName+'.'+fmt)
757 saf = save_all_figs
758
759 @axes_kwarg
760 def add_markers_to_lines(ax: plt.Axes = None,
761 marker_list: list = None,
762 markevery: int = 10):
763 """
764 Add markers to existing lings on a plot.
765
766 Convenient if you have already have a plot made, but then
767 need to add markers afterwards, so that it can be interpreted in
768 black and white. The markevery argument makes the markers less
769 frequent than the data, which is generally what you want.
770
771 Parameters
772 ----------
773 ax : matplotlib.Axes or None, optional
774 axis which to add markers to.
775 Default is current axe gca()
776 marker_list : list of string, optional
777 list of marker characters. Default is ['o', 'D', 's', '+', 'x'].
778 see matplotlib.plot help for possible marker characters
779 markevery : int, optional.
780 markevery number of points with a marker.
781 Default is 10.
782
783 """
784 marker_list = marker_list if marker_list else ['o', 'D', 's', '+', 'x']
785
786 lines = ax.get_lines()
787 if len(lines) > len (marker_list ):
788 marker_list *= 3
789 [k[0].set_marker(k[1]) for k in zip(lines, marker_list)]
790 [line.set_markevery(markevery) for line in lines]
791
792 @axes_kwarg
793 def legend_off(ax: plt.Axes = None):
794 """
795 Turn off the legend for a given axes.
796
797 If no axes is given then it will use current axes.
798
799 Parameters
800 ----------
801 ax : matplotlib.Axes or None, optional
802 axis to operate on.
803 Default is None for current axe gca()
804 """
805 ax.legend_.set_visible(0)
806
807 @axes_kwarg
808 def scrape_legend(n: int | None = None,
809 ax:plt.Axes = None):
810 """
811 Scrape a legend with redundant labels.
812
813 Given a legend of m entries of n groups, this will remove all but
814 every m/nth entry. This is used when you plot many lines representing
815 the same thing, and only want one label entry in the legend for the
816 whole ensemble of lines.
817
818 Parameters
819 ----------
820 n : int or None, optional.
821 Default is None.
822 ax : matplotlib.Axes or None, optional
823 axis to operate on.
824 Default is None for current axe gca()
825 """
826
827 handles, labels = ax.get_legend_handles_labels()
828
829 if n is None:
830 n =len ( set(labels))
831
832 if n>len(handles):
833 raise ValueError('number of entries is too large')
834
835 k_list = [int(k) for k in np.linspace(0,len(handles)-1,n)]
836 ax.legend([handles[k] for k in k_list], [labels[k] for k in k_list])
837
838
839 def func_on_all_figs(func: Callable, *args, **kwargs):
840 r"""
841 Run a function after making all open figures current.
842
843 Useful if you need to change the properties of many open figures
844 at once, like turn off the grid.
845
846 Parameters
847 ----------
848 func : function
849 function to call
850 \*args, \*\*kwargs : passed to func
851
852 Examples
853 --------
854 >>> rf.func_on_all_figs(grid, alpha=.3)
855 """
856 for fig_n in plt.get_fignums():
857 fig = plt.figure(fig_n)
858 for ax_n in fig.axes:
859 fig.add_axes(ax_n) # trick to make axes current
860 func(*args, **kwargs)
861 plt.draw()
862
863 foaf = func_on_all_figs
864
865
866 def plot_vector(a: complex, off: complex = 0+0j, **kwargs):
867 """
868 Plot a 2d vector.
869
870 Parameters
871 ----------
872 a : complex
873 complex coordinates (real for X, imag for Y) of the arrow location.
874 off : complex, optional
875 complex direction (real for U, imag for V) components
876 of the arrow vectors, by default 0+0j
877
878 Returns
879 -------
880 quiver : matplotlib.pyplot.quiver
881 """
882 return quiver(off.real, off.imag, a.real, a.imag, scale_units='xy',
883 angles='xy', scale=1, **kwargs)
884
885
886 def colors() -> list[str]:
887 """
888 Return the list of colors of the rcParams color cycle.
889
890 Returns
891 -------
892 colors : List[str]
893 """
894 return [c['color'] for c in rcParams['axes.prop_cycle']]
895
896
897 ## specific plotting functions
898 def plot(netw: Network, *args, **kw):
899 """
900 Plot something vs frequency
901 """
902 return netw.frequency.plot(*args, **kw)
903
904
905 def plot_passivity(netw: Network, port=None, label_prefix=None, **kwargs):
906 """
907 Plot dB(diag(passivity metric)) vs frequency.
908
909 Note
910 ----
911 This plot does not completely capture the passivity metric, which
912 is a test for `unitary-ness` of the s-matrix. However, it may
913 be used to display a measure of power dissipated in a network.
914
915 See Also
916 --------
917 passivity
918 """
919 name = '' if netw.name is None else netw.name
920
921 if port is None:
922 ports = range(netw.nports)
923 else:
924 ports = [port]
925 for k in ports:
926 if label_prefix is None:
927 label = name + ', port %i' % (k + 1)
928 else:
929 label = label_prefix + ', port %i' % (k + 1)
930 netw.frequency.plot(mf.complex_2_db(netw.passivity[:, k, k]),
931 label=label,
932 **kwargs)
933
934 plt.legend()
935 if plt.isinteractive():
936 plt.draw()
937
938
939 def plot_reciprocity(netw: Network, db=False, *args, **kwargs):
940 """
941 Plot reciprocity metric.
942
943 See Also
944 --------
945 reciprocity
946 """
947 for m in range(netw.nports):
948 for n in range(netw.nports):
949 if m > n:
950 if 'label' not in kwargs.keys():
951 kwargs['label'] = f"ports {netw._fmt_trace_name(m, n)}"
952 y = netw.reciprocity[:, m, n].flatten()
953 y = mf.complex_2_db(y) if db else np.abs(y)
954 netw.frequency.plot(y, *args, **kwargs)
955
956 plt.legend()
957 if plt.isinteractive():
958 plt.draw()
959
960
961 def plot_reciprocity2(netw: Network, db=False, *args, **kwargs):
962 """
963 Plot reciprocity metric #2.
964
965 This is distance of the determinant of the wave-cascading matrix
966 from unity.
967
968 .. math::
969
970 abs(1 - S/S^T )
971
972
973
974 See Also
975 --------
976 reciprocity
977 """
978 for m in range(netw.nports):
979 for n in range(netw.nports):
980 if m > n:
981 if 'label' not in kwargs.keys():
982 kwargs['label'] = f"ports {netw._fmt_trace_name(m, n)}"
983 y = netw.reciprocity2[:, m, n].flatten()
984 if db:
985 y = mf.complex_2_db(y)
986 netw.frequency.plot(y, *args, **kwargs)
987
988 plt.legend()
989 if plt.isinteractive():
990 plt.draw()
991
992
993 def plot_s_db_time(netw: Network, *args, window: str | float | tuple[str, float]=('kaiser', 6),
994 normalize: bool = True, center_to_dc: bool = None, **kwargs):
995 return netw.windowed(window, normalize, center_to_dc).plot_s_time_db(*args,**kwargs)
996
997
998 # plotting
999 def plot_s_smith(netw: Network, m=None, n=None,r=1, ax=None, show_legend=True,\
1000 chart_type='z', draw_labels=False, label_axes=False, draw_vswr=None, *args,**kwargs):
1001 r"""
1002 Plots the scattering parameter on a smith chart.
1003
1004 Plots indices `m`, `n`, where `m` and `n` can be integers or
1005 lists of integers.
1006
1007
1008 Parameters
1009 ----------
1010 m : int, optional
1011 first index
1012 n : int, optional
1013 second index
1014 ax : matplotlib.Axes object, optional
1015 axes to plot on. in case you want to update an existing
1016 plot.
1017 show_legend : boolean, optional
1018 to turn legend show legend of not, optional
1019 chart_type : ['z','y']
1020 draw impedance or admittance contours
1021 draw_labels : Boolean
1022 annotate chart with impedance values
1023 label_axes : Boolean
1024 Label axis with titles `Real` and `Imaginary`
1025 border : Boolean
1026 draw rectangular border around image with ticks
1027 draw_vswr : list of numbers, Boolean or None
1028 draw VSWR circles. If True, default values are used.
1029
1030 \*args : arguments, optional
1031 passed to the matplotlib.plot command
1032 \*\*kwargs : keyword arguments, optional
1033 passed to the matplotlib.plot command
1034
1035
1036 See Also
1037 --------
1038 plot_vs_frequency_generic - generic plotting function
1039 smith - draws a smith chart
1040
1041 Examples
1042 --------
1043 >>> myntwk.plot_s_smith()
1044 >>> myntwk.plot_s_smith(m=0,n=1,color='b', marker='x')
1045 """
1046 # TODO: prevent this from re-drawing smith chart if one already
1047 # exists on current set of axes
1048
1049 # get current axis if user doesn't supply and axis
1050 if ax is None:
1051 ax = plt.gca()
1052
1053
1054 if m is None:
1055 M = range(netw.number_of_ports)
1056 else:
1057 M = [m]
1058 if n is None:
1059 N = range(netw.number_of_ports)
1060 else:
1061 N = [n]
1062
1063 if 'label' not in kwargs.keys():
1064 generate_label=True
1065 else:
1066 generate_label=False
1067
1068 for m in M:
1069 for n in N:
1070 # set the legend label for this trace to the networks name if it
1071 # exists, and they didn't pass a name key in the kwargs
1072 if generate_label:
1073 kwargs['label'] = _get_label_str(netw, "S", m, n)
1074
1075 # plot the desired attribute vs frequency
1076 if len (ax.patches) == 0:
1077 smith(ax=ax, smithR = r, chart_type=chart_type, draw_labels=draw_labels, draw_vswr=draw_vswr)
1078 ax.plot(netw.s[:,m,n].real, netw.s[:,m,n].imag, *args,**kwargs)
1079
1080 #draw legend
1081 if show_legend:
1082 ax.legend()
1083 ax.axis(np.array([-1.1,1.1,-1.1,1.1])*r)
1084
1085 if label_axes:
1086 ax.set_xlabel('Real')
1087 ax.set_ylabel('Imaginary')
1088
1089
1090 def plot_it_all(netw: Network, *args, **kwargs):
1091 r"""
1092 Plot dB, deg, smith, and complex in subplots.
1093
1094 Plots the magnitude in dB in subplot 1, the phase in degrees in
1095 subplot 2, a smith chart in subplot 3, and a complex plot in
1096 subplot 4.
1097
1098 Parameters
1099 ----------
1100 \*args : arguments, optional
1101 passed to the matplotlib.plot command
1102 \*\*kwargs : keyword arguments, optional
1103 passed to the matplotlib.plot command
1104
1105 See Also
1106 --------
1107 plot_s_db - plot magnitude (in dB) of s-parameters vs frequency
1108 plot_s_deg - plot phase of s-parameters (in degrees) vs frequency
1109 plot_s_smith - plot complex s-parameters on smith chart
1110 plot_s_complex - plot complex s-parameters in the complex plane
1111
1112 Examples
1113 --------
1114 >>> from skrf.data import ring_slot
1115 >>> ring_slot.plot_it_all()
1116 """
1117 plt.clf()
1118 plt.subplot(221)
1119 netw.plot_s_db(*args, **kwargs)
1120 plt.subplot(222)
1121 netw.plot_s_deg(*args, **kwargs)
1122 plt.subplot(223)
1123 netw.plot_s_smith(*args, **kwargs)
1124 plt.subplot(224)
1125 netw.plot_s_complex(*args, **kwargs)
1126
1127
1128 def stylely(rc_dict: dict = None, style_file: str = 'skrf.mplstyle'):
1129 """
1130 Loads the rc-params from the specified file (file must be located in skrf/data).
1131
1132 Parameters
1133 ----------
1134 rc_dict : dict, optional
1135 rc dict passed to :func:`matplotlib.rc`, by default {}
1136 style_file : str, optional
1137 style file, by default 'skrf.mplstyle'
1138 """
1139 from .data import pwd # delayed to solve circular import
1140 rc_dict = rc_dict if rc_dict else {}
1141
1142 mpl.style.use(os.path.join(pwd, style_file))
1143 mpl.rc(rc_dict)
1144
1145
1146 # Network Set Plotting Commands
1147 def animate(self: NetworkSet, attr: str = 's_deg', ylims: tuple = (-5, 5),
1148 xlims: tuple | None = None, show: bool = True,
1149 savefigs: bool = False, dir_: str = '.', *args, **kwargs):
1150 r"""
1151 Animate a property of the networkset.
1152
1153 This loops through all elements in the NetworkSet and calls
1154 a plotting attribute (ie Network.plot_`attr`), with given \*args
1155 and \*\*kwargs.
1156
1157 Parameters
1158 ----------
1159 attr : str, optional
1160 plotting property of a Network (ie 's_db', 's_deg', etc)
1161 Default is 's_deg'
1162 ylims : tuple, optional
1163 passed to ylim. needed to have consistent y-limits across frames.
1164 Default is (-5 ,5).
1165 xlims : tuple or None, optional.
1166 passed to xlim. Default is None.
1167 show : bool, optional
1168 show each frame as its animated. Default is True.
1169 savefigs : bool, optional
1170 save each frame as a png. Default is False.
1171
1172 \*args, \*\*kwargs :
1173 passed to the Network plotting function
1174
1175 Note
1176 ----
1177 using `label=None` will speed up animation significantly,
1178 because it prevents the legend from drawing
1179
1180 to create video paste this:
1181
1182 !avconv -r 10 -i out_%5d.png -vcodec huffyuv out.avi
1183
1184 or (depending on your ffmpeg version)
1185
1186 !ffmpeg -r 10 -i out_%5d.png -vcodec huffyuv out.avi
1187
1188 Examples
1189 --------
1190 >>> ns.animate('s_deg', ylims=(-5,5), label=None)
1191
1192 """
1193 was_interactive = plt.isinteractive()
1194 plt.ioff()
1195
1196 for idx, k in enumerate(self):
1197 plt.clf()
1198 if 'time' in attr:
1199 tmp_ntwk = k.windowed()
1200 tmp_ntwk.__getattribute__('plot_' + attr)(*args, **kwargs)
1201 else:
1202 k.__getattribute__('plot_' + attr)(*args, **kwargs)
1203 if ylims is not None:
1204 plt.ylim(ylims)
1205 if xlims is not None:
1206 plt.xlim(xlims)
1207 # rf.legend_off()
1208 plt.draw()
1209 if show:
1210 plt.show()
1211 if savefigs:
1212 fname = os.path.join(dir_, 'out_%.5i' % idx + '.png')
1213 plt.savefig(fname)
1214
1215 if savefigs:
1216 print('\n\n')
1217 if was_interactive:
1218 plt.ion()
1219
1220
1221 #------------------------------
1222 #
1223 # NetworkSet plotting functions
1224 #
1225 #------------------------------
1226
1227 @axes_kwarg
1228 def plot_uncertainty_bounds_component(
1229 self: NetworkSet, attribute: PrimaryPropertiesT,
1230 m: int | None = None, n: int | None = None, *,
1231 type: str = 'shade', n_deviations: int = 3,
1232 alpha: float = .3, color_error: str | None = None,
1233 markevery_error: int = 20, ax: plt.Axes = None,
1234 ppf: bool = None, kwargs_error: dict = None,
1235 **kwargs):
1236 r"""
1237 Plot mean value of a NetworkSet with +/- uncertainty bounds in an Network's attribute.
1238
1239 This is designed to represent uncertainty in a scalar component of the s-parameter.
1240 for example plotting the uncertainty in the magnitude would be expressed by,
1241
1242 .. math::
1243
1244 mean(|s|) \pm std(|s|)
1245
1246 The order of mean and abs is important.
1247
1248
1249 Parameters
1250 ----------
1251 attribute : str
1252 attribute of Network type to analyze
1253 m : int or None
1254 first index of attribute matrix. Default is None (all)
1255 n : int or None
1256 second index of attribute matrix. Default is None (all)
1257 type : str
1258 ['shade' | 'bar'], type of plot to draw
1259 n_deviations : int
1260 number of std deviations to plot as bounds
1261 alpha : float
1262 passed to matplotlib.fill_between() command. [number, 0-1]
1263 color_error : str
1264 color of the +- std dev fill shading. Default is None.
1265 markevery_error : float
1266 tbd
1267 type : str
1268 if type=='bar', this controls frequency of error bars
1269 ax : matplotlib axes object
1270 Axes to plot on. Default is None.
1271 ppf : function
1272 post processing function. a function applied to the
1273 upper and lower bounds. Default is None
1274 kwargs_error : dict
1275 dictionary of kwargs to pass to the fill_between or
1276 errorbar plot command depending on value of type.
1277 \*\*kwargs :
1278 passed to Network.plot_s_re command used to plot mean response
1279
1280 Note
1281 ----
1282 For phase uncertainty you probably want s_deg_unwrap, or
1283 similar. uncertainty for wrapped phase blows up at +-pi.
1284
1285 """
1286
1287 kwargs_error = kwargs_error if kwargs_error else {}
1288
1289 if m is None:
1290 M = range(self[0].number_of_ports)
1291 else:
1292 M = [m]
1293 if n is None:
1294 N = range(self[0].number_of_ports)
1295 else:
1296 N = [n]
1297
1298 for m in M:
1299 for n in N:
1300
1301 plot_attribute = attribute
1302
1303 ntwk_mean = self.__getattribute__('mean_'+attribute)
1304 ntwk_std = self.__getattribute__('std_'+attribute)
1305 ntwk_std.s = n_deviations * ntwk_std.s
1306
1307 upper_bound = (ntwk_mean.s[:, m, n] + ntwk_std.s[:, m, n]).squeeze()
1308 lower_bound = (ntwk_mean.s[:, m, n] - ntwk_std.s[:, m, n]).squeeze()
1309
1310 if ppf is not None:
1311 if type == 'bar':
1312 raise NotImplementedError('the \'ppf\' options don\'t work correctly with the bar-type error plots')
1313 ntwk_mean.s = ppf(ntwk_mean.s)
1314 upper_bound = ppf(upper_bound)
1315 lower_bound = ppf(lower_bound)
1316 lower_bound[np.isnan(lower_bound)] = min(lower_bound)
1317 if ppf in [mf.magnitude_2_db, mf.mag_2_db]: # fix of wrong ylabels due to usage of ppf for *_db plots
1318 if attribute == 's_mag':
1319 plot_attribute = 's_db'
1320 elif attribute == 's_time_mag':
1321 plot_attribute = 's_time_db'
1322
1323 if type == 'shade':
1324 ntwk_mean.plot_s_re(ax=ax, m=m, n=n, **kwargs)
1325 if color_error is None:
1326 color_error = ax.get_lines()[-1].get_color()
1327 ax.fill_between(ntwk_mean.frequency.f,
1328 lower_bound.real, upper_bound.real, alpha=alpha, color=color_error,
1329 **kwargs_error)
1330 # ax.plot(ntwk_mean.frequency.f_scaled, ntwk_mean.s[:,m,n],*args,**kwargs)
1331
1332 elif type == 'bar':
1333 ntwk_mean.plot_s_re(ax=ax, m=m, n=n, **kwargs)
1334 if color_error is None:
1335 color_error = ax.get_lines()[-1].get_color()
1336 ax.errorbar(ntwk_mean.frequency.f[::markevery_error],
1337 ntwk_mean.s_re[:, m, n].squeeze()[::markevery_error],
1338 yerr=ntwk_std.s_mag[:, m, n].squeeze()[::markevery_error],
1339 color=color_error, **kwargs_error)
1340
1341 else:
1342 raise(ValueError('incorrect plot type'))
1343
1344 ax.set_ylabel(self[0].Y_LABEL_DICT.get(plot_attribute[2:], '')) # use only the function of the attribute
1345 scale_frequency_ticks(ax, ntwk_mean.frequency.unit)
1346 ax.axis('tight')
1347
1348 @axes_kwarg
1349 def plot_minmax_bounds_component(self: NetworkSet, attribute: PrimaryPropertiesT, m: int = 0, n: int = 0,
1350 *, type: str = 'shade',
1351 alpha: float = .3, color_error: str | None = None,
1352 markevery_error: int = 20, ax: plt.Axes = None,
1353 ppf: bool = None, kwargs_error: dict = None,
1354 **kwargs):
1355 r"""
1356 Plots mean value of the NetworkSet with minimum and maximum bounds in an Network's attribute.
1357
1358 This is designed to represent min/max in a scalar component of the s-parameter. For example
1359 plotting the min/max in the magnitude would be expressed by
1360
1361 .. math::
1362
1363 min(|s|)
1364
1365 mean(|s|)
1366
1367 max(|s|)
1368
1369 The order of mean and abs is important.
1370
1371 Parameters
1372 ----------
1373 attribute : str
1374 attribute of Network type to analyze
1375 m : int
1376 first index of attribute matrix
1377 n : int
1378 second index of attribute matrix
1379 type : str
1380 ['shade' | 'bar'], type of plot to draw
1381 alpha : float
1382 passed to matplotlib.fill_between() command. [number, 0-1]
1383 color_error : str
1384 color of the min/max fill shading. Default is None.
1385 markevery_error : float
1386 tbd
1387 type : str
1388 if type=='bar', this controls frequency of error bars
1389 ax : matplotlib axes object
1390 Axes to plot on. Default is None.
1391 ppf : function
1392 post processing function. a function applied to the
1393 upper and lower bounds. Default is None
1394 kwargs_error : dict
1395 dictionary of kwargs to pass to the fill_between or
1396 errorbar plot command depending on value of type.
1397 \*\*kwargs :
1398 passed to Network.plot_s_re command used to plot mean response
1399
1400 Note
1401 ----
1402 For phase uncertainty you probably want s_deg_unwrap, or
1403 similar. Uncertainty for wrapped phase blows up at +-pi.
1404
1405 """
1406
1407 kwargs_error = kwargs_error if kwargs_error else {}
1408
1409 ntwk_mean = self.__getattribute__('mean_'+attribute)
1410 ntwk_std = self.__getattribute__('std_'+attribute)
1411
1412 lower_bound = self.__getattribute__('min_'+attribute).s_re[:,m,n].squeeze()
1413 upper_bound = self.__getattribute__('max_'+attribute).s_re[:,m,n].squeeze()
1414
1415 if ppf is not None:
1416 if type =='bar':
1417 raise NotImplementedError('the \'ppf\' options don\'t work correctly with the bar-type error plots')
1418 ntwk_mean.s = ppf(ntwk_mean.s)
1419 upper_bound = ppf(upper_bound)
1420 lower_bound = ppf(lower_bound)
1421 lower_bound[np.isnan(lower_bound)]=min(lower_bound)
1422 if ppf in [mf.magnitude_2_db, mf.mag_2_db]: # quickfix of wrong ylabels due to usage of ppf for *_db plots
1423 if attribute == 's_mag':
1424 attribute = 's_db'
1425 elif attribute == 's_time_mag':
1426 attribute = 's_time_db'
1427
1428 if type == 'shade':
1429 ntwk_mean.plot_s_re(ax=ax,m=m,n=n, **kwargs)
1430 if color_error is None:
1431 color_error = ax.get_lines()[-1].get_color()
1432 ax.fill_between(ntwk_mean.frequency.f,
1433 lower_bound, upper_bound, alpha=alpha, color=color_error,
1434 **kwargs_error)
1435 #ax.plot(ntwk_mean.frequency.f_scaled,ntwk_mean.s[:,m,n],*args,**kwargs)
1436 elif type =='bar':
1437 raise (NotImplementedError)
1438 ntwk_mean.plot_s_re(ax=ax, m=m, n=n, **kwargs)
1439 if color_error is None:
1440 color_error = ax.get_lines()[-1].get_color()
1441 ax.errorbar(ntwk_mean.frequency.f[::markevery_error],
1442 ntwk_mean.s_re[:,m,n].squeeze()[::markevery_error],
1443 yerr=ntwk_std.s_mag[:,m,n].squeeze()[::markevery_error],
1444 color=color_error,**kwargs_error)
1445
1446 else:
1447 raise(ValueError('incorrect plot type'))
1448
1449 ax.set_ylabel(self[0].Y_LABEL_DICT.get(attribute[2:], '')) # use only the function of the attribute
1450 scale_frequency_ticks(ax, ntwk_mean.frequency.unit)
1451 ax.axis('tight')
1452
1453 @axes_kwarg
1454 def plot_violin(self: NetworkSet, attribute: PrimaryPropertiesT, m: int = 0, n: int = 0,
1455 *, widths: float = None, showmeans: bool = True,
1456 showextrema: bool = True, showmedians: bool = False,
1457 quantiles = None, points: int = 100, bw_method = None,
1458 ax: plt.Axes = None, **kwargs
1459 ):
1460 r"""Plots the violin plot of the network set for the desired attribute.
1461
1462 A violin plot provides the distribution of the attribute at each frequency point, and optionally the
1463 extrema, mean, and median. The plot becomes cluttered quickly with many frequencies, so reducing the number
1464 with :meth:`NetworkSet.interpolate_frequency` is recommended.
1465
1466 Parameters
1467 ----------
1468 attribute : str
1469 attribute of Network type to analyze
1470 m : int
1471 first index of attribute matrix
1472 n : int
1473 second index of attribute matrix
1474 widths : float
1475 The maximum width of each violin in units of the positions axis.
1476 The default is 0.75 of the distance between the first two frequencies.
1477 showmeans : bool
1478 Whether to show the mean with a line.
1479 showextrema : bool
1480 Whether to show the extrema with a line.
1481 showmedians : bool
1482 Whether to show the median with a line.
1483 quantiles : ArrayLike
1484 If not None, set a list of floats in interval [0, 1] for each violin,
1485 which stands for the quantiles that will be rendered for that violin.
1486 points : int
1487 The number of points to evaluate each of the gaussian kernel density estimations at.
1488 bw_method : {'scott', 'silverman'} or float or callable, default: 'scott'
1489 _description_. Defaults to None.
1490 ax : matplotlib axes object
1491 Axes to plot on. Default is None.
1492 \*\*kwargs :
1493 passed to :meth:`matplotlib.pyplot.violinplot`
1494
1495 Note
1496 ----
1497 For phase plots you probably want s_deg_unwrap, or
1498 similar. Uncertainty for wrapped phase blows up at +-pi.
1499 """
1500
1501 freq = self.ntwk_set[0].f
1502
1503 # default widths to 3/4 distance between frequencies
1504 if not widths and len(freq) > 1:
1505 widths = (freq[1]-freq[0])*0.75
1506 elif not widths:
1507 widths = 0.5
1508
1509 data = np.array([getattr(p, attribute)[:,m,n] for p in self.ntwk_set])
1510
1511 ax.violinplot(data, freq, widths=widths, showmeans=showmeans, showextrema=showextrema,
1512 showmedians=showmedians, quantiles=quantiles, points=points, bw_method=bw_method, **kwargs)
1513
1514 ax.set_xlabel(f'Frequency ({self.ntwk_set[0].frequency.unit})')
1515 ax.set_ylabel(self[0].Y_LABEL_DICT.get(attribute[2:], '')) # use only the function of the attribute
1516 scale_frequency_ticks(ax, self.ntwk_set[0].frequency.unit)
1517 ax.axis('tight')
1518
1519 def plot_uncertainty_bounds_s_db(self: NetworkSet, *args, **kwargs):
1520 """
1521 Call ``plot_uncertainty_bounds(attribute='s_mag','ppf':mf.magnitude_2_db*args,**kwargs)``.
1522
1523 See plot_uncertainty_bounds for help.
1524
1525 """
1526 kwargs.update({'ppf':mf.magnitude_2_db})
1527 self.plot_uncertainty_bounds_component("s_mag", *args,**kwargs)
1528
1529 def plot_minmax_bounds_s_db(self: NetworkSet, *args, **kwargs):
1530 """
1531 Call ``plot_uncertainty_bounds(attribute= 's_mag','ppf':mf.magnitude_2_db*args,**kwargs)``.
1532
1533 See plot_uncertainty_bounds for help.
1534
1535 """
1536 kwargs.update({'ppf':mf.magnitude_2_db})
1537 self.plot_minmax_bounds_component("s_mag", *args,**kwargs)
1538
1539 def plot_minmax_bounds_s_db10(self: NetworkSet, *args, **kwargs):
1540 """
1541 Call ``plot_uncertainty_bounds(attribute= 's_mag','ppf':mf.magnitude_2_db*args,**kwargs)``.
1542
1543 see plot_uncertainty_bounds for help
1544
1545 """
1546 kwargs.update({'ppf':mf.mag_2_db10})
1547 self.plot_minmax_bounds_component("s_mag", *args,**kwargs)
1548
1549 def plot_uncertainty_bounds_s_time_db(self: NetworkSet, *args, **kwargs):
1550 """
1551 Call ``plot_uncertainty_bounds(attribute= 's_mag','ppf':mf.magnitude_2_db*args,**kwargs)``.
1552
1553 See plot_uncertainty_bounds for help.
1554
1555 """
1556 kwargs.update({'ppf':mf.magnitude_2_db})
1557 self.plot_uncertainty_bounds_component("s_time_mag", *args,**kwargs)
1558
1559 def plot_minmax_bounds_s_time_db(self: NetworkSet, *args, **kwargs):
1560 """
1561 Call ``plot_uncertainty_bounds(attribute= 's_mag','ppf':mf.magnitude_2_db*args,**kwargs)``.
1562
1563 See plot_uncertainty_bounds for help.
1564
1565 """
1566 kwargs.update({'ppf':mf.magnitude_2_db})
1567 self.plot_minmax_bounds_component("s_time_mag", *args, **kwargs)
1568
1569 def plot_uncertainty_decomposition(self: NetworkSet, m: int = 0, n: int = 0):
1570 """
1571 Plot the total and component-wise uncertainty.
1572
1573 Parameters
1574 ----------
1575 m : int
1576 first s-parameters index
1577 n :
1578 second s-parameter index
1579
1580 """
1581 if self.name is not None:
1582 plt.title(f"Uncertainty Decomposition: {self.name} $S_{{{self.ntwk_set[0]._fmt.trace_name(m,n)}}}$")
1583 self.std_s.plot_s_mag(label='Distance', m=m,n=n)
1584 self.std_s_re.plot_s_mag(label='Real', m=m,n=n)
1585 self.std_s_im.plot_s_mag(label='Imaginary', m=m,n=n)
1586 self.std_s_mag.plot_s_mag(label='Magnitude', m=m,n=n)
1587 self.std_s_arcl.plot_s_mag(label='Arc-length', m=m,n=n)
1588
1589 def plot_logsigma(self: NetworkSet, label_axis: bool = True, *args,**kwargs):
1590 r"""
1591 Plot the uncertainty for the set in units of log-sigma.
1592
1593 Log-sigma is the complex standard deviation, plotted in units
1594 of dB's.
1595
1596 Parameters
1597 ----------
1598 label_axis : bool, optional
1599 Default is True.
1600 \*args, \*\*kwargs : arguments
1601 passed to self.std_s.plot_s_db()
1602 """
1603 self.std_s.plot_s_db(*args,**kwargs)
1604 if label_axis:
1605 plt.ylabel('Standard Deviation(dB)')
1606
1607
1608 def signature(self: NetworkSet, m: int = 0, n: int = 0, component: str = 's_mag',
1609 vmax: Number | None = None, vs_time: bool = False,
1610 cbar_label: str | None = None,
1611 *args, **kwargs):
1612 r"""
1613 Visualization of a NetworkSet.
1614
1615 Creates a colored image representing the some component
1616 of each Network in the NetworkSet, vs frequency.
1617
1618 Parameters
1619 ------------
1620 m : int, optional
1621 first s-parameters index. Default is 0.
1622 n : int, optional
1623 second s-parameter index. Default is 0.
1624 component : ['s_mag','s_db','s_deg' ..]
1625 scalar component of Network to visualize. should
1626 be a property of the Network object.
1627 vmax : number or None.
1628 sets upper limit of colorbar, if None, will be set to
1629 3*mean of the magnitude of the complex difference.
1630 Default is None.
1631 vs_time: Boolean, optional.
1632 if True, then we assume each Network.name was made with
1633 rf.now_string, and we make the y-axis a datetime axis.
1634 Default is False.
1635 cbar_label: String or None, optional
1636 label for the colorbar. Default is None
1637 \*args,\*\*kw : arguments, keyword arguments
1638 passed to :func:`~pylab.imshow`
1639 """
1640
1641 mat = np.array([self[k].__getattribute__(component)[:, m, n] \
1642 for k in range(len(self))])
1643
1644 # if vmax is None:
1645 # vmax = 3*mat.mean()
1646
1647 if vs_time:
1648 # create a datetime index
1649 dt_idx = [now_string_2_dt(k.name) for k in self]
1650 mpl_times = date2num(dt_idx)
1651 y_max = mpl_times[0]
1652 y_min = mpl_times[-1]
1653
1654 else:
1655 y_min = len(self)
1656 y_max = 0
1657
1658 # creates x and y scales
1659 freq = self[0].frequency
1660 extent = [freq.f_scaled[0], freq.f_scaled[-1], y_min, y_max]
1661
1662 # set default imshow kwargs
1663 kw = {'extent': extent, 'aspect': 'auto', 'interpolation': 'nearest',
1664 'vmax': vmax}
1665 # update the users kwargs
1666 kw.update(kwargs)
1667 img = plt.imshow(mat, *args, **kw)
1668
1669 if vs_time:
1670 ax = plt.gca()
1671 ax.yaxis_date()
1672 # date_format = plt.DateFormatter('%M:%S.%f')
1673 # ax.yaxis.set_major_formatter(date_format)
1674 # cbar.set_label('Magnitude (dB)')
1675 plt.ylabel('Time')
1676 else:
1677 plt.ylabel('Network #')
1678
1679 plt.grid(0)
1680 freq.labelXAxis()
1681
1682 cbar = plt.colorbar()
1683 if cbar_label is not None:
1684 cbar.set_label(cbar_label)
1685
1686 return img
1687
1688 def plot_contour(freq: Frequency,
1689 x: NumberLike, y: NumberLike, z: NumberLike,
1690 min0max1: int, graph: bool = True,
1691 cmap: str = 'plasma_r', title: str = '',
1692 **kwargs):
1693 r"""
1694 Create a contour plot.
1695
1696 Parameters
1697 ----------
1698 freq : :skrf.Frequency:
1699 Frequency object.
1700 x : array
1701 x points
1702 y : array
1703 y points.
1704 z : array
1705 z points.
1706 min0max1 : int
1707 0 for min, 1 for max.
1708 graph : bool, optional
1709 plot graph if True. The default is True.
1710 cmap : str, optional
1711 Colormap label. The default is 'plasma_r'.
1712 title : str, optional
1713 Figure title. The default is ''.
1714 \*\*kwargs : dict
1715 Other parameters passed to `matplotlib.plot()`.
1716
1717 Returns
1718 -------
1719 GAMopt : :skrf.Network:
1720 Network
1721 VALopt : float
1722 min or max.
1723
1724 """
1725 from . import Network
1726
1727 ri = np.linspace(0,1, 50)
1728 ti = np.linspace(0,2*np.pi, 150)
1729 Ri , Ti = np.meshgrid(ri, ti)
1730 xi = np.linspace(-1,1, 50)
1731 Xi, Yi = np.meshgrid(xi, xi)
1732 triang = tri.Triangulation(x, y)
1733 interpolator = tri.LinearTriInterpolator(triang, z)
1734 Zi = interpolator(Xi, Yi)
1735 if min0max1 == 1 :
1736 VALopt = np.max(z)
1737 else :
1738 VALopt = np.min(z)
1739 GAMopt = Network(f=[freq], s=x[z==VALopt] +1j*y[z==VALopt])
1740
1741 if graph :
1742 fig, ax = plt.subplots(**kwargs)
1743 an = np.linspace(0, 2*np.pi, 50)
1744 cs, sn = np.cos(an), np.sin(an)
1745 plt.plot(cs, sn, color='k', lw=0.25)
1746 plt.plot(cs, sn*0, color='g', lw=0.25)
1747 plt.plot((1+cs)/2, sn/2, color='k', lw=0.25)
1748 plt.axis('equal')
1749 ax.set_axis_off()
1750 ax.contour(Xi, Yi, Zi, levels=20, vmin=Zi.min(), vmax= Zi.max(), linewidths=0.5, colors='k')
1751 cntr1 = ax.contourf(Xi, Yi, Zi, levels=20, vmin=Zi.min(), vmax= Zi.max(),cmap=cmap)
1752 fig.colorbar(cntr1, ax=ax)
1753 ax.plot(x, y, 'o', ms=0.3, color='k')
1754 ax.set(xlim=(-1, 1), ylim=(-1, 1))
1755 plt.title(title)
1756 plt.show()
1757 return GAMopt, VALopt
1758
1759 def plot_prop_complex(netw: Network, prop_name: str,
1760 m=None, n=None, ax=None,
1761 show_legend=True, **kwargs):
1762 r"""
1763 plot the Network attribute :attr:`{}` vs frequency.
1764
1765 Parameters
1766 ----------
1767 attribute : string
1768 Network attribute to plot
1769 m : int, optional
1770 first index of s-parameter matrix, if None will use all
1771 n : int, optional
1772 second index of the s-parameter matrix, if None will use all
1773 ax : :class:`matplotlib.Axes` object, optional
1774 An existing Axes object to plot on
1775 show_legend : Boolean
1776 draw legend or not
1777 y_label : string, optional
1778 the y-axis label
1779
1780 \*args,\**kwargs : arguments, keyword arguments
1781 passed to :func:`matplotlib.plot`
1782
1783 Note
1784 ----
1785 This function is dynamically generated upon Network
1786 initialization. This is accomplished by calling
1787 :func:`plot_vs_frequency_generic`
1788
1789 Examples
1790 --------
1791 >>> myntwk.plot_{}(m=1,n=0,color='r')
1792 """
1793
1794 # create index lists, if not provided by user
1795 if m is None:
1796 M = range(netw.number_of_ports)
1797 else:
1798 M = [m]
1799 if n is None:
1800 N = range(netw.number_of_ports)
1801 else:
1802 N = [n]
1803
1804 if 'label' not in kwargs.keys():
1805 gen_label = True
1806 else:
1807 gen_label = False
1808
1809 for m in M:
1810 for n in N:
1811 # set the legend label for this trace to the networks
1812 # name if it exists, and they didn't pass a name key in
1813 # the kwargs
1814 if gen_label:
1815 kwargs['label'] = _get_label_str(netw, prop_name[0].upper(), m, n)
1816
1817 # plot the desired attribute vs frequency
1818 plot_complex_rectangular(
1819 z=getattr(netw, prop_name)[:, m, n],
1820 show_legend=show_legend, ax=ax,
1821 **kwargs)
1822
1823 def plot_prop_polar(netw: Network, prop_name: str,
1824 m=None, n=None, ax=None,
1825 show_legend=True, **kwargs):
1826
1827 r"""
1828 plot the Network attribute :attr:`{}` vs frequency.
1829
1830 Parameters
1831 ----------
1832 attribute : string
1833 Network attribute to plot
1834 m : int, optional
1835 first index of s-parameter matrix, if None will use all
1836 n : int, optional
1837 second index of the s-parameter matrix, if None will use all
1838 ax : :class:`matplotlib.Axes` object, optional
1839 An existing Axes object to plot on
1840 show_legend : Boolean
1841 draw legend or not
1842 y_label : string, optional
1843 the y-axis label
1844
1845 \*args,\**kwargs : arguments, keyword arguments
1846 passed to :func:`matplotlib.plot`
1847
1848 Note
1849 ----
1850 This function is dynamically generated upon Network
1851 initialization. This is accomplished by calling
1852 :func:`plot_vs_frequency_generic`
1853
1854 Examples
1855 --------
1856 >>> myntwk.plot_{}(m=1,n=0,color='r')
1857 """
1858
1859 # create index lists, if not provided by user
1860 if m is None:
1861 M = range(netw.number_of_ports)
1862 else:
1863 M = [m]
1864 if n is None:
1865 N = range(netw.number_of_ports)
1866 else:
1867 N = [n]
1868
1869 if 'label' not in kwargs.keys():
1870 gen_label = True
1871 else:
1872 gen_label = False
1873
1874 for m in M:
1875 for n in N:
1876 # set the legend label for this trace to the networks
1877 # name if it exists, and they didn't pass a name key in
1878 # the kwargs
1879 if gen_label:
1880 kwargs['label'] = _get_label_str(netw, prop_name[0].upper(), m, n)
1881
1882 # plot the desired attribute vs frequency
1883 plot_complex_polar(
1884 z = getattr(netw,prop_name)[:,m,n],
1885 show_legend = show_legend, ax = ax,
1886 **kwargs)