Download This Notebook: Plotting.ipynb

Plotting

Introduction

This tutorial describes skrf’s plotting features. If you would like to use skrf’s matplotlib interface with skrf styling, start with this

In [1]:
%matplotlib inline
import skrf as rf
rf.stylely()

Plotting Methods

Plotting functions are implemented as methods of the Network class.

  • Network.plot_s_re
  • Network.plot_s_im
  • Network.plot_s_mag
  • Network.plot_s_db

Similar methods exist for Impedance (Network.z) and Admittance Parameters (Network.y),

  • Network.plot_z_re
  • Network.plot_z_im
  • Network.plot_y_re
  • Network.plot_y_im

Smith Chart

As a first example, load a Network and plot all four s-parameters on the Smith chart.

In [2]:
from skrf import Network

ring_slot = Network('data/ring slot.s2p')
ring_slot.plot_s_smith()
../_images/tutorials_Plotting_4_0.png
In [3]:
ring_slot.plot_s_smith(draw_labels=True)
../_images/tutorials_Plotting_5_0.png

Another common option is to draw addmitance contours, instead of impedance. This is controled through the chart_type argument.

In [4]:
ring_slot.plot_s_smith(chart_type='y')
../_images/tutorials_Plotting_7_0.png

See skrf.plotting.smith() for more info on customizing the Smith Chart.

Complex Plane

Network parameters can also be plotted in the complex plane without a Smith Chart through Network.plot_s_complex.

In [5]:
ring_slot.plot_s_complex()

from matplotlib import pyplot as plt
plt.axis('equal') # otherwise circles wont be circles
Out[5]:
(-0.85516579877200005,
 0.963732138327,
 -0.8760764348472001,
 0.90240321826520009)
../_images/tutorials_Plotting_9_1.png

Log-Magnitude

Scalar components of the complex network parameters can be plotted vs frequency as well. To plot the log-magnitude of the s-parameters vs. frequency,

In [6]:
ring_slot.plot_s_db()
../_images/tutorials_Plotting_11_0.png

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,

In [7]:
from skrf.data import ring_slot_meas
ring_slot.plot_s_db(m=0,n=0, label='Theory')
ring_slot_meas.plot_s_db(m=0,n=0, label='Measurement')
../_images/tutorials_Plotting_13_0.png

Phase

Plot phase,

In [8]:
ring_slot.plot_s_deg()
../_images/tutorials_Plotting_15_0.png

Or unwrapped phase,

In [9]:
ring_slot.plot_s_deg_unwrap()
../_images/tutorials_Plotting_17_0.png

Phase is radian (rad) is also available

Group Delay

A Network has a plot() method which creates a rectangular plot of the argument vs frequency. This can be used to make plots are arent ‘canned’. For example group delay

In [10]:
gd = abs(ring_slot.s21.group_delay) *1e9 # in ns

ring_slot.plot(gd)
plt.ylabel('Group Delay (ns)')
plt.title('Group Delay of Ring Slot S21')
Out[10]:
<matplotlib.text.Text at 0x7fbce123e710>
../_images/tutorials_Plotting_21_1.png

Impedance, Admittance

The components the Impendance and Admittance parameters can be plotted similarly,

In [11]:
ring_slot.plot_z_im()
../_images/tutorials_Plotting_23_0.png
In [12]:
ring_slot.plot_y_im()
../_images/tutorials_Plotting_24_0.png

Customizing Plots

The legend entries are automatically filled in with the Network’s Network.name. The entry can be overidden by passing the label argument to the plot method.

In [13]:
ring_slot.plot_s_db(m=0,n=0, label = 'Simulation')
../_images/tutorials_Plotting_26_0.png

The frequency unit used on the x-axis is automatically filled in from the Networks Network.frequency.unit attribute. To change the label, change the frequency’s unit.

In [14]:
ring_slot.frequency.unit = 'mhz'
ring_slot.plot_s_db(0,0)
../_images/tutorials_Plotting_28_0.png

Other key word arguments given to the plotting methods are passed through to the matplotlib matplotlib.pyplot.plot function.

In [15]:
ring_slot.frequency.unit='ghz'
ring_slot.plot_s_db(m=0,n=0, linewidth = 3, linestyle = '--', label = 'Simulation')
ring_slot_meas.plot_s_db(m=0,n=0, marker = 'o', markevery = 10,label = 'Measured')

../_images/tutorials_Plotting_30_0.png

All components of the plots can be customized through matplotlib functions, and styles can be used with a context manager.

In [16]:
from matplotlib import pyplot as plt
from matplotlib import style

with style.context('seaborn-ticks'):
    ring_slot.plot_s_smith()
    plt.xlabel('Real Part');
    plt.ylabel('Imaginary Part');
    plt.title('Smith Chart With Legend Room');
    plt.axis([-1.1,2.1,-1.1,1.1])
    plt.legend(loc=5)
../_images/tutorials_Plotting_32_0.png

Saving Plots

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,

from skrf.plotting import save_all_figs
save_all_figs('data/', format=['png','eps','pdf'])

Adding Markers Post Plot

A common need is to make a color plot, interpretable in greyscale print. 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.

In [17]:
from skrf import plotting
with style.context('printable'):
    ring_slot.plot_s_deg()
    plotting.add_markers_to_lines()
    plt.legend() # have to re-generate legend

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/style/core.py in use(style)
    106             try:
--> 107                 rc = rc_params_from_file(style, use_default_template=False)
    108                 _apply_style(rc)

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/__init__.py in rc_params_from_file(fname, fail_on_error, use_default_template)
   1150     """
-> 1151     config_from_file = _rc_params_in_file(fname, fail_on_error)
   1152

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/__init__.py in _rc_params_in_file(fname, fail_on_error)
   1067     rc_temp = {}
-> 1068     with _open_file_or_url(fname) as fd:
   1069         try:

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/contextlib.py in __enter__(self)
     58         try:
---> 59             return next(self.gen)
     60         except StopIteration:

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/__init__.py in _open_file_or_url(fname)
   1052             encoding = "utf-8"
-> 1053         with io.open(fname, encoding=encoding) as f:
   1054             yield f

FileNotFoundError: [Errno 2] No such file or directory: 'printable'

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
<ipython-input-17-4aa103b0c60f> in <module>()
      1 from skrf import plotting
----> 2 with style.context('printable'):
      3     ring_slot.plot_s_deg()
      4     plotting.add_markers_to_lines()
      5     plt.legend() # have to re-generate legend

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/contextlib.py in __enter__(self)
     57     def __enter__(self):
     58         try:
---> 59             return next(self.gen)
     60         except StopIteration:
     61             raise RuntimeError("generator didn't yield") from None

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/style/core.py in context(style, after_reset)
    142         mpl.rcdefaults()
    143     try:
--> 144         use(style)
    145     except:
    146         # Restore original settings before raising errors during the update.

~/checkouts/readthedocs.org/user_builds/scikit-rf/conda/latest/lib/python3.5/site-packages/matplotlib/style/core.py in use(style)
    111                        "not a valid URL or path. See `style.available` for "
    112                        "list of available styles.")
--> 113                 raise IOError(msg % style)
    114
    115

OSError: 'printable' not found in the style library and input is not a valid URL or path. See `style.available` for list of available styles.