Pages

Interactive HTML Plots with Python and Plotly

I came across Plotly's offline plotting functionality recently as part of my work at Draper Labs and was very impressed with the results. This method is particularly useful for a number of reasons. Firstly, since the plot is interactive and the raw data is listed explicitly in the HTML output, my coworkers have the option to zoom, select a subset of the plotted curves to display, take a snapshot, or extract and replot the raw data. None of this functionality is available in static PNG plots, which I have been accustomed to make in the past. Secondly, most interactive plots require running Matlab or Python with specific modules installed which requires a certain amount of effort and programming know-how that is unreasonable to expect from every team member; using these HTML plots requires no more technical expertise than being able to say "Open with... Chrome".

I can now send these HTML plots to any of my coworkers and be confident that I will not receive tedious requests to replot minute details or that recipients will not or cannot view the data due to technical barriers. I find the interactivity also aids mental digestion of the plotted data and is particularly helpful for large data sets since curves can be selected from the legend. Moreover, the plots are then easily embeddable in webpages.
import numpy as np
import plotly
import plotly.graph_objects as go


def plot_Plotly(datalist = None, legend = None):
    if datalist is None or legend is None:
        exit(1)
     
    # Create interactive Plotly for all data            
    fig = go.Figure()
            
    for i,data in enumerate(datalist):
        fig.add_trace(go.Scatter(x = data[0,:], y=data[1,:], mode='lines', name=str(legend[i])))
        fig.update_layout(title=r'$\text{My Title}$', xaxis_title=r'$\text{My X-Axis}$', yaxis_title=r'$\text{My Y-Axis}$')

    plotly.offline.plot(fig, filename='/Users/nolanpeard/Desktop/plotly.html', include_mathjax='cdn')
    
    # Uncomment the next line to print the appropriate command for embedding in HTML webpages. The line above generates a stand-alone HTML file that can be opened in a browser 
    # print(plotly.offline.plot(fig, include_mathjax='cdn', include_plotlyjs=False, output_type='div'))
    # Remember to include  in the HTML before the first div command, otherwise the plot will not work 


if __name__ == "__main__":
    keys = [r'$\sin(4x)$', r'$\cos(4x)$']
    x = np.linspace(-10,10,1000)
    y1 = np.sin(4*x)
    y2 = np.cos(4*x)

    data = [[x, y1], [x, y2]]
    data = np.asarray(data)
        
    plot_Plotly(datalist = np.asarray(data), legend = np.asarray(keys))

Flying Squirrel

Do you see the flying squirrel in the data? This happened randomly while working on my correlated diffraction project.