def plot_motion_field_streamplot(UV, geodata=None):
    """Function to plot a precipitation field witha a colorbar. 
    
    Parameters 
    ---------- 
    UV : array-like 
        Array of shape (2, m,n) containing the input motion field.
    geodata : dictionary
        
    step : int
    
    Returns: 
    ----------
    ax : fig axes
        Figure axes. Needed if one wants to add e.g. text inside the plot.
    
    """

    # prepare X Y coordinates
    if geodata is not None:
        x = np.arange(geodata['x1'] / 1000, geodata['x2'] / 1000)
        y = np.arange(geodata['y1'] / 1000, geodata['y2'] / 1000)
    else:
        x = np.arange(UV.shape[2])
        y = np.arange(UV.shape[1])

    plt.streamplot(x, y, UV[0, :, :], -UV[1, :, :], density=2, color='black')

    axes = plt.gca()

    if geodata is None:
        axes.xaxis.set_ticklabels([])
        axes.yaxis.set_ticklabels([])

    return axes
Beispiel #2
0
    def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'):
        outdir = self.set_dir(outdir)
        p = 64
        if F is None: F=self.calc_F(u,v)

        plt.close('all')
        plt.figure()
        #fig, axes = plt.subplots(nrows=1)
        if contour:
            plt.hold(True)
            plt.contourf(x,y,F)
        if plot=='quiver':
            plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1)
        
        if plot=='pcolor':
            plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1)
            plt.colorbar()

        if plot=='stream':
            speed = F[::16]
            plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k')

        plt.xlabel('$x$ (a.u.)')
        plt.ylabel('$y$ (a.u.)')
        
        plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight')
        plt.close()
Beispiel #3
0
def streamplot(UV, geodata=None, **kwargs):
    """Function to plot a motion field as streamlines. 
    
    Parameters 
    ---------- 
    UV : array-like 
        Array of shape (2, m,n) containing the input motion field.
    geodata : dictionary
        Optional dictionary containing geographical information about the field. 
        If geodata is not None, it must contain the following key-value pairs:
        
        x1           x-coordinate of the lower-left corner of the data raster (meters)
        y1           y-coordinate of the lower-left corner of the data raster (meters)
        x2           x-coordinate of the upper-right corner of the data raster (meters)
        y2           y-coordinate of the upper-right corner of the data raster (meters)
        yorigin      a string specifying the location of the first element in
                     the data raster w.r.t. y-axis:
                     'upper' = upper border
                     'lower' = lower border
                     
    Optional kwargs
    ---------------    
    density : float
        Controls the closeness of streamlines.
        Default : 1.5
    color : string
        Optional streamline color. This is a synonym for the PolyCollection 
        facecolor kwarg in matplotlib.collections.
        Default : black
    
    Returns: 
    ----------
    ax : fig axes
        Figure axes. Needed if one wants to add e.g. text inside the plot.
    
    """
    
    # defaults
    density     = kwargs.get("density", 1.5)
    color       = kwargs.get("color", "black")
    
    # prepare x y coordinates
    if geodata is not None:
        x = np.linspace(geodata['x1']/geodata["xpixelsize"], geodata['x2']/geodata["xpixelsize"], UV.shape[2])
        y = np.linspace(geodata['y1']/geodata["ypixelsize"], geodata['y2']/geodata["ypixelsize"], UV.shape[1])
    else:
        x = np.arange(UV.shape[2])
        y = np.arange(UV.shape[1],0,-1)
    
    plt.streamplot(x, np.flipud(y), UV[0,:,:], -UV[1,:,:], density=density, 
                   color=color)
    
    axes = plt.gca()
    
    if geodata is None:
        axes.xaxis.set_ticklabels([])
        axes.yaxis.set_ticklabels([])
   
    return axes
Beispiel #4
0
def plot_streamline(x,y,u,v,outdir='./',outname='field_stream',format='eps'):
    if not os.path.exists(outdir): os.makedirs(outdir)
    speed = np.sqrt(u**2+v**2)
    plt.close('all')
    plt.figure()
    plt.streamplot(x, y, u, v, color=speed,linewidth=5*speed/speed.max(),cmap=plt.cm.jet)
    plt.savefig(os.path.join(outdir,outname+'.'+format),format=format,dpi=320,bbox_inches='tight')
    plt.close()
    return
def potential(x_axis,
              y_axis,
              cbar,
              x_label,
              y_label,
              cbar_label,
              int_pol,
              colorMap,
              xmin=None,
              xmax=None,
              ymin=None,
              ymax=None,
              plot=None):
    """A general plotter allowing for the plotting of a heatmap(primarily used
       here for potential function) which takes in relevant data about the
       graph. It also allows for the option of overlaying either a quiver or a
       streamline plot, or not!

    Parameters:
    x_axis, y_axis : The corresponding x and y axis data lists of a plot
    cbar: The heatmap list data which usually corresponds to x and y axis
    x_label, y_label, : The x, y and z label of the graph       dtype = string
    cbar_label : The colourbar label                            dtype = string
    int_pol: The colour interpolation of the heatmap            dtype = integer
    colorMap: The style and colour of heatmap                   dtype = string
    xmin, xmax: The minimum and maximum value of the x-axis
    ymin, ymax: The minimum and maximum value of the y-axis
    plot: "quiver", "stream" allowing for the overlay of quiver or streamline
          plot

    Returns:
    Image : AxesImage
    """
    plt.contourf(x_axis, y_axis, cbar, int_pol, cmap=colorMap)
    cbar_tag = plt.colorbar()
    Z = cbar
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    cbar_tag.set_label(cbar_label, rotation=270)
    cbar_tag.set_clim(-1000.0, 1000.0)
    E = np.gradient(Z)
    E = E / np.sqrt(E[0]**2 + E[1]**2)
    if plot is not None:
        if plot == "quiver":
            print("\nQuiver plot:")
            plt.quiver(x_axis, y_axis, E[1], E[0])
        if plot == "stream":
            print("\nStreamline Plot:")
            plt.streamplot(x_axis, y_axis, -E[1], -E[0], color='black')
    if xmin is not None and xmax is not None:
        plt.xlim(xmin, xmax)
    if ymin is not None and ymax is not None:
        plt.ylim(ymin, ymax)
    plt.show()
Beispiel #6
0
    def plot_field(self,
                   x,
                   y,
                   u=None,
                   v=None,
                   F=None,
                   contour=False,
                   outdir=None,
                   plot='quiver',
                   figname='_field',
                   format='eps'):
        outdir = self.set_dir(outdir)
        p = 64
        if F is None: F = self.calc_F(u, v)

        plt.close('all')
        plt.figure()
        #fig, axes = plt.subplots(nrows=1)
        if contour:
            plt.hold(True)
            plt.contourf(x, y, F)
        if plot == 'quiver':
            plt.quiver(x[::p], y[::p], u[::p], v[::p], scale=0.1)

        if plot == 'pcolor':
            plt.pcolormesh(x[::4], y[::4], F[::4], cmap=plt.cm.Pastel1)
            plt.colorbar()

        if plot == 'stream':
            speed = F[::16]
            plt.streamplot(x[::16],
                           y[::16],
                           u[::16],
                           v[::16],
                           density=(1, 1),
                           color='k')

        plt.xlabel('$x$ (a.u.)')
        plt.ylabel('$y$ (a.u.)')

        plt.savefig(os.path.join(outdir, figname + '.' + format),
                    format=format,
                    dpi=320,
                    bbox_inches='tight')
        plt.close()
Beispiel #7
0
def plot_streamline(x,
                    y,
                    u,
                    v,
                    outdir='./',
                    outname='field_stream',
                    format='eps'):
    if not os.path.exists(outdir): os.makedirs(outdir)
    speed = np.sqrt(u**2 + v**2)
    plt.close('all')
    plt.figure()
    plt.streamplot(x,
                   y,
                   u,
                   v,
                   color=speed,
                   linewidth=5 * speed / speed.max(),
                   cmap=plt.cm.jet)
    plt.savefig(os.path.join(outdir, outname + '.' + format),
                format=format,
                dpi=320,
                bbox_inches='tight')
    plt.close()
    return
Beispiel #8
0
import matplotlib.pylab as plt
import numpy as np
from math import sqrt, cos, sin, log, exp, pi

w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = X**2 + Y**2
V = X**2 - Y**2
speed = np.sqrt(U**2 + V**2)
lw = 5 * speed / speed.max()
p = plt.figure(figsize=(14, 14), facecolor='black', dpi=400)
p = plt.axis('off')
plt.streamplot(X,
               Y,
               U,
               V,
               density=[2, 2],
               arrowsize=1,
               cmap='summer',
               color=U,
               linewidth=lw**0.85,
               arrowstyle='fancy')

p = plt.savefig(f'C:/Users/Alejandro/Pictures/RandomPlots/03052020.PNG',
                facecolor='black')
