Debian Codegraph @

doc/source/tutorials/Plotting.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "raw",
5 "metadata": {
6 "raw_mimetype": "text/restructuredtext"
7 },
8 "source": [
9 ".. _plotting::\n",
10 "\n",
11 "|\n",
12 "|\n",
13 "\n",
14 "Download This Notebook: :download:`Plotting.ipynb`\n"
15 ]
16 },
17 {
18 "cell_type": "markdown",
19 "metadata": {},
20 "source": [
21 "# Plotting \n",
22 "\n",
23 "## Introduction\n",
24 "\n",
25 "This tutorial describes **skrf's** plotting features. If you would like to use skrf's matplotlib interface with skrf styling, start with this"
26 ]
27 },
28 {
29 "cell_type": "code",
30 "execution_count": null,
31 "metadata": {},
32 "outputs": [],
33 "source": [
34 "%matplotlib inline"
35 ]
36 },
37 {
38 "cell_type": "code",
39 "execution_count": null,
40 "metadata": {},
41 "outputs": [],
42 "source": [
43 "from matplotlib import pyplot as plt # for advanced smith chart only\n",
44 "\n",
45 "import skrf as rf"
46 ]
47 },
48 {
49 "cell_type": "markdown",
50 "metadata": {},
51 "source": [
52 "## Plotting Methods\n",
53 "\n",
54 "\n",
55 "Plotting functions are implemented as methods of the `Network` class.\n",
56 "\n",
57 "* `Network.plot_s_re`\n",
58 "* `Network.plot_s_im`\n",
59 "* `Network.plot_s_mag`\n",
60 "* `Network.plot_s_db`\n",
61 "* ...\n",
62 " \n",
63 "Similar methods exist for Impedance (`Network.z`) and Admittance Parameters (`Network.y`), \n",
64 "\n",
65 "\n",
66 "* `Network.plot_z_re`\n",
67 "* `Network.plot_z_im`\n",
68 "* ...\n",
69 "* `Network.plot_y_re`\n",
70 "* `Network.plot_y_im`\n",
71 "* ...\n",
72 "\n",
73 "\n",
74 "\n",
75 "\n",
76 "## Smith Chart \n",
77 "\n",
78 "\n",
79 "As a first example, load a [Network](../api/network.rst) and plot all four s-parameters on the Smith chart."
80 ]
81 },
82 {
83 "cell_type": "code",
84 "execution_count": null,
85 "metadata": {},
86 "outputs": [],
87 "source": [
88 "from skrf import Network\n",
89 "\n",
90 "ring_slot = Network('data/ring slot.s2p')\n",
91 "ring_slot.plot_s_smith()"
92 ]
93 },
94 {
95 "cell_type": "markdown",
96 "metadata": {},
97 "source": [
98 "scikit-rf includes a convenient command to make nicer figures quick:"
99 ]
100 },
101 {
102 "cell_type": "code",
103 "execution_count": null,
104 "metadata": {},
105 "outputs": [],
106 "source": [
107 "rf.stylely() # nicer looking. Can be configured with different styles\n",
108 "ring_slot.plot_s_smith()"
109 ]
110 },
111 {
112 "cell_type": "code",
113 "execution_count": null,
114 "metadata": {},
115 "outputs": [],
116 "source": [
117 "ring_slot.plot_s_smith(draw_labels=True)"
118 ]
119 },
120 {
121 "cell_type": "markdown",
122 "metadata": {},
123 "source": [
124 "Another common option is to draw admittance contours, instead of impedance. This is controlled through the `chart_type` argument."
125 ]
126 },
127 {
128 "cell_type": "code",
129 "execution_count": null,
130 "metadata": {},
131 "outputs": [],
132 "source": [
133 "ring_slot.plot_s_smith(chart_type='y')"
134 ]
135 },
136 {
137 "cell_type": "markdown",
138 "metadata": {},
139 "source": [
140 "### Advanced Smith Chart with markers\n",
141 "\n",
142 "The Smith Chart is a convenient plot that shows complex numbers with real and imaginary parts from zero to infinity with a zoom on a real reference in the center region. It is, however, not straightforward to figure out what point is related to which frequency because there is no frequency axis. A common workaround is to provide some frequency markers related to a table."
143 ]
144 },
145 {
146 "cell_type": "code",
147 "execution_count": null,
148 "metadata": {},
149 "outputs": [],
150 "source": [
151 "# prepare markers\n",
152 "lines = [\n",
153 " {'marker_idx': [30, 60, 90], 'color': 'g', 'm': 0, 'n': 0, 'ntw': ring_slot},\n",
154 " {'marker_idx': [15, 45, 75], 'color': 'r', 'm': 1, 'n': 0, 'ntw': ring_slot},\n",
155 "]\n",
156 "\n",
157 "# prepare figure\n",
158 "fig, ax = plt.subplots(1, 1, figsize=(7,8))\n",
159 "\n",
160 "# impedance smith chart\n",
161 "rf.plotting.smith(ax = ax, draw_labels = True, ref_imm = 50.0, chart_type = 'z')\n",
162 "\n",
163 "# plot data\n",
164 "col_labels = ['Frequency', 'Real Imag']\n",
165 "row_labels = []\n",
166 "row_colors = []\n",
167 "cell_text = []\n",
168 "for l in lines:\n",
169 " m = l['m']\n",
170 " n = l['n']\n",
171 " l['ntw'].plot_s_smith(m=m, n=n, ax = ax, color=l['color'])\n",
172 " #plot markers\n",
173 " for i, k in enumerate(l['marker_idx']):\n",
174 " x = l['ntw'].s.real[k, m, n]\n",
175 " y = l['ntw'].s.imag[k, m, n]\n",
176 " z = l['ntw'].z[k, m, n]\n",
177 " z = f'{z.real:.4f} + {z.imag:.4f}j ohm'\n",
178 " f = l['ntw'].frequency.f_scaled[k]\n",
179 " f_unit = l['ntw'].frequency.unit\n",
180 " row_labels.append(f'M{i + 1}')\n",
181 " row_colors.append(l['color'])\n",
182 " ax.scatter(x, y, marker = 'v', s=20, color=l['color'])\n",
183 " ax.annotate(row_labels[-1], (x, y), xytext=(-7, 7), textcoords='offset points', color=l['color'])\n",
184 " cell_text.append([f'{f:.3f} {f_unit}', z])\n",
185 "leg1 = ax.legend(loc=\"upper right\", fontsize= 6)\n",
186 "\n",
187 "# plot the table\n",
188 "the_table = ax.table(cellText=cell_text,\n",
189 " colWidths=[0.4] * 2,\n",
190 " rowLabels=row_labels,\n",
191 " colLabels=col_labels,\n",
192 " rowColours=row_colors,\n",
193 " loc='bottom')\n",
194 "the_table.auto_set_font_size(False)\n",
195 "the_table.set_fontsize(6)\n",
196 "#the_table.scale(1.5, 1.5)"
197 ]
198 },
199 {
200 "cell_type": "markdown",
201 "metadata": {},
202 "source": [
203 "### Advanced Smith Chart with background\n",
204 "\n",
205 "The Smith Chart can be drawn above a high-resolution Smith Chart background (or another image upon your fantasy)."
206 ]
207 },
208 {
209 "cell_type": "code",
210 "execution_count": null,
211 "metadata": {},
212 "outputs": [],
213 "source": [
214 "# prepare figure\n",
215 "fig, ax = plt.subplots(1, 1, figsize=(8,8))\n",
216 "background = plt.imread('figures/smithchart.png')\n",
217 "\n",
218 "# tweak background position\n",
219 "ax.imshow(background, extent=[-1.185, 1.14, -1.13, 1.155])\n",
220 "rf.plotting.smith(ax = ax, draw_labels = True, ref_imm = 1.0, chart_type = 'z')\n",
221 "\n",
222 "ring_slot.plot_s_smith(ax = ax)"
223 ]
224 },
225 {
226 "cell_type": "markdown",
227 "metadata": {},
228 "source": [
229 " \n",
230 "See `skrf.plotting.smith()` for more info on customizing the Smith Chart. \n",
231 "\n",
232 "## Complex Plane \n",
233 "\n",
234 "\n",
235 "Network parameters can also be plotted in the complex plane without a Smith Chart through `Network.plot_s_complex`."
236 ]
237 },
238 {
239 "cell_type": "code",
240 "execution_count": null,
241 "metadata": {},
242 "outputs": [],
243 "source": [
244 "from matplotlib import pyplot as plt\n",
245 "\n",
246 "ring_slot.plot_s_complex()\n",
247 "\n",
248 "plt.axis('equal') # otherwise circles won't be circles"
249 ]
250 },
251 {
252 "cell_type": "markdown",
253 "metadata": {},
254 "source": [
255 "## Log-Magnitude \n",
256 "\n",
257 "\n",
258 "Scalar components of the complex network parameters can be plotted vs \n",
259 "frequency as well. To plot the log-magnitude of the s-parameters vs. frequency,"
260 ]
261 },
262 {
263 "cell_type": "code",
264 "execution_count": null,
265 "metadata": {},
266 "outputs": [],
267 "source": [
268 "ring_slot.plot_s_db()"
269 ]
270 },
271 {
272 "cell_type": "markdown",
273 "metadata": {},
274 "source": [
275 " \n",
276 "When no arguments are passed to the plotting methods, all parameters are plotted. Single parameters can be plotted by passing indices `m` and `n` to the plotting commands (indexing start from 0). Comparing the simulated reflection coefficient off the ring slot to a measurement, "
277 ]
278 },
279 {
280 "cell_type": "code",
281 "execution_count": null,
282 "metadata": {},
283 "outputs": [],
284 "source": [
285 "from skrf.data import ring_slot_meas\n",
286 "\n",
287 "ring_slot.plot_s_db(m=0,n=0, label='Theory')\n",
288 "ring_slot_meas.plot_s_db(m=0,n=0, label='Measurement')"
289 ]
290 },
291 {
292 "cell_type": "markdown",
293 "metadata": {},
294 "source": [
295 "## Phase \n",
296 "\n",
297 "\n",
298 "Plot phase, "
299 ]
300 },
301 {
302 "cell_type": "code",
303 "execution_count": null,
304 "metadata": {},
305 "outputs": [],
306 "source": [
307 "ring_slot.plot_s_deg()"
308 ]
309 },
310 {
311 "cell_type": "markdown",
312 "metadata": {},
313 "source": [
314 " \n",
315 "Or unwrapped phase, "
316 ]
317 },
318 {
319 "cell_type": "code",
320 "execution_count": null,
321 "metadata": {},
322 "outputs": [],
323 "source": [
324 "ring_slot.plot_s_deg_unwrap()"
325 ]
326 },
327 {
328 "cell_type": "markdown",
329 "metadata": {},
330 "source": [
331 "Phase is radian (rad) is also available"
332 ]
333 },
334 {
335 "cell_type": "markdown",
336 "metadata": {},
337 "source": [
338 "## Group Delay "
339 ]
340 },
341 {
342 "cell_type": "markdown",
343 "metadata": {},
344 "source": [
345 "A Network has a `plot()` method which creates a rectangular plot of the argument vs frequency. This can be used to make plots are aren't 'canned'. For example group delay"
346 ]
347 },
348 {
349 "cell_type": "code",
350 "execution_count": null,
351 "metadata": {},
352 "outputs": [],
353 "source": [
354 "gd = abs(ring_slot.s21.group_delay) *1e9 # in ns\n",
355 "\n",
356 "ring_slot.plot(gd)\n",
357 "plt.ylabel('Group Delay (ns)')\n",
358 "plt.title('Group Delay of Ring Slot S21')"
359 ]
360 },
361 {
362 "cell_type": "markdown",
363 "metadata": {},
364 "source": [
365 "## Impedance, Admittance \n",
366 "\n",
367 "\n",
368 "The components the Impedance and Admittance parameters can be plotted \n",
369 "similarly, "
370 ]
371 },
372 {
373 "cell_type": "code",
374 "execution_count": null,
375 "metadata": {},
376 "outputs": [],
377 "source": [
378 "ring_slot.plot_z_im()"
379 ]
380 },
381 {
382 "cell_type": "code",
383 "execution_count": null,
384 "metadata": {},
385 "outputs": [],
386 "source": [
387 "ring_slot.plot_y_im()"
388 ]
389 },
390 {
391 "cell_type": "markdown",
392 "metadata": {},
393 "source": [
394 "## Customizing Plots\n",
395 "\n",
396 "\n",
397 "The legend entries are automatically filled in with the Network's `Network.name`. The entry can be overridden by passing the `label` argument to the plot method."
398 ]
399 },
400 {
401 "cell_type": "code",
402 "execution_count": null,
403 "metadata": {},
404 "outputs": [],
405 "source": [
406 "ring_slot.plot_s_db(m=0,n=0, label = 'Simulation')"
407 ]
408 },
409 {
410 "cell_type": "markdown",
411 "metadata": {},
412 "source": [
413 "The frequency unit used on the x-axis is automatically filled in from \n",
414 "the Networks `Network.frequency.unit` attribute. To change\n",
415 "the label, change the frequency's `unit`."
416 ]
417 },
418 {
419 "cell_type": "code",
420 "execution_count": null,
421 "metadata": {},
422 "outputs": [],
423 "source": [
424 "ring_slot.frequency.unit = 'mhz'\n",
425 "ring_slot.plot_s_db(0,0)"
426 ]
427 },
428 {
429 "cell_type": "markdown",
430 "metadata": {},
431 "source": [
432 "Other key word arguments given to the plotting methods are passed through to the matplotlib `matplotlib.pyplot.plot` function. "
433 ]
434 },
435 {
436 "cell_type": "code",
437 "execution_count": null,
438 "metadata": {},
439 "outputs": [],
440 "source": [
441 "ring_slot.frequency.unit='ghz'\n",
442 "ring_slot.plot_s_db(m=0,n=0, linewidth = 3, linestyle = '--', label = 'Simulation')\n",
443 "ring_slot_meas.plot_s_db(m=0,n=0, marker = 'o', markevery = 10,label = 'Measured')\n"
444 ]
445 },
446 {
447 "cell_type": "markdown",
448 "metadata": {},
449 "source": [
450 "All components of the plots can be customized through [matplotlib]( http://matplotlib.sourceforge.net) functions, and `styles` can be used with a context manager. "
451 ]
452 },
453 {
454 "cell_type": "code",
455 "execution_count": null,
456 "metadata": {},
457 "outputs": [],
458 "source": [
459 "from matplotlib import pyplot as plt\n",
460 "from matplotlib import style\n",
461 "\n",
462 "mpl_style = \"seaborn-ticks\"\n",
463 "mpl_style = mpl_style if mpl_style in style.available else \"seaborn-v0_8-ticks\"\n",
464 "\n",
465 "with style.context(mpl_style):\n",
466 " ring_slot.plot_s_smith()\n",
467 " plt.xlabel('Real Part')\n",
468 " plt.ylabel('Imaginary Part')\n",
469 " plt.title('Smith Chart With Legend Room')\n",
470 " plt.axis([-1.1,2.1,-1.1,1.1])\n",
471 " plt.legend(loc=5)\n"
472 ]
473 },
474 {
475 "cell_type": "markdown",
476 "metadata": {},
477 "source": [
478 "## Saving Plots\n",
479 "\n",
480 "Plots can be saved in various file formats using the GUI provided by the matplotlib. However, skrf provides a convenience function, called `skrf.plotting.save_all_figs`, that allows all open figures to be saved to disk in multiple file formats, with filenames pulled from each figure's title,"
481 ]
482 },
483 {
484 "cell_type": "code",
485 "execution_count": null,
486 "metadata": {},
487 "outputs": [],
488 "source": [
489 "from skrf.plotting import save_all_figs\n",
490 "\n",
491 "save_all_figs('data/', format=['png','eps','pdf'])"
492 ]
493 },
494 {
495 "cell_type": "markdown",
496 "metadata": {},
497 "source": [
498 "## Adding Markers Post Plot\n",
499 "\n",
500 "\n",
501 "A common need is to make a color plot, interpretable in greyscale print. \n",
502 "The `skrf.plotting.add_markers_to_lines` adds different markers each line in a plots *after* the plot has been made, which is usually when you remember to add them."
503 ]
504 },
505 {
506 "cell_type": "code",
507 "execution_count": null,
508 "metadata": {},
509 "outputs": [],
510 "source": [
511 "from skrf import plotting\n",
512 "\n",
513 "with plt.style.context('grayscale'):\n",
514 " ring_slot.plot_s_deg()\n",
515 " plotting.add_markers_to_lines()\n",
516 " plt.legend() # have to re-generate legend\n"
517 ]
518 },
519 {
520 "cell_type": "code",
521 "execution_count": null,
522 "metadata": {},
523 "outputs": [],
524 "source": []
525 }
526 ],
527 "metadata": {
528 "anaconda-cloud": {},
529 "celltoolbar": "Raw Cell Format",
530 "kernelspec": {
531 "display_name": "Python 3 (ipykernel)",
532 "language": "python",
533 "name": "python3"
534 },
535 "language_info": {
536 "codemirror_mode": {
537 "name": "ipython",
538 "version": 3
539 },
540 "file_extension": ".py",
541 "mimetype": "text/x-python",
542 "name": "python",
543 "nbconvert_exporter": "python",
544 "pygments_lexer": "ipython3",
545 "version": "3.8.10"
546 },
547 "vscode": {
548 "interpreter": {
549 "hash": "637c323cf467337602e9974a89cb4d3fc95fac3ef875a73e62754f8e768d8de7"
550 }
551 }
552 },
553 "nbformat": 4,
554 "nbformat_minor": 1
555 }