Skip to content

Instantly share code, notes, and snippets.

@shabaz123
Created July 15, 2024 00:27
Show Gist options
  • Save shabaz123/69f24585a5025b119238cad1d9bcfbcb to your computer and use it in GitHub Desktop.
Save shabaz123/69f24585a5025b119238cad1d9bcfbcb to your computer and use it in GitHub Desktop.
Plot S11 File with cursor attempt
# Create a Smith Chart and plot the contents of a .s1p file
import numpy as np
import skrf as rf
from matplotlib import rcParams, pyplot as plt
import sys
from mpl_smithchart import SmithAxes
# output settings
out_title = "Smith Chart Output"
# set the default filename
fname1 = 'test.s1p'
# check if there is any command line filename
if len(sys.argv) == 2:
fname1 = sys.argv[1]
class SnappingCursor:
"""
A cross-hair cursor that snaps to the data point of a line, which is
closest to the *x* position of the cursor.
For simplicity, this assumes that *x* values of the data are sorted.
"""
def __init__(self, ax, line):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self.x, self.y = line.get_data()
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
self._last_index = None
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
index = min(np.searchsorted(self.x, x), len(self.x) - 1)
if index == self._last_index:
return # still on the same data point. Nothing to do.
self._last_index = index
x = self.x[index]
y = self.y[index]
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
print(f'Opening file: {fname1}')
ntwk1 = rf.Network(fname1)
sdata = ntwk1.s
sdata = sdata.reshape(sdata.shape[0])
# customize the Smith Chart functionality here:
SmithAxes.update_scParams(grid_major_enable=True)
# create a figure and Smith Chart
fig = plt.figure(figsize=(10,10)).set_layout_engine('tight')
ax = plt.subplot(111, projection='smith')
# plot the data
line = plt.plot(sdata, markevery=5, label="trace1", datatype=SmithAxes.S_PARAMETER)
# final decorations
legend = plt.legend(loc="lower right", fontsize=12)
plt.title(out_title, fontsize=18)
# cursor
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
# save the plot to a file
plt.savefig("export.png", format="png")
# display the plot
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment