Пример #1
0
def cohere():
    """
    Compute the coherence of two signals
    mpl_examples/pylab_examples/cohere_demo.py
    """
    import numpy as np
    from smartplotlib import xyplot, subplot, alias


    # make a little extra space between the subplots

    dt = 0.01
    t = np.arange(0, 30, dt)
    nse1 = np.random.randn(len(t))                 # white noise 1
    nse2 = np.random.randn(len(t))                 # white noise 2
    r = np.exp(-t/0.05)

    cnse1 = np.convolve(nse1, r, mode='same')*dt   # colored noise 1
    cnse2 = np.convolve(nse2, r, mode='same')*dt   # colored noise 2

    # two signals with a coherent part and a random part
    s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1
    s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2

    ps1 = xyplot(t, s1, fmt='b-', y2= s2, fmt2="g-",
                 axes=211, xlabel="time", ylabel="s1 & s2")

    ps1.go("fclear", "axes", "plot")

    c = xyplot.cohere(s1, s2, 256, 1./dt,
                      ylabel="coherence", axes=212)

    c.go("axes", "plot", "draw", "show")
    return c
Пример #2
0
def annotates():
    import numpy as np
    from smartplotlib import xyplot, cycle
    n=10
    x = np.arange(n)
    y = x*x
    dy = ([10,-15]*(int(n/2)+1))[:n]
    print (dy)

    xy = xyplot(x, y, marker="*", dx=0.1, dy=dy,
                arrowprops=dict(width=2), axes=211,
                ylim=(-20,100), xlim=(-1,10)
                )
    xy.go("fclear", "axes", "plot", "annotates")

    # or an other fancy way to cycle is to use the iter method
    xy.plot(axes=212)
    xy.axes(axes=212)
    ans = [a() for a in  xyplot.annotates.iter(len(x), x=x, y=y,
                                              texts=list("abcdefghijklmnopqrstuvwxyz"),
                                              dx=0.0,
                                              dy=[10,-10], axes=212)
           ]
    xy.go("show", "draw")
    return xy
Пример #3
0
def psd():
    import numpy as np
    from smartplotlib import xyplot, alias
    Fs = 150.0;  # sampling rate
    Ts = 1.0/Fs; # sampling interval
    t = np.arange(0,1,Ts) # time vector

    noises = np.zeros( (len(t),), dtype=float )
    for a,f in zip([1e-2,2e-2,0.5e-2,1e-3],[20,40,60,80]):
        noises += np.sin(2*np.pi*f*t)*a
    ff = 5;   # frequency of the signal
    y = np.sin(2*np.pi*ff*t)+noises
    xy = xyplot(t, y, xlabel="time", ylabel="Signal",
                axes=211, hspace=0.4)


    xy.go("fclear", "fset", "axes", "plot")
    psd = xy.ydata.psd(axes=212, Fs=Fs)
    psd.axvline([5, 20,40,60,80], color="red", linestyle="--")
    ###
    # psd is plotted in 10*log10(psd) ('dB/Hz' or dB)
    # one may want to plot the linear scale
    # that easy :
    #    psd.plot(y=alias("psd"))

    psd.go("axes", "plot")

    xy.go("show", "draw")
    return psd
Пример #4
0
def xbinedstat():
    import numpy as np
    from smartplotlib import xyplot

    N=10000
    x = np.linspace(0, 2, N)
    yerr = np.random.rand(N)*np.exp(x)*np.sign(np.random.rand(N)-0.5)
    y = 5+yerr
    xy = xyplot(y, x, fmt="k+")

    xy.go("fclear", "axes", "plot")


    stat = xy.xdata.binedstat.derive(linestyle="-", direction="x")
    ## itertcall iter on iterable and call the instances
    ps = [s.plot() for s in stat.itercall(fstat=["-std", "+std", "mean", "median"],
                                          color=list("rrgb"))]

    xy.go("show", "draw")
    return ps


    import numpy as np
    from smartplotlib import xyplot

    N=10000
    x = np.linspace(0, 2, N)
    yerr = np.random.rand(N)*np.exp(x)*np.sign(np.random.rand(N)-0.5)
    y = 5+yerr
    xy = xyplot(y, x, marker="+", color="k")

    xy.go("fclear", "axes", "plot")

    ## itertcall iter on iterable and call the instances
    s, m = xy.xbinedstat.itercall(fstat=["std","mean"],color=["red", "blue"])
    s.plot(linestyle="-")
    m.errorbar(linestyle="-", marker="None")

    xy.go("show", "draw")
    return xy
Пример #5
0
def histogram2d():
    from matplotlib.colors import LogNorm
    from smartplotlib import xyplot
    import numpy as np
    from pylab import randn

    #normal distribution center at x=0 and y=5
    x = randn(100000)
    y = randn(100000)+5
    xy = xyplot(x, y)
    xy.fclear()
    h = xy.histogram2d( bins=40, norm=LogNorm())

    pc = h.pcolorfast()
    h.colorbar(pc)
    h.contour(colors="k", contours=[10,300,700,900])
    h.go("show", "draw")
    return h
Пример #6
0
def binedstat():
    import numpy as np
    from smartplotlib import xyplot

    N=10000
    x = np.linspace(0, 2, N)
    yerr = np.random.rand(N)*np.exp(x)*np.sign(np.random.rand(N)-0.5)
    y = 5+yerr
    xy = xyplot(x, y, fmt="k+", axes=211)

    xy.go("fclear", "axes", "plot")

    stat = xy.ydata.binedstat.derive(linestyle="-")


    sp = stat(fstat="+std", color="red")
    sp.step()
    ## call sp.binedstat to enable the fill_between
    ## count = 0 is necessary here to have both lines sharing the same x
    ## otherwhis they will be shifted (for histogram purpose)
    sm = sp.binedstat(fstat="-std", color="red", count=0)
    sm.step()
    ## can fill between the last two calls
    sm.fill_between(alpha=0.3)

    m  = stat(fstat="mean", color="b")
    m.plot()

    m.errorbar(linestyle="-", marker="None")

    std = stat(axes=212, fstat="std", ylabel="Std",
               linestyle="solid", label="bined std")
    std.go("axes","fill")
    ##
    # fit a polynome on the newly created standar deviation
    # histogram. label=True mean that result of the fit is plotted
    # as label
    std.polyfit(dim=2, label=True).plot(fmt="r-")
    std.legend(loc="upper left")
    xy.go("show", "draw")
    return stat
Пример #7
0
def spectrum():
    """ example of magnitude_spectrum, angle_spectrum and phase_spectrum
    with smartplotlib
    """
    import numpy as np
    from smartplotlib import xyplot, subplot

    ###
    # make some data
    Fs = 150.0;  # sampling rate
    Ts = 1.0/Fs; # sampling interval
    t = np.arange(0,1,Ts) # time vector

    ff = 5;   # frequency of the signal
    y = np.sin(2*np.pi*ff*t)

    ###
    # make an new instance of xyplot with the data
    xy = xyplot(t, y, xlabel="time", ylabel="Signal", axes=311)
    ###
    ###
    # plot the original data
    xy.go("fclear", "axes", "plot")

    ###
    # xy.ydata is a dataplot from whish data is aliased to "y"
    # a dataplot contain a collection of plot that can be obtain
    # from a 1d data
    m = xy.ydata.magnitude_spectrum(axes=312,
                                    #
                                    )
    a = xy.ydata.angle_spectrum(axes=313,
                                sharex=311 # note the sharex
                               )
    p = xy.ydata.phase_spectrum(axes=313, color="red")

    a.go("axes", "plot")
    p.plot() # p is on same axes than a no need to make axes
    m.go("axes", "plot", "draw", "show")

    return m
Пример #8
0
def specgram():
    """ smartplotlib example of specgram """
    from pylab import np, pi, sin, arange, logical_and, where, randn, cm
    from smartplotlib import xyplot, subplot


    dt = 0.0005
    t = arange(0.0, 20.0, dt)
    s1 = sin(2*pi*100*t)
    s2 = 2*sin(2*pi*400*t)

    # create a transient "chirp"
    mask = where(logical_and(t>10, t<12), 1.0, 0.0)
    s2 = s2 * mask

    # add some noise into the mix
    nse = 0.01*randn(len(t))

    x = s1 + s2 + nse # the signal
    NFFT = 1024       # the length of the windowing segments
    Fs = int(1.0/dt)  # the sampling frequency

    # Pxx is the segments x freqs array of instantaneous power, freqs is
    # the frequency vector, bins are the centers of the time bins in which
    # the power is computed, and im is the matplotlib.image.AxesImage
    # instance

    xy = xyplot(t, x, axes=211, xlabel="t", ylabel="x")

    ###
    # xy.ydata is a dataplot from whish data is aliased to "y"
    # a dataplot contain a collection of plot that can be obtain
    # from a 1d data
    spec = xy.ydata.specgram(NFFT=NFFT, Fs=Fs, noverlap=900,
                             cmap=cm.gist_heat, axes=212)
    xy.fclear()
    xy.axes()
    xy.plot()
    # above is same as xy.go("fclear", "axes", "plot")
    spec.go("axes", "imshow", "show", "axes", "draw")
    return spec
Пример #9
0
def polyfit():

    from smartplotlib import xyplot
    import numpy as np

    x = np.arange(100);
    yerr = np.random.rand(100)*2.0*x
    y = x*x + yerr

    xyplot.fclear()

    # make a new xyplot with my data
    xy = xyplot(x,y, yerr=yerr, xlabel="t [s]")

    # plot the data with errobar
    xy.errorbar(linestyle="None", label="data")

    # fit a polynome and plot it
    # note that color and linestyle can also be in .plot
    xy.polyfit(dim=2, color="red", linestyle="--", label=True).plot()

    # fit a tangent to a xrange
    # by default plot only for the given range
    # so we need to make it a bit longer with xmin and xmax
    # also xmin and xmax can be True, that mean, min and max of data
    # not range
    plf = xy.polyfit(dim=1, xrange=(55,65),  color="green",
                     xmin=35, xmax=90,
                     linestyle="--", label="tangent @ 55<x<65").plot()

    ##
    # other method can be done with the go method
    # here. axes plot, set the axes labels etc ..., legend plot
    # the legend,  than show and draw are figure.show() and figure.canvas.draw()
    xy.go("axes", "legend", "show", "draw")
    return plf