Plotting#

import matplotlib.pyplot as plt
import plotly.graph_objects as go
import numpy  as np

%matplotlib inline
%config InlineBackend.figure_format='retina'
  • Matplotlib is the most widely used plotting library in the ecosystem of python. In the above cel we loaded matplotlib and the relevant libraries.

  • The easiest way to use matplotlib is via pyplot, which allows you to plot 1D and 2D data. Here is a simple example:

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f229032df40>]
../_images/5dcb2887b4cef1398e8567d682f6812dba1ef6305fc960b6b282a38df5a369c4.png

if we want to customize plots it is better to plot by first defining fig and ax objecs which have manuy methods for customizing figure resolution and plot related aspects respecticely.

fig, ax = plt.subplots()

y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
ax.plot(x, y_sin)
ax.plot(x, y_cos)

# Specify labels
ax.set_xlabel('x axis label')
ax.set_ylabel('y axis label')
ax.set_title('Sine and Cosine')
ax.legend(['Sine', 'Cosine'])

#fig.savefig("myfig.pdf")
<matplotlib.legend.Legend at 0x7f228dff7f40>
../_images/406b387400469922cd0b829c9aa62ac355f29cca2a14905eada1a0db8e475d1e.png

Widgets#

Suppose we would like to explore how the variation of parameter \(\lambda\) affects the following function of a standing wave:

\[f(x) = sin (\omega \cdot x +p)\]
  • Make a python-function which creates a plot as a function of a parameter(s) of interest.

  • Add an interactive widget on top to vary the parameter.

from ipywidgets import interact, interactive
 def plot_wave(phase, freq):          
    
    x  = np.linspace(0,10,1000)
    y  = np.sin(freq*x+phase)
        
    plt.plot(x, y)
    plt.show()
interactive(plot_wave, 
            phase=(0,2*np.pi), 
            freq=(0.1,5))

Here is another example combining interactive plotly plot with ipywidget slider

def plot_sine_wave(frequency=1.0):
    
    x = np.linspace(0, 2 * np.pi, 1000)
    y = np.sin(frequency * x)
    
    trace  = go.Scatter(x=x, y=y, mode='lines')
    layout = go.Layout(title=f'Sine Wave with Frequency = {frequency} Hz')
    
    fig = go.Figure(data=[trace], layout=layout)
    fig.show()
    
interact(plot_sine_wave, frequency=(0.5, 5, 0.1))
<function __main__.plot_sine_wave(frequency=1.0)>

Additional resoruces.#

Matplotlib has a huge scientific user base. This means that you can always find a good working template of any kind of visualization which you want to make. With basic understanding of matplotlib and some solid googling skills you can go very far. Here are some additional resources that you may find helpful