Skip to content

Instantly share code, notes, and snippets.

@ahmedhosny
Created January 11, 2018 22:01
Show Gist options
  • Select an option

  • Save ahmedhosny/7d2df225d1842eecc6644c7d36dcf69d to your computer and use it in GitHub Desktop.

Select an option

Save ahmedhosny/7d2df225d1842eecc6644c7d36dcf69d to your computer and use it in GitHub Desktop.
plots 1D vectors and smoothes them using plotly
import numpy as np
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)
from plotly import tools
import scipy.signal as signal
from scipy.interpolate import interp1d
# myX - x axis values
# myY - y axis values
# smooth - smoothing value
def getSmooth(myX,myY,smooth):
# BUTTER
# GET THE WINDOW
b, a = signal.butter(3, smooth, analog=False, btype = 'lowpass' , output='ba')
fitData = signal.filtfilt(b,a,myY)
# EXTRA STEP NEEDED TO SMOOTH - interpolate (this gives a function)
f2 = interp1d(myX, fitData, kind='cubic')
# MAKE A NEW X DOMAIN
newX = np.linspace(0,len(myX)-1,len(myX))
return newX, f2(newX)
# metricList - list of values to plot on Y
# mul - multiplier to move the values up and down along Y
# smooth - smooth value
# color1 - color of non smoothed line
# color2 - color of smoothed line
def getTwoLines(metricList,mul,smooth,color1,color2):
scatter1 = go.Scatter( x=np.arange(len(metricList)), y=[k-mul for k in metricList],
showlegend=False ,line=dict(color=color1,width=1) )
newX,newY = getSmooth(np.arange(len(metricList)),[k-mul for k in metricList],smooth)
scatter2 = go.Scatter( x=np.arange(len(newX)-1), y=[k for k in newY],
line=dict(color=color2,width=2))
return [scatter1,scatter2]
dummy = np.random.normal(size=50)
data = getTwoLines(dummy,0,0.05,'rgb(31,120,180)','rgb(166,206,227)')
layout = go.Layout(
title = "test title",
xaxis=dict(
showgrid=True,
title="x axis"
),
yaxis=dict(
showgrid=True,
title="y axis"
)
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
plot(fig,
show_link=False,
image_filename="name",
image="svg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment