Skip to content

Instantly share code, notes, and snippets.

@jj-github-jj
Last active November 9, 2022 03:59
Show Gist options
  • Save jj-github-jj/48274f0d64b7724d875b4154f35bfd2a to your computer and use it in GitHub Desktop.
Save jj-github-jj/48274f0d64b7724d875b4154f35bfd2a to your computer and use it in GitHub Desktop.
plotly snippets
# speed up figures with lots of data
pip install plotly-resampler
from plotly_resampler import register_plotly_resampler, unregister_plotly_resampler
register_plotly_resampler(mode="auto", default_n_shown_samples=1000)
import plotly.io as pio
pio.renderers.default = "notebook" # patch for exporting to html in vscode for plotly interactive plots
#hover hoverlabel
fig.update_layout(hoverlabel = dict(namelength = -1)) # show full string in hover label plotly
#Plotly
import plotly.graph_objects as go
fig.layout.height=400
fig.update_yaxes(range=[-20,0])
fig.layout.title='Tx RL'
fig.layout.yaxis.title='S11 dB -Return Loss'
# add new line in annotation plotly using html <br>
fig=fig.add_annotation(x=x*1e6,y=-3,text=f'LO <br> {x:2.2g}',visible=True)
def plotly_xy(x,y, title="Plot Title",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",
legend_title="Legend Title"):
fig=go.Figure() #initialize figure object
fig=fig.update_layout(
title=title,
xaxis_title=xaxis_title,
yaxis_title=yaxis_title,
legend_title=legend_title,
)
fig=fig.add_trace (go.Scatter(x=x,y=y,name='test spectrum',showlegend=True))
fig=fig.update_xaxes(exponentformat="SI") #Engg notation for x axis
return (fig)
# add traces syntax copying data
fig3 = go.Figure(data=fig1.data + fig2.data)
fig=go.Figure() #initialize figure object
fig=fig.update_layout(
title="Title",yaxis_title="dBc/Hz",xaxis_title="Offset Hz")
fig=fig.update_xaxes(exponentformat="SI",type="log")
#-- prefix or change legend names
fig.data[0].name=name+fig.data[0].name
fig.data[1].name=name+fig.data[1].name
fig=fig.add_trace (go.Scatter(x=df_s.index,y=df_s['s_db 21'],name=ntwk.name))
fig.update_layout(
title="Plot Title",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",
legend_title="Legend Title",
font=dict(
family="Courier New, monospace",
size=18,
color="RebeccaPurple"
)
)
fig.update_layout(
title="Plot Title",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",
legend_title="Legend Title",
)
fig=go.Figure() #initialize figure object
fig=fig.add_trace (go.Scatter(x=x,y=y,name='test spectrum'),showlegend=True)
fig=fig.update_xaxes(exponentformat="SI") #Engg notation for x axis
fig.update_layout(yaxis_range=[-4,4])
fig.add_vline(x=2.5, line_width=3, line_dash="dash", line_color="green")
fig.add_hrect(y0=0.9, y1=2.6, line_width=0, fillcolor="red", opacity=0.2)
fig.show()
fig.add_annotation(x=H2,y=-20,text='H2',visible=True)
#fig.add_vline(x=H2) #vertical line
fig=fig.update_layout(hovermode='x unified') #show vertical line where the mouse is with annotation
#--- set to engg
fig=fig.update_xaxes(exponentformat="SI") #Engg notation for x axis
fig=fig.update_xaxes(showexponent='all')
fig=fig.update_xaxes(minexponent=0) #default is 3 for min exponent which can sometimes not show SI notation when desired
#--- plot util
def clear_annotations(fig):
fig.layout.annotations=[]
return (fig)
def find_nearest(array, value):
array = np.asarray(array) #in case input is a list
idx = (np.abs(array - value)).argmin()
return idx,array[idx] #return in x,y format x is index, y is value
def xy_annotate (fig2, trace_index=0, y_vals=[],text_in='',angle=0):
""" annotates the closest point on the xy trace of plotly graph object fig2
"""
print ('text in', text_in)
d=fig2.data[trace_index] # first trace
for y_val in y_vals:
x=d.x[find_nearest(d.y,y_val)[0]] #find index,val nearest to y_val
y= find_nearest(d.y,y_val)[1] #index 1 is y value, index 0 is array index
# print ('xy',x,y)
# print ('text ..', text_in)
if text_in=='': #use x y coordinates as text if text is not specified
text=f'{x:0.2f} {y:0.2f}'
else:
text=text_in
#print ('text',text)
fig2=fig2.add_annotation(x=x,y=y,text=text,visible=True)
#xshift and yshift move the entire text and arrow units pixels
fig2=fig2.update_annotations(font_size=10,textangle=angle,standoff=0,xshift=1,yshift=-1)
# standoff
# print ('xy',x,y)
return (fig2)
def legend_as_annotation(fig,relative_y=.1):
ntraces=len(fig.data)
for trace_index, data in enumerate(fig.data):
ymax=np.max(data.y)
ymin=np.min(data.y)
y_val=ymin+relative_y*(ymax-ymin)*trace_index/ntraces
fig=xy_annotate(fig,trace_index=trace_index, y_vals=[y_val],text_in=data.name)
return (fig)
#--- line styles
fig=fig.add_trace (go.Scatter(x=Pin,y=IP3_dBm,name="IP3 dBm",line=dict (dash='dash') ))
fig.add_trace(go.Scatter(x=month, y=high_2007, name='High 2007',
line=dict(color='firebrick', width=4,
dash='dash') # dash options include 'dash', 'dot', and 'dashdot'
# syntax for copying plots
fig3 = go.Figure(data=(fig.data[0], fig.data[1]))
fig3 = go.Figure(data=fig1.data + fig2.data)
#Fig_Set_B is a collection of go.Figure objects with scatter plots
# this line gets the first xy trace from each plot in Fig_Set_B plots and combines them into a single plot
# by combining the data (dicts) into a single tuple of selected dicts which can be used as data for new plot
fig3 = go.Figure(data= tuple(Fig_Set_B[x].data[0] for x in range(6)) ) # create a tuple of first trace in plot set
#update to SI (engineering format) and range in one line on plotly
fig3=fig3.update_layout(xaxis_range=[.5e9,8e9],xaxis = dict(exponentformat = 'SI') )
def plotly_fig_to_clipboard(fig):
try :import clipboard #clipboard copy paste
except:
!pip install clipboard
import clipboard
s=plotly.io.to_json(fig) #single figure not list of figures for now
clipboard.copy(s) # s=clipboard.paste(); fig=plotly.io.from_json(s)
#copy list of figures to clipboard and recover from clipboard
s=[plotly.io.to_json(x) for x in fig_list]
import json
sjson=json.dumps(s)
clipboard.copy(sjson) #list of figures copied as single json string
# in target notebook
clipv=clipboard.paste()
import ast
clipv=ast.literal_eval(clipv) #can not use clipv=clipboard.paste() directly since it makes clipv a string
nfig=plotly.io.from_json(clipv[1]) # clipv now is a list of plotly fig objects
def copy_plot_and_annotations(target_fig,source_fig_list,fig_index,trace_index):
fig=target_fig
source_fig_list[trace_index]
print ('a')
fig=fig.add_trace(source_fig_list[fig_index].data[trace_index])
#fig.layout=(x_db_plots[0].layout)
#fig=fig.add_trace(mytuple)
#x_db_plots[0].layout.annotations
#copy annotation from another figure
for annotation in source_fig_list[fig_index].layout.annotations:
fig=fig.add_annotation( annotation)
return (fig)
# save to zip file plotly fig object and restore from zip file fig object
jjutil_reload()
comment='this is a comment 21'
zipfile_name=''
figure_number =1
os.path.basename(filename)
mf.mp_save_fig_zip_file(fig2)
jjutil_reload()
import my_functions_from_ipynb_files as mf
zip_file_name
mf.read_fig_from_zipfile(zip_file_name)
new_fig=mf.mp_read_from_html(r'P:\Misc\users\js\py\LV\Rainier LO PN sweep DSAin\temp\Figure1_tmp8xyhoi90.html',plot_number=1)
new_fig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment