Interact Exercise 2

Imports


In [2]:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np

In [3]:
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display


:0: FutureWarning: IPython widgets are experimental and may change in the future.

Plotting with parameters

Write a plot_sin1(a, b) function that plots $sin(ax+b)$ over the interval $[0,4\pi]$.

  • Customize your visualization to make it effective and beautiful.
  • Customize the box, grid, spines and ticks to match the requirements of this data.
  • Use enough points along the x-axis to get a smooth plot.
  • For the x-axis tick locations use integer multiples of $\pi$.
  • For the x-axis tick labels use multiples of pi using LaTeX: $3\pi$.

In [4]:
def plot_sin1(a,b):
    x = np.arange(0,4*np.pi)
    plt.plot(x, np.sin(a*x+b))
    plt.xticks([0,np.pi, 2*np.pi, 3*np.pi, 4*np.pi],
           ['$0$', r'$\pi$', r'$2\pi$', r'$3\pi$', r'$4\pi$'])
    plt.title('Sine Function')
    plt.grid(True)
    plt.xlabel('x')
    plt.ylabel('y')
    print(plot_sin1)

In [5]:
plot_sin1(5, 3.4);


<function plot_sin1 at 0x7f7d3d258d90>

Then use interact to create a user interface for exploring your function:

  • a should be a floating point slider over the interval $[0.0,5.0]$ with steps of $0.1$.
  • b should be a floating point slider over the interval $[-5.0,5.0]$ with steps of $0.1$.

In [6]:
interact(plot_sin1, a = [0.,5.,0.1], b = [-5.,5.,0.1])


<function plot_sin1 at 0x7f7d3d258d90>
Out[6]:
<function __main__.plot_sin1>

In [7]:
assert True # leave this for grading the plot_sine1 exercise

In matplotlib, the line style and color can be set with a third argument to plot. Examples of this argument:

  • dashed red: r--
  • blue circles: bo
  • dotted black: k.

Write a plot_sine2(a, b, style) function that has a third style argument that allows you to set the line style of the plot. The style should default to a blue line.


In [8]:
def plot_sine2(a,b, style):
    x = np.arange(0,4*np.pi)
    plt.plot(x, np.sin(a*x+b), style)
    plt.xticks([0,np.pi, 2*np.pi, 3*np.pi, 4*np.pi],
               ['$0$', r'$\pi$', r'$2\pi$', r'$3\pi$', r'$4\pi$'])
    plt.title('Sine Function')
    plt.grid(True)
    plt.xlabel('x')
    plt.ylabel('y')
    style = style
    print(plot_sine2)

In [9]:
plot_sine2(4.0, -1.0, 'r--')


<function plot_sine2 at 0x7f7d3d147f28>

Use interact to create a UI for plot_sine2.

  • Use a slider for a and b as above.
  • Use a drop down menu for selecting the line style between a dotted blue line line, black circles and red triangles.

In [11]:
interact(plot_sine2, a = [0.,5.,0.1], b = [-5.,5.,0.1], 
         style=('b.', 'ko', 'r^'))


<function plot_sine2 at 0x7f7d3d147f28>

In [176]:
assert True # leave this for grading the plot_sine2 exercise

In [ ]: