Under Construction

Basic Visualization Cycle

Loading data

  • Load csv files using the pandas package into a data frame that is convenient to work with.

Plotting

  • Plot various views of data using matplotlib

In [2]:
# This command instructs the jupyter notebook to place the figures inline
%matplotlib inline

# Allows interaction in a separate window
#%matplotlib 

#%matplotlib 

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pylab as plt

df_enerji = pd.read_csv(u'data/enerji.csv',sep=';')
df_enerji


Out[2]:
Year Total Household Commercial Government Industrial Illumination Other
0 1970 7307.80000 15.899450 4.774351 4.129834 64.173896 2.641014 8.381455
1 1971 8289.30000 16.263134 4.567334 4.130626 64.478303 2.412749 8.147853
2 1972 9527.30000 16.087454 4.676036 3.815352 64.999528 2.183200 8.238431
3 1973 10530.10000 14.793782 4.299104 3.517535 67.287110 2.059809 8.042659
4 1974 11358.70000 15.157544 5.075405 3.828783 66.720663 1.957971 7.259634
5 1975 13491.70000 17.485565 4.887449 3.675593 64.819852 1.857438 7.274102
6 1976 16078.90000 17.549708 4.653303 3.455460 65.334693 1.591527 7.415308
7 1977 17968.80000 17.701794 4.988090 3.086461 66.688371 1.418013 6.117270
8 1978 18933.80000 18.901647 4.878577 3.172105 65.523561 1.460879 6.063231
9 1979 19633.10000 20.140477 5.725535 3.168119 63.858993 1.479644 5.627232
10 1980 20398.20000 21.507290 5.621574 2.986538 63.769842 1.419243 4.695512
11 1981 22030.00000 20.944167 5.705402 2.896505 64.485247 1.354517 4.614163
12 1982 23586.80000 20.886258 5.832923 2.527261 64.433073 1.310055 5.010430
13 1983 24465.10000 21.029548 5.720394 2.808082 63.664976 1.211113 5.565888
14 1984 27635.20000 19.802281 5.680798 2.774360 65.232023 1.197024 5.313513
15 1985 29708.60000 18.965215 5.454649 3.000815 66.000081 1.370983 5.208256
16 1986 32209.70000 18.951123 5.215820 3.217354 64.843510 2.067700 5.704493
17 1987 36697.30000 18.920193 4.762748 3.184703 65.053560 2.142664 5.936132
18 1988 39721.50000 20.025175 4.988231 3.195750 63.586471 2.052793 6.151580
19 1989 43120.00000 19.565399 5.334416 2.964518 64.013683 2.123609 5.998377
20 1990 46820.00000 19.569201 5.463050 3.125374 62.391713 2.630073 6.820589
21 1991 49282.90000 21.998908 6.197078 3.782854 57.853332 2.877063 7.290764
22 1992 53984.70000 21.268433 6.057827 3.720684 58.415810 3.444865 7.092380
23 1993 59237.00000 21.201276 6.086399 3.825987 57.813698 3.832571 7.240070
24 1994 61400.91700 21.904705 6.033646 5.399170 55.598624 4.075099 6.988756
25 1995 67393.85100 21.504259 6.224939 4.468614 56.395955 4.608581 6.797653
26 1996 74156.63800 22.107522 7.741592 4.048820 54.800583 4.159951 7.141532
27 1997 81884.91240 22.610262 8.368328 4.644799 53.112755 4.042548 7.221309
28 1998 87704.61670 22.842661 8.817956 4.870464 52.607228 4.208718 6.652974
29 1999 91201.87700 24.762927 8.999833 4.139236 50.964237 4.589034 6.544733
30 2000 98295.70716 24.301732 9.501314 4.179161 49.688534 4.636738 7.692520
31 2001 97070.04100 24.268381 10.206843 4.501882 48.407351 5.035778 7.579765
32 2002 102947.86150 22.884812 10.556112 4.449368 49.043653 4.957773 8.108282
33 2003 111766.06690 22.542526 11.516827 4.074626 49.298672 4.451090 8.116259
34 2004 121141.85240 22.798859 12.923817 3.740024 49.170396 3.658957 7.707947
35 2005 130262.75920 23.748135 14.235676 3.579472 47.821971 3.180485 7.434261
36 2006 143070.49860 24.090251 14.158324 4.225048 47.547686 2.761137 7.217555
37 2007 155135.25970 23.512272 14.916764 4.469121 47.567871 2.612328 6.921644
38 2008 161947.52830 24.442236 14.759924 4.534958 46.218837 2.451552 7.592493
39 2009 156894.06990 24.951552 15.946336 4.455007 44.915704 2.450592 7.280809
40 2010 172050.62810 24.068907 16.118511 4.127845 46.108899 2.190216 7.385622
41 2011 186099.55100 23.788930 16.402637 3.907820 47.275875 2.141934 6.482804
42 2012 194923.34950 23.278451 16.327404 4.511259 47.352835 1.992931 6.537121
43 2013 198045.18050 22.707689 18.911461 4.130228 47.086118 1.936747 5.227757

In [3]:
print(df_enerji.columns)

x = df_enerji.Year
y = df_enerji.Total/1000

fig = plt.figure(figsize=(10,4))
plt.plot(x, y)
plt.title('Total Energy consumption in Turkey (in Tera-Watt-hours TWh)')
plt.xlabel('Year')
plt.ylabel('Energy Consumption/TWh')
plt.show()
#mpld3.display(fig)


Index(['Year', 'Total', 'Household', 'Commercial', 'Government', 'Industrial',
       'Illumination', 'Other'],
      dtype='object')

In [4]:
sector = 'Commercial'
plt.plot(x, y*df_enerji[sector], 'o-')
plt.title('Energy use in Turkey by the '+sector+' sector')
plt.show()

plt.plot(x, df_enerji[sector], 'o-')
plt.title('Percentage of Energy use in Turkey by the '+sector+' sector')
plt.show()



In [5]:
sector1 = 'Commercial'
sector2 = 'Household'

x1 = df_enerji['Total']*df_enerji[sector1]/1000
x2 = df_enerji['Total']*df_enerji[sector2]/1000

plt.plot(x1, x2, 'o')
plt.xlabel(sector1)
plt.ylabel(sector2)
plt.title('Energy use in Turkey by '+sector1+' versus '+sector2)
plt.show()



In [6]:
from __future__ import print_function
"""
Edward Tufte uses this example from Anscombe to show 4 datasets of x
and y that have the same mean, standard deviation, and regression
line, but which are qualitatively different.

matplotlib fun for a rainy day
"""

import matplotlib.pyplot as plt
import numpy as np

x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])
y1 = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])
y2 = np.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74])
y3 = np.array([7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73])
x4 = np.array([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8])
y4 = np.array([6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89])


def fit(x):
    return 3 + 0.5*x

plt.figure(figsize=(8,8))

xfit = np.array([np.amin(x), np.amax(x)])

plt.subplot(221)
plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20))
plt.text(3, 12, 'I', fontsize=20)

plt.subplot(222)
plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20))
plt.text(3, 12, 'II', fontsize=20)

plt.subplot(223)
plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.text(3, 12, 'III', fontsize=20)
plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20))

plt.subplot(224)

xfit = np.array([np.amin(x4), np.amax(x4)])
plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20))
plt.text(3, 12, 'IV', fontsize=20)

# verify the stats
pairs = (x, y1), (x, y2), (x, y3), (x4, y4)
for x, y in pairs:
    print('mean=%1.2f, std=%1.2f, r=%1.2f' % (np.mean(y), np.std(y), np.corrcoef(x, y)[0][1]))

plt.show()


mean=7.50, std=1.94, r=0.82
mean=7.50, std=1.94, r=0.82
mean=7.50, std=1.94, r=0.82
mean=7.50, std=1.94, r=0.82

In [2]:
'''
=================================
3D surface with polar coordinates
=================================

Demonstrates plotting a surface defined in polar coordinates.
Uses the reversed version of the YlGnBu color map.
Also demonstrates writing axis labels with latex math mode.

Example contributed by Armin Moser.
'''

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create the mesh in polar coordinates and compute corresponding Z.
r = np.linspace(0, 1.25, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)
Z = ((R**2 - 1)**2)

# Express the mesh in the cartesian system.
X, Y = R*np.cos(P), R*np.sin(P)

# Plot the surface.
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)

# Tweak the limits and add latex math labels.
ax.set_zlim(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')

plt.show()

In [3]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

## See http://matplotlib.org/examples/showcase/xkcd.html

#if 1:
with plt.xkcd():
    # Based on "Stove Ownership" from XKCD by Randall Monroe
    # http://xkcd.com/418/

    fig = plt.figure()
    data = np.random.rand(10)
    plt.hist(data)
    
plt.show()


Further Visualization Techniques

Below, we will illustrate some other visualization techniques using the seaborn package.

pip install seaborn

In [1]:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import matplotlib.pyplot as plt

import seaborn as sns
sns.set(color_codes=True)

x = np.random.normal(size=64)


plt.figure(figsize=(16,6))
plt.subplot(2,2,1)
sns.distplot(x, kde=False, hist=True, bins=50, fit=stats.invgauss, rug=True);

plt.subplot(2,2,2)
sns.distplot(x, kde=False, rug=True, bins=30);



In [2]:
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
sns.jointplot(x="x", y="y", data=df);

plt.show()



In [7]:
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("white"):
    sns.jointplot(x=x, y=y, kind="hex", color="k");


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-18bfc00ea058> in <module>()
      1 x, y = np.random.multivariate_normal(mean, cov, 1000).T
----> 2 with sns.axes_style("white"):
      3     sns.jointplot(x=x, y=y, kind="hex", color="k");

NameError: name 'sns' is not defined

In [4]:
sns.jointplot(x="x", y="y", data=df, kind="kde");



In [5]:
f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df.x, df.y, ax=ax)
sns.rugplot(df.x, color="g", ax=ax)
sns.rugplot(df.y, vertical=True, ax=ax);



In [6]:
f, ax = plt.subplots(figsize=(6, 6))
cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True)
sns.kdeplot(df.x, df.y, cmap=cmap, n_levels=60, shade=True);



In [7]:
g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("$X$", "$Y$");



In [8]:
iris = sns.load_dataset("iris")
sns.pairplot(iris);



In [9]:
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=6);


/Users/cemgil/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.py:475: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
  warnings.warn("No labelled objects found. "

In [12]:
plt.get_backend()


Out[12]:
'module://ipykernel.pylab.backend_inline'

In [8]:
import numpy as np
import matplotlib.pyplot as plt


# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
          r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
          fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)

#plt.savefig('tex_demo')
plt.show()


HTML5 Animation example


In [16]:
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import animation, rc
from IPython.display import HTML

# equivalent to rcParams['animation.html'] = 'html5'
rc('animation', html='html5')

# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()

ax.set_xlim(( 0, 2))
ax.set_ylim((-2, 2))

line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return (line,)

# animation function. This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return (line,)

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=10, blit=True)



In [17]:
anim


Out[17]:

JS Animation Example


In [18]:
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
plt.rcParams["animation.html"] = "jshtml"


t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

from IPython.display import HTML
HTML(ani.to_jshtml())


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
    925             try:
--> 926                 cval = self.validate[key](val)
    927             except ValueError as ve:

/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/rcsetup.py in __call__(self, s)
     72         raise ValueError('Unrecognized %s string "%s": valid strings are %s'
---> 73                          % (self.key, s, list(six.itervalues(self.valid))))
     74 

ValueError: Unrecognized animation.html string "jshtml": valid strings are ['html5', 'none']

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-18-9d52b74a9a1e> in <module>()
      2 import matplotlib.animation
      3 import numpy as np
----> 4 plt.rcParams["animation.html"] = "jshtml"
      5 
      6 

/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
    926                 cval = self.validate[key](val)
    927             except ValueError as ve:
--> 928                 raise ValueError("Key %s: %s" % (key, str(ve)))
    929             dict.__setitem__(self, key, cval)
    930         except KeyError:

ValueError: Key animation.html: Unrecognized animation.html string "jshtml": valid strings are ['html5', 'none']

In [3]:
%matplotlib inline

#%matplotlib tkagg


# update a distribution based on new data.
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
from matplotlib.animation import FuncAnimation
plt.rcParams["animation.html"] = "jshtml"

class UpdateDist(object):
    def __init__(self, ax, prob=0.5):
        self.success = 0
        self.prob = prob
        self.line, = ax.plot([], [], 'k-')
        self.x = np.linspace(0, 1, 200)
        self.ax = ax

        # Set up plot parameters
        self.ax.set_xlim(0, 1)
        self.ax.set_ylim(0, 15)
        self.ax.grid(True)

        # This vertical line represents the theoretical value, to
        # which the plotted distribution should converge.
        self.ax.axvline(prob, linestyle='--', color='black')

    def init(self):
        self.success = 0
        self.line.set_data([], [])
        return self.line,

    def __call__(self, i):
        # This way the plot can continuously run and we just keep
        # watching new realizations of the process
        if i == 0:
            return self.init()

        # Choose success based on exceed a threshold with a uniform pick
        if np.random.rand(1,) < self.prob:
            self.success += 1
        y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1)
        self.line.set_data(self.x, y)
        return self.line,

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=200, init_func=ud.init,
        interval=100, blit=False)

from IPython.display import HTML
HTML(anim.to_jshtml())


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
    925             try:
--> 926                 cval = self.validate[key](val)
    927             except ValueError as ve:

/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/rcsetup.py in __call__(self, s)
     72         raise ValueError('Unrecognized %s string "%s": valid strings are %s'
---> 73                          % (self.key, s, list(six.itervalues(self.valid))))
     74 

ValueError: Unrecognized animation.html string "jshtml": valid strings are ['html5', 'none']

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-3-b05ee7f719bb> in <module>()
      9 import scipy.stats as ss
     10 from matplotlib.animation import FuncAnimation
---> 11 plt.rcParams["animation.html"] = "jshtml"
     12 
     13 class UpdateDist(object):

/Users/cemgil/anaconda/lib/python3.6/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
    926                 cval = self.validate[key](val)
    927             except ValueError as ve:
--> 928                 raise ValueError("Key %s: %s" % (key, str(ve)))
    929             dict.__setitem__(self, key, cval)
    930         except KeyError:

ValueError: Key animation.html: Unrecognized animation.html string "jshtml": valid strings are ['html5', 'none']

In [19]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

class ParticleAnimator(object):
    def __init__(self, N=1, plot_coords=False, gravity=0.008):
        fig = plt.figure(figsize=(7, 7))
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], frameon=True)
        ax.set_xlim(0, 1), ax.set_xticks([])
        ax.set_ylim(0, 1), ax.set_yticks([])
        
        self.fig = fig
        self.ax = ax
        self.N = N
        self.x = np.zeros((2,N))
        self.y = np.zeros((2,N))
        self.A = np.matrix('[1,0.25;0,1]')
        self.g = gravity
        self.plot_coords = plot_coords

    def reset_variables(self):
        self.x[0,:] = np.random.rand(1,self.N)
        self.x[1,:] = np.random.randn(1,self.N)/5
        self.y[0,:] = 0.9
        self.y[1,:] = 0

        # Particles
        #self.ln, = plt.plot(self.x[0,:], self.y[0,:], 'go')
        self.ln, = plt.plot([], [], 'go')

        # Lines from origin, x and y axes
        #self.ln2, = plt.plot([self.x[0,0], 0], [self.y[0,0], 0], '--')
        self.ln2, = plt.plot([], [], '--')

        self.lnx, = plt.plot([], [],'b--')
        self.lny, = plt.plot([], [], 'r--')
        
        return self.ln
    def __call__(self, frame_number):
        if frame_number==0:
            return self.reset_variables()
        self.x = self.A*self.x + np.matrix('[0;-1]')*np.random.randn(1)*0.0005
        self.y = self.A*self.y + np.matrix('[0;-1]')*self.g
        for i in range(self.N):
            if self.x[0,i]<0: 
                self.x[0,i]=0
                self.x[1,i]=-1.0*self.x[1,i]
            if self.x[0,i]>1:
                self.x[0,i] = 1
                self.x[1,i]=-1.0*self.x[1,i]
            if self.y[0,i]<0: 
                self.y[0,i]=0
                self.y[1,i]=-1.05*self.y[1,i]
            if self.y[0,i]>1:
                self.y[0,i] = 1
                self.y[1,i]=-0.2*self.y[1,i]

        
        self.ln.set_xdata(self.x[0,:].tolist()[0])
        self.ln.set_ydata(self.y[0,:].tolist()[0])

        if self.plot_coords:
            x0 = self.x[0,0]
            y0 = self.y[0,0]
            self.ln2.set_xdata([x0, 0])
            self.lnx.set_xdata([x0, x0])
            self.lny.set_xdata([0, x0 ])
            #	ln.set_ydata(y[0,:])
            self.ln2.set_ydata([y0, 0])
            self.lnx.set_ydata([0, y0])
            self.lny.set_ydata([y0, y0])
        self.fig.gca().set_title(frame_number)
        return self.ln        
        

# Number of particles to simulate

pa = ParticleAnimator(N=1, plot_coords=False, gravity=0.005)
anim_obj = FuncAnimation(pa.fig, pa, frames=200, interval=10)

from IPython.display import HTML
HTML(anim_obj.to_jshtml())


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-e99ef4910915> in <module>()
     81 
     82 from IPython.display import HTML
---> 83 HTML(anim_obj.to_jshtml())

AttributeError: 'FuncAnimation' object has no attribute 'to_jshtml'

In [6]:
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
from IPython.display import clear_output, display, HTML
from matplotlib import rc

import scipy as sc
import scipy.optimize as opt


def sigmoid(x):
    return 1/(1+np.exp(-x))

def inv_sigmoid(p=0.5):
    xs = opt.bisect(lambda x: sigmoid(x)-p, a=-100, b=100)
    return xs

def inv_sigmoid1D(w, b, p=0.5):
    xs = opt.bisect(lambda x: sigmoid(w*x+b)-p, a=-100, b=100)
    return xs
    
fig = plt.figure(figsize=(10,6))
ax = fig.gca()
ax.set_ylim([-0.1,1.1])
x = np.linspace(-10,10,100)
ax.set_xlim([-10,10])

ln = plt.Line2D(x, sigmoid(x))
ln2 = plt.axvline([0], ls= ':', color='k')
ln_left = plt.axvline([0], ls= ':', color='b')
ln_right = plt.axvline([0], ls= ':', color='r')

ax.add_line(ln)
plt.close(fig)
ax.set_xlabel('$x$')
ax.set_ylabel('$\sigma(wx + b)$')

def plot_fun(w, b):
    ln.set_ydata(sigmoid(w*x+b))
    if np.abs(w)>0.00001:
        ln2.set_xdata(inv_sigmoid1D(w,b,0.5))
        ln_left.set_xdata(inv_sigmoid1D(w,b,0.25))
        ln_right.set_xdata(inv_sigmoid1D(w,b,0.75))
    display(fig)
    
res = interact(plot_fun, w=(-3, 3, 0.1), b=(-10.0,10.0,0.1))



In [6]:
%pylab inline


Populating the interactive namespace from numpy and matplotlib

In [13]:
from tempfile import NamedTemporaryFile

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.
</video>"""

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")
    
    return VIDEO_TAG.format(anim._encoded_video)

In [11]:
from IPython.display import HTML

def display_animation(anim):
    plt.close(anim._fig)
    return HTML(anim_to_html(anim))

In [14]:
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=40, blit=True)

# call our new function to display the animation
display_animation(anim)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-4b45af5b2a05> in <module>()
     23 
     24 # call our new function to display the animation
---> 25 display_animation(anim)

<ipython-input-11-63a8cd04f4be> in display_animation(anim)
      3 def display_animation(anim):
      4     plt.close(anim._fig)
----> 5     return HTML(anim_to_html(anim))

<ipython-input-13-adbeb94273d0> in anim_to_html(anim)
     11             anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
     12             video = open(f.name, "rb").read()
---> 13         anim._encoded_video = video.encode("base64")
     14 
     15     return VIDEO_TAG.format(anim._encoded_video)

AttributeError: 'bytes' object has no attribute 'encode'

In [15]:
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2,marker='o')

N = 10
global x
global y
x = np.random.rand(N)*2 - 1
y = np.random.rand(N)*2 - 1

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    global x,y
    x = x + 0.01*np.random.randn(N)
    y = y + 0.01*np.random.randn(N)
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim2 = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=40, blit=True)

# call our new function to display the animation
display_animation(anim2)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-b653903478ac> in <module>()
     30 
     31 # call our new function to display the animation
---> 32 display_animation(anim2)

<ipython-input-11-63a8cd04f4be> in display_animation(anim)
      3 def display_animation(anim):
      4     plt.close(anim._fig)
----> 5     return HTML(anim_to_html(anim))

<ipython-input-13-adbeb94273d0> in anim_to_html(anim)
     11             anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
     12             video = open(f.name, "rb").read()
---> 13         anim._encoded_video = video.encode("base64")
     14 
     15     return VIDEO_TAG.format(anim._encoded_video)

AttributeError: 'bytes' object has no attribute 'encode'

In [9]:
"""
===========================
Plots with different scales
===========================

Demonstrate how to do two plots on the same axes with different left and
right scales.

The trick is to use *two different axes* that share the same *x* axis.
You can use separate `matplotlib.ticker` formatters and locators as
desired since the two axes are independent.

Such axes are generated by calling the `Axes.twinx` method.  Likewise,
`Axes.twiny` is available to generate axes that share a *y* axis but
have different top and bottom scales.

The twinx and twiny methods are also exposed as pyplot functions.

"""

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = np.sin(2 * np.pi * t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
ax2.tick_params('y', colors='r')

fig.tight_layout()
plt.show()



In [10]:
"""
===============
Watermark image
===============

Use a PNG file as a watermark
"""
from __future__ import print_function
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.pyplot as plt

datafile ='data/boun_logo.png'
print('loading %s' % datafile)
im = image.imread(datafile)
im[:, :, -1] = 0.03  # set the alpha channel

fig, ax = plt.subplots()

ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()
fig.figimage(im, 0, 0, zorder=3, resize=True)

plt.show()


loading data/boun_logo.png

In [11]:
"""
===========================================
Changing colors of lines intersecting a box
===========================================

The lines intersecting the rectangle are colored in red, while the others
are left as blue lines. This example showcases the `intersect_bbox` function.

"""

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.path import Path

left, bottom, width, height = (1, -1, 2, 2)
rect = plt.Rectangle((left, bottom), width, height, facecolor="#aaaaaa")

fig, ax = plt.subplots()
ax.add_patch(rect)

bbox = Bbox.from_bounds(left, bottom, width, height)

for i in range(12):
    vertices = (np.random.random((2, 2)) - 0.5) * 6.0
    path = Path(vertices)
    if path.intersects_bbox(bbox):
        color = 'r'
    else:
        color = 'b'
    ax.plot(vertices[:, 0], vertices[:, 1], color=color)

plt.show()