Beispiel #9
0
    # Plot weighting field directions
    E_x, E_y = get_weighting_field(xx,
                                   yy,
                                   D=thickness,
                                   S=width,
                                   is_planar=True)

    # Indexing is different here (mixing array indexing and cartesian coordinates)
    # Similar issue: http://stackoverflow.com/questions/22568256/2d-quiver-plot-matplotlib-and-matlab-output-doesnt-match
    E_y_2, E_x_2 = np.gradient(-phi_w, np.gradient(y), np.gradient(x))

    plt.streamplot(x,
                   y,
                   E_x_2,
                   E_y_2,
                   density=1.0,
                   color='black',
                   arrowstyle='->')
    plt.streamplot(x, y, E_x, E_y, density=1.0, color='gray', arrowstyle='->')

    plt.title(
        'Weighting potential and weighting field direction (planar sensor)')
    plt.xlabel('Position [um]')
    plt.ylabel('Depth [um]')

    #     print np.where(np.logical_or(E_x - E_x_2 > 0.1, E_y - E_y_2 > 0.1))
    #     print E_x[np.where(E_x - E_x_2 == (E_x - E_x_2).max())], E_x_2[np.where(E_x - E_x_2 == (E_x - E_x_2).max())], x[0], y[75]
    #     plt.savefig('WeightingField_planar.pdf', layout='tight')

    xs, ys = [], []
Beispiel #10
0
import numpy as np
import matplotlib.pylab as plt
Sol=np.genfromtxt('campo.txt')
potencial=Sol[:513,:]
Ex=Sol[513:2*513,:]
Ey=Sol[2*513:,:]
plt.imshow(potencial,cmap=plt.cm.inferno,extent=(-2.5, 2.5, -2.5,2.5))
x=np.linspace(-2.5,2.5,513)
y=np.linspace(-2.5,2.5,513)
X,Y = np.meshgrid(x, y)
color = 2 * np.log(np.hypot(Ex, Ey))
plt.streamplot(X,Y,Ex,Ey, color=color,  linewidth=0.5, cmap=plt.cm.inferno,
               density=2, arrowstyle='->', arrowsize=1)
plt.savefig('placas.pdf')
Beispiel #11
0
    if keep == "n":
        break
"""
    As posições do gráfico são referentes as posiçoes das cargas deixadas pelo usuário
    O mínimo no eixo x é o valor mínimo que uma carga se situa no eixo x menos 1, assim como no eixo y
    O mesmo se aplica para o valor máximo para ambos os eixos
"""
x0, x1 = min([c.position[0]
              for c in cargas]) - 1, max([c.position[0] for c in cargas]) + 1
y0, y1 = min([c.position[1]
              for c in cargas]) - 1, max([c.position[1] for c in cargas]) + 1

# Funções referentes à criação de matrizes para as pposições de linhas de campo
x = np.linspace(x0, x1, 64)
y = np.linspace(y0, y1, 64)
x, y = np.meshgrid(x, y)

# Cálculo das cargas e plotagem no gráfico
Ex, Ey = E_total(x, y, cargas).get_campos_eixos()
color = 2 * np.log(np.hypot(Ex, Ey))
plt.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno)

# Posicionamento das cargas pontuais no Gráfico
for C in cargas:
    if C.load > 0:
        plt.plot(C.position[0], C.position[1], 'bo', ms=8 * np.sqrt(C.load))
    if C.load < 0:
        plt.plot(C.position[0], C.position[1], 'ro', ms=8 * np.sqrt(-C.load))

plt.show()
Beispiel #12
0
ax = pl.subplot(111)
print ax.axis()

grid = pl.grid()
poly = pl.Polygon([(0, 0), (xReg[1], 0), (xReg[1], -xReg[1] / 9 * 12.)], color='k', alpha=0.2)
ax.add_patch(poly)
poly = pl.Polygon([(0, 0), (xReg[0], -xReg[0] * 4), (xReg[0], yReg[0]), (xReg[1], -xReg[1] * 2.)], color='k', alpha=0.4)
ax.add_patch(poly)

pl.plot(XPlus, XPlus / 9 * (-12.), 'k--')
pl.plot(XPlus, XPlus * 0, 'k--')
pl.plot(XPlus, -XPlus * 2, 'k--')
pl.plot(XMinus, -XMinus * 4, 'k--')
pl.axis([xReg[0], xReg[1], yReg[0], yReg[1]])
#pl.streamplot(X, Y, U, V, color=speed)
pl.streamplot(X, Y, U, V, color='k')
#pl.colorbar()
pl.plot([0], [0], 'wo', ms=8)
pl.plot([3. / 7, 9. / 11], [0, -12. / 11], 'ko', ms=8)
pl.plot([12. / 17], [-12. / 17], 'kD', ms=8)
annotationSize = 15
ax.annotate('O', xy=(0, 0.), size=annotationSize, xycoords='data',
            xytext=( 0.03, 0.1), textcoords='data',
            bbox=dict(boxstyle="round", fc='1.'))
ax.annotate('A', xy=(3. / 7, 0.), size=annotationSize, xycoords='data',
            xytext=(3. / 7 + 0.03, 0.1), textcoords='data',
            bbox=dict(boxstyle="round", fc='1.'))
ax.annotate('B', xy=(12. / 17, -12. / 17), size=annotationSize, xycoords='data',
            xytext=(12. / 17 + 0.03, -12. / 17 + 0.1), textcoords='data',
            bbox=dict(boxstyle="round", fc='1.'))
ax.annotate('C', xy=(9. / 11, -12. / 11), size=annotationSize, xycoords='data',
Beispiel #13
0
def plot_memb_current_for_cell(time_pt,
                               params,
                               plot_morpho=False,
                               plot_field=True,
                               plot_synapses=False,
                               plot_current=False,
                               ax=None):

    # this is used for frames of the movie

    v_ext, xx, yy, seg_coords, x_range, y_range, dt = params
    #v_ext, xx, yy, seg_coords, x_range, y_range, inh_syn_coords, exc_syn_coords, dt = params

    max_field = np.max(v_ext)
    if max_field >= 1000:
        # convert to microvolts
        v_ext = v_ext / 10e2  # change to microvolts
        scale_type = 'micro'
        max_field /= 10e2
    else:
        scale_type = 'nano'

    #v_ext = v_ext / 10e2 # change nano to micro volts
    import matplotlib.colors as colors

    if ax == None:
        ax = plt.subplot(1, 1, 1)

    # draw field
    mycmap, colormap_range_ceil, aspect, one_forth_colormap, colormap_range = helper_provide_imshow_details(
        v_ext, x_range, y_range)

    if plot_field:
        pcm = plt.imshow(
            v_ext[time_pt, :, :],
            interpolation="nearest",
            #norm=colors.SymLogNorm(linthresh=0.01 * np.max(v_ext),
            #                       linscale=1.0,
            #                       vmin=colormap_range_ceil[0], vmax=colormap_range_ceil[1]),
            origin='lower',
            aspect=0.8,
            extent=(x_range[0], x_range[1], y_range[0], y_range[1]),
            cmap=mycmap)
        plt.clim(colormap_range[0], colormap_range[1])

    if plot_morpho:
        # draw morpho
        import pdb
        pdb.set_trace()
        col = graph.plot_neuron(seg_coords, colors='k', autolim=True)

        soma_idcs, = np.where(seg_coords['name'] == 'soma')

        draw_soma(ax,
                  x0=seg_coords[soma_idcs[0]]['x0'],
                  x1=seg_coords[soma_idcs[-1]]['x1'],
                  y0=seg_coords[soma_idcs[0]]['y0'],
                  y1=seg_coords[soma_idcs[-1]]['y1'],
                  color='k')
        plt.xlim(x_range)
        plt.ylim(y_range)

    x_tic_label, xtics, y_tic_label, ytics = helper_define_tick_space(
        x_range, y_range)
    ax.set_yticks(ytics)
    ax.set_yticklabels(y_tic_label)
    ax.set_xticks(xtics)
    ax.set_xticklabels(x_tic_label)

    if plot_field:
        cbar = plt.colorbar(pcm, extend='both', drawedges=False)  # ax=ax[0],
        cbar.set_ticks([
            colormap_range[0], -one_forth_colormap, 0, one_forth_colormap,
            colormap_range[1]
        ])
        cbar.set_ticklabels([
            str(colormap_range[0]),
            str(-one_forth_colormap), '0',
            str(one_forth_colormap), colormap_range[1]
        ])

    if scale_type == 'micro':
        cbar.set_label(r"voltage ($\mu$V)", fontsize=18)
    elif scale_type == 'nano':
        cbar.set_label(r"voltage (nV)", fontsize=18)

#cbar.set_label(r"voltage ($\mu$V)", fontsize=18)
#cbar.set_label(r"voltage (nV)", fontsize=18)
    cbar.ax.tick_params(labelsize=16)

    if plot_current:
        # draw streamplots
        U = -np.diff(v_ext[time_pt, :, :], axis=0)[:, :-1]
        V = -np.diff(v_ext[time_pt, :, :], axis=1)[:-1, :]

        plt.streamplot(xx[0, :-1], yy[:-1, 0], V, U, density=1.0, color='g')

    plt.title('time: ' + str(("%0.2f" % (time_pt * dt))) + 'ms')

    ax.set_xlabel(r"space ($\mu$m)")
    ax.set_ylabel(r"space ($\mu$m)")

    clean_plot(ax)
    plt.tight_layout()
    return mycmap, colormap_range