Ejemplo n.º 1
0
def polygon(i, j, m, n, x, y, k=0, col='black'):
    if k == 1:
        return pylab.Polygon([(j * m / (x + 2), -n / (y + 2) * i),
                              ((j + 1) * m / (x + 2), -n / (y + 2) * i),
                              ((j + 1) * m / (x + 2), -n / (y + 2) * (i + 1)),
                              (j * m / (x + 2), -n / (y + 2) * (i + 1))],
                             color=col)
    else:
        return pylab.Polygon([((j + 1) * m / (x + 2), -n / (y + 2) * (i + 1)),
                              ((j + 2) * m / (x + 2), -n / (y + 2) * (i + 1)),
                              ((j + 2) * m / (x + 2), -n / (y + 2) * (i + 2)),
                              ((j + 1) * m / (x + 2), -n / (y + 2) * (i + 2))],
                             color=col)
Ejemplo n.º 2
0
    def rectangle(self,
                  lon1,
                  lat1,
                  lon2,
                  lat2,
                  c='0.3',
                  shading=None,
                  step=100):
        """Draw a projection correct rectangle on the map."""
        class pos:
            x = np.array([])
            y = np.array([])

        def line(lons, lats):
            x, y = self(lons, lats)
            self.plot(x, y, c=c)
            pos.x = np.hstack((pos.x, x))
            pos.y = np.hstack((pos.y, y))

        line([lon1] * step, np.linspace(lat1, lat2, step))
        line(np.linspace(lon1, lon2, step), [lat1] * step)
        line([lon2] * step, np.linspace(lat2, lat1, step))
        line(np.linspace(lon2, lon1, step), [lat2] * step)
        if shading:
            p = pl.Polygon(list(zip(pos.x, pos.y)),
                           facecolor=shading,
                           edgecolor=c,
                           alpha=0.5,
                           linewidth=1)
            pl.gca().add_patch(p)
Ejemplo n.º 3
0
def rbox(ax, data, **keywords):
    """
    Create a ggplot2 style boxplot, is eqivalent to calling ax.boxplot
    with the following additions:

    Keyword arguments:
    colors -- array-like collection of colours for box fills
    names -- array-like collection of box names which are passed on as
    tick labels
    """
    hasColors = 'colors' in keywords
    if hasColors:
        colors = keywords['colors']
        keywords.pop('colors')

    if 'names' in keywords:
        ax.tickNames = plt.setp(ax, xticklabels=keywords['names'])
        keywords.pop('names')

    bp = ax.boxplot(data, **keywords)
    pylab.setp(bp['boxes'], color='black')
    pylab.setp(bp['whiskers'], color='black', linestyle='solid')
    pylab.setp(bp['fliers'], color='black', alpha=.9, marker='o', markersize=3)
    pylab.setp(bp['medians'], color='black')

    numBoxes = len(data)
    for i in range(numBoxes):
        box = bp['boxes'][i]
        boxX = []
        boxY = []
        for j in range(5):
            boxX.append(box.get_xdata()[j])
            boxY.append(box.get_ydata()[j])
        boxCoords = zip(boxX, boxY)

        if hasColors:
            boxPolygon = pylab.Polygon(boxCoords,
                                       facecolor=colors[i % len(colors)])
        else:
            boxPolygon = pylab.Polygon(boxCoords, facecolor='0.95')

        ax.add_patch(boxPolygon)
    return bp
Ejemplo n.º 4
0
 def draw(self, axes, figure, color):
     poly = plt.Polygon(zip(self.xcoords, self.ycoords))
     poly.set_linewidth(1)
     poly.set_alpha(1)
     poly.set_edgecolor(color)
     poly.set_facecolor('none')
     poly.set_hatch('//')
     patch = axes.add_patch(poly)
     figure.canvas.draw()
     return patch
def draw_static_geo(ax_xy, ax_yz, ax_xz):
    Np, ro, tfinal, x_lim, y_lim, z_lim, xi_lim, yi_lim, zi_lim = time_pos_ax_limits(
    )
    py.gcf().sca(ax_xy)
    substrate_xy = py.Rectangle((x_lim[0], y_lim[0]), (x_lim[1] - x_lim[0]),
                                (y_lim[1] - y_lim[0]),
                                fc=cl_lgrey)
    py.gca().add_patch(substrate_xy)
    for kk in range(-2, 3):
        rectangle = py.Rectangle(
            (x_lim[0] / 2, -elec_width / 2 + kk * elec_spacing),
            x_lim[1],
            elec_width,
            fc=cl_royal_blue)
        py.gca().add_patch(rectangle)
        # ax.add_patch(rectangle)

    py.gcf().sca(ax_yz)
    substrate_yz = py.Rectangle((y_lim[0], z_lim[0]), (x_lim[1] - x_lim[0]),
                                abs(z_lim[0]),
                                fc=cl_dgrey,
                                ec='k')
    py.gca().add_patch(substrate_yz)

    py.gcf().sca(ax_xz)
    substrate_xz = py.Rectangle((x_lim[0], z_lim[0]), (x_lim[1] - x_lim[0]),
                                abs(z_lim[0]),
                                fc=cl_dgrey,
                                ec='k')
    py.gca().add_patch(substrate_xz)

    # Draw fluidic/reflecting geometries
    py.gcf().sca(ax_xy)
    w_type = geo_element_types()

    # Loop over all types of geometry segments
    for wt in range(w_type.shape[0]):

        fname = 'geo_points' + str(
            w_type[wt]) + '()'  # name of the corresponding geometry function

        # Evaluate geo_points*()function by string name
        p_w, z_w = eval(fname)

        Nwalls = p_w.shape[0]
        # Draw all sements of a particular type of geometry
        for m in range(Nwalls):

            f_wall_xy = py.Polygon(p_w[m],
                                   closed=True,
                                   fc=cl_army_green,
                                   ec='k')
            py.gca().add_patch(f_wall_xy)

    return 0
Ejemplo n.º 6
0
def drawPolygons (axes):
    """
    Рисование многоугольника
    """
    polygon_1 = pylab.Polygon ([(0, -0.75),
                                (0, -1.25),
                                (0.5, -1.25),
                                (1, -0.75)])
    axes.add_patch (polygon_1)
    pylab.text (0.6, -0.7, "Polygon", horizontalalignment="center")


    polygon_2 = pylab.Polygon ([(-0.5, 0),
                                (-1, -0.5),
                                (-1, -1),
                                (-0.5, -1)],
                               fill = False,
                               closed = False)
    axes.add_patch (polygon_2)
    pylab.text (-1.0, -0.1, "Polygon", horizontalalignment="center")
Ejemplo n.º 7
0
def plot_vector_list2d(vectors, polygon=False, **kwargs):
    x = []
    y = []
    points = []
    for v in vectors:
        x.append(v.x)
        y.append(v.y)
        points.append([x, y])

    if polygon:
        pylab.Polygon(points, **kwargs)
    else:
        pylab.plot(x, y, **kwargs)
Ejemplo n.º 8
0
    def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
        """
        {_gate_plot_doc}
        """
        if ax == None:
            ax = pl.gca()

        if ax_channels is not None:
            flip = self._find_orientation(ax_channels)
        if flip:
            vert = [v[::-1] for v in self.vert]
        else:
            vert = self.vert
        kwargs.setdefault('fill', False)
        kwargs.setdefault('color', 'black')
        poly = pl.Polygon(vert, *args, **kwargs)
        return ax.add_artist(poly)
Ejemplo n.º 9
0
def plothistCI(a, b, l, u):
    '''
        >>> x=np.random.randn(1000)
        >>> bn=np.linspace(-3,3,41)
        >>> a,b,l,u=histCI(x,bins=bn)
        >>> plothistCI(a,b,l,u)
    '''
    b = b[:-1] + np.diff(b) / 2.
    plt.plot(b, a, color=CLR)
    x = np.concatenate([b, b[::-1]])
    ci = np.concatenate([u, l[::-1]])
    plt.gca().add_patch(
        plt.Polygon(np.array([x, ci]).T,
                    alpha=0.2,
                    fill=True,
                    fc='red',
                    ec='red'))
Ejemplo n.º 10
0
def draw_ROI(self, im=None, color='r'):
    """Draw the ROI on an image"""
    plt.ion()
    ax = im.axes
    if hasattr(self, 'xcoords'):  # it's a polygon
        poly = plt.Polygon(zip(self.xcoords, self.ycoords))
        poly.set_linewidth(1)
        poly.set_alpha(1)
        poly.set_edgecolor(color)
        poly.set_facecolor('none')
        ax.add_patch(poly)

    elif hasattr(self, 'circ'):  # it's a circle
        mycirc = plt.Circle(self.circ.center, self.circ.radius)
        mycirc.set_linewidth(1)
        mycirc.set_alpha(1)
        mycirc.set_edgecolor(color)
        mycirc.set_facecolor('none')
        ax.add_artist(mycirc)
Ejemplo n.º 11
0
    def fillcontinents(self,
                       color='#9887ff',
                       lake_color='b',
                       ax=None,
                       zorder=None,
                       alpha=None,
                       ocean_color='w',
                       ocean_alpha=1,
                       edge_color='k',
                       coast_color='none'):

        if not ax: ax = pl.gca()
        if self.projection[0] == 's': Lat0 = -90
        else: Lat0 = 90

        # boundary:
        xc, yc = self([0, 0], [Lat0, self.boundinglat])
        xc0, yc0 = xc[0], yc[0]
        r = np.sqrt((xc[1] - xc[0])**2 + (yc[1] - yc[0])**2)
        circle = pl.Circle((xc0, yc0),
                           r,
                           facecolor=ocean_color,
                           edgecolor=edge_color,
                           clip_on=0,
                           alpha=ocean_alpha,
                           zorder=zorder)
        ax.add_patch(circle)

        for i in range(len(self.coastpolygons)):
            xy = zip(*self.coastpolygons[i])
            if self.coastpolygontypes[i] == 1: cor = color
            else: cor = lake_color
            poly = pl.Polygon(xy,
                              edgecolor=coast_color,
                              facecolor=cor,
                              alpha=alpha,
                              zorder=zorder)
            axpoly = ax.add_patch(poly)
            axpoly.set_clip_path(circle)

        self._tasks(ax)

        self.clipping_path = circle
Ejemplo n.º 12
0
def draw_car(ax, s, car_length=car_length, **kwargs):
    # parse the state
    x, y, alpha, speed, theta = s

    # rotation matrix for the car relative to the current universe
    dx, dy = cos(alpha), sin(alpha)
    R = array([(dx, -dy), (dy, dx)])
    assert linalg.det(R) > 0.

    # scale the coordinate system so that the car's length is 1
    R *= car_length

    # rotation matrix of the wheels relative to the car
    Rwheel = array([(cos(theta), -sin(theta)), (sin(theta), cos(theta))])
    # rotation matrix of the wheels relative to the current universe
    Rwheel = dot(R, Rwheel)

    # body of the car in the curernt universe
    body = dot([(-2, -1), (2, -1), (2, 1), (-2, 1)], R.T) + (x, y)

    # the front axle, in the current universe
    axle = dot([(2, -1.5), (2, 1.5)], R.T) + (x, y)

    # a wheel. a vertical segment in its own coordinate system
    wheel = dot([(-.5, 0), (.5, 0)], Rwheel.T)

    hbody = P.Polygon(body, fill=False, edgecolor=kwargs.get('color', 'b'))
    haxle = P.Line2D(axle[:, 0], axle[:, 1], **kwargs)
    hleftwheel = P.Line2D([axle[0, 0] + wheel[:, 0]],
                          [axle[0, 1] + wheel[:, 1]], **kwargs)
    hrightwheel = P.Line2D([axle[1, 0] + wheel[:, 0]],
                           [axle[1, 1] + wheel[:, 1]], **kwargs)
    hcenter = P.Line2D([x], [y], marker='o', ms=5, mec=None, **kwargs)

    # the artists for the car
    hs = (hbody, haxle, hleftwheel, hrightwheel, hcenter)

    # add artists to the axis if supplied
    if ax:
        for h in hs:
            ax.add_artist(h)

    return hs
Ejemplo n.º 13
0
 def create_artist(self):
     self.poly = pl.Polygon(self.coordinates, color='k', fill=False)
     self.artist_list = to_list(self.poly)
     self.ax.add_artist(self.poly)
Ejemplo n.º 14
0
  pylab.plt.setp(bp['whiskers'], color='g')
  pylab.plt.setp(bp['medians'], color='black')
  pylab.plt.setp(bp['fliers'], color=palegreen, marker='+')
 
  # Now fill the boxes with desired colors
  numBoxes = len(plot_data)
  medians = range(numBoxes)
  for i in range(numBoxes):
    box = bp['boxes'][i]
    boxX = []
    boxY = []
    for j in range(5):
      boxX.append(box.get_xdata()[j])
      boxY.append(box.get_ydata()[j])
    boxCoords = zip(boxX,boxY)
    boxPolygon = pylab.Polygon(boxCoords, facecolor=palegreen)
    ax1.add_patch(boxPolygon)
 
  # Plot the errors
  if (len(error_x) > 0):
    ax1.scatter(error_x, error_y, color='r', marker='x', zorder=3)
 
  # Plot throughput
  ax2 = ax1.twinx()
  ax2.plot(throughput_data, 'o-', color=paleblue, linewidth=2, markersize=8)
 
  # Label the axis
  ax1.set_title(label)
  ax1.set_xlabel('Number of concurrent requests')
  ax2.set_ylabel('Requests per second')
  ax1.set_ylabel('Milliseconds')
Ejemplo n.º 15
0
def compAlpha(data, nb_orb=1., t_orb=6283., ciso=1e-3, plot=False \
                  , save=False):
    """compAlpha method, to compute Alpha out of \c 'history.txt'.

    Usage:
      compAlpha(data, [nb_orb, t_orb, ciso, plot])
    With:
      data:     a DumsesHistory object
      nb_orbit: number of orbits on which to perform the computation
      t_orb:    elapsed time during one orbit (in code unit)
      ciso:     sound speed
      plot:     set to True to plot the results
      save:     set to True to save the plot in PNG, PDF and EPS formats
    """
    try:
        assert (isinstance(data, dp.DumsesHistory))
    except AssertionError:
        print("Error: 'data' has to be a DumsesHistory object!")
        sys.exit(42)

    try:
        assert ("maxwell" in data.dict)
    except AssertionError:
        print(bold + "Error: " + reset + "'maxwell' is not in 'history.txt'")
    try:
        assert ("reynolds" in data.dict)
    except AssertionError:
        print(bold + "Error: " + reset + "'reynolds' is not in 'history.txt'")
    try:
        assert ("max+rey" in data.dict)
    except AssertionError:
        print(bold + "Error: " + reset + "'max+rey' is not in 'history.txt'")
    maxwell = data.dict["maxwell"]
    reynolds = data.dict["reynolds"]
    maxnolds = data.dict["max+rey"]

    if "time" in data.dict:
        time = data.dict["time"]
        tmax = time[-1]
        tlim = nb_orb * t_orb
        tn = pl.find(time >= (tmax - tlim))
        ntn = tn.size
        xlabel = "time"
    else:
        tmax = data.dict.values()[0].size - 1
        time = np.linspace(0, tmax, tmax + 1)
        tlim = tmax - nb_orb
        tn = map(int, np.linspace(tlim, tmax, nb_orb))
        xlabel = r"n$_{\sf hist}$"

    alpha = np.sum(maxnolds[tn]) / ntn / ciso**2
    alpha_max = np.sum(maxwell[tn]) / ntn / ciso**2
    alpha_rey = np.sum(reynolds[tn]) / ntn / ciso**2
    sigma_alpha = np.sum((maxnolds[tn] / ciso**2 - alpha)**2) / ntn
    sigma_alpha_max = np.sum((maxwell[tn] / ciso**2 - alpha_max)**2) / ntn
    sigma_alpha_rey = np.sum((reynolds[tn] / ciso**2 - alpha_rey)**2) / ntn
    sigma_alpha = np.sqrt(sigma_alpha)
    sigma_alpha_max = np.sqrt(sigma_alpha_max)
    sigma_alpha_rey = np.sqrt(sigma_alpha_rey)
    print("For %d orbits, " %nb_orb + "Alpha = %5.4f" %alpha \
              + ' +/- %3.2e' %sigma_alpha)
    print("           " + "Alpha_Max = %5.4f" %alpha_max \
              + ' +/- %3.2e' %sigma_alpha_max)
    print("           " + "Alpha_Rey = %5.4f" %alpha_rey \
              + ' +/- %3.2e' %sigma_alpha_rey)

    if plot:
        fig = pl.figure(figsize=(8, 12))
        # Alpha total
        ax = pl.subplot(311)
        pl.subplots_adjust(bottom=0.15)
        pl.ylabel(r'$\alpha$')
        pl.title(r'$\alpha_{\sf mean}$ = %5.4f' %alpha \
              + r' $\pm$ %s' %formatter(sigma_alpha))
        pl.plot(time / t_orb, maxnolds / ciso**2, color='w')
        x0, x1, y0, y1 = pl.axis()
        vert = [((tmax-tlim)/t_orb,y0)] + [((tmax-tlim)/t_orb,y1)] \
             + [(x1,y1)] + [(x1,y0)]
        poly = pl.Polygon(vert, fill=False, edgecolor='grey', hatch='//')
        ax.add_patch(poly)
        pl.plot(time / t_orb, maxnolds / ciso**2)
        pl.plot(time/t_orb \
              , pl.linspace(alpha,alpha,time.size) \
              , color='k', lw=1.)
        vert = [(min(time), alpha-sigma_alpha)] \
             + [(min(time), alpha+sigma_alpha)] \
             + [(x1, alpha+sigma_alpha)] \
             + [(x1, alpha-sigma_alpha)]
        poly = pl.Polygon(vert, facecolor='lightgrey' \
                              , edgecolor='lightgrey')
        ax.add_patch(poly)
        pl.axis([x0, x1, y0, y1])

        # Alpha Maxwell
        ax = pl.subplot(312)
        pl.subplots_adjust(bottom=0.15)
        pl.ylabel(r'$\alpha_{\sf Maxwell}$')
        pl.title(r'$\alpha_{\sf Maxwell\ mean}$ = %5.4f' %alpha_max \
              + r' $\pm$ %s' %formatter(sigma_alpha_max))
        pl.plot(time / t_orb, maxwell / ciso**2, color='w')
        x0, x1, y0, y1 = pl.axis()
        vert = [((tmax-tlim)/t_orb,y0)] + [((tmax-tlim)/t_orb,y1)] \
             + [(x1,y1)] + [(x1,y0)]
        poly = pl.Polygon(vert, fill=False, edgecolor='grey', hatch='//')
        ax.add_patch(poly)
        pl.plot(time / t_orb, maxwell / ciso**2)
        pl.plot(time/t_orb \
              , pl.linspace(alpha_max,alpha_max,time.size) \
              , color='k', lw=1.)
        vert = [(min(time), alpha_max-sigma_alpha_max)] \
             + [(min(time), alpha_max+sigma_alpha_max)] \
             + [(x1, alpha_max+sigma_alpha_max)] \
             + [(x1, alpha_max-sigma_alpha_max)]
        poly = pl.Polygon(vert, facecolor='lightgrey' \
                              , edgecolor='lightgrey')
        ax.add_patch(poly)
        pl.axis([x0, x1, y0, y1])

        # Alpha Reynolds
        ax = pl.subplot(313)
        pl.subplots_adjust(bottom=0.15)
        pl.xlabel(xlabel)
        pl.ylabel(r'$\alpha_{\sf Reynolds}$')
        pl.title(r'$\alpha_{\sf Reynolds\ mean}$ = %5.4f' %alpha_rey \
              + r' $\pm$ %s' %formatter(sigma_alpha_rey))
        pl.plot(time / t_orb, reynolds / ciso**2, color='w')
        x0, x1, y0, y1 = pl.axis()
        vert = [((tmax-tlim)/t_orb,y0)] + [((tmax-tlim)/t_orb,y1)] \
             + [(x1,y1)] + [(x1,y0)]
        poly = pl.Polygon(vert, fill=False, edgecolor='grey', hatch='//')
        ax.add_patch(poly)
        pl.plot(time / t_orb, reynolds / ciso**2)
        pl.plot(time/t_orb \
              , pl.linspace(alpha_rey,alpha_rey,time.size) \
              , color='k', lw=1.)
        vert = [(min(time), alpha_rey-sigma_alpha_rey)] \
             + [(min(time), alpha_rey+sigma_alpha_rey)] \
             + [(x1, alpha_rey+sigma_alpha_rey)] \
             + [(x1, alpha_rey-sigma_alpha_rey)]
        poly = pl.Polygon(vert, facecolor='lightgrey' \
                              , edgecolor='lightgrey')
        ax.add_patch(poly)
        pl.axis([x0, x1, y0, y1])

        if save:
            for form in ['png', 'pdf', 'eps']:
                namefig = 'alpha.' + form
                pl.savefig(namefig)
            pl.close()
        else:
            pl.show()
Ejemplo n.º 16
0
# ======================================================================
# Return an N-sided polygon in teh shape of an ellipse:
# Orientation in degrees. +90 is to account for different definition of
# orientation between SExtractor  (and IPP?) and pylab.


def ellipse((x, y), (a, b), orientation=0, resolution=100, **kwargs):

    # phi = numpy.deg2rad(orientation+90.0)
    phi = numpy.deg2rad(orientation)
    theta = 2 * numpy.pi * pylab.arange(resolution) / resolution
    xs = a * numpy.cos(theta)
    ys = b * numpy.sin(theta)
    xr = x + xs * numpy.cos(phi) - ys * numpy.sin(phi)
    yr = y + xs * numpy.sin(phi) + ys * numpy.cos(phi)

    return pylab.Polygon(zip(xr, yr), **kwargs)


# ======================================================================

# If called as a script, the python variable __name__ will be set to
# "__main__" - so test for this, and execute the main program if so.
# Writing it like this allows the function to be called
# from the python command line as well as from the unix prompt.

if __name__ == '__main__':
    proto_plot_sources(sys.argv[1:])

# ======================================================================
Ejemplo n.º 17
0
pyl.figure(figsize=(20, 20), dpi=50)
map_axis = pyl.axes([0.0, 0.0, 0.8, 0.9])
cb_axis = pyl.axes([0.83, 0.1, 0.03, 0.6])
c_map = pyl.cm.PuRd
pyl.axes(map_axis)
pyl.axis([-74.3, -73.6, 40.4, 41.0])
pyl.gca().set_axis_off()

for entry in chloro_df.iterrows():
    polygon_data = list(zip(*entry[1][1].exterior.coords.xy))
    zip_code = entry[1][0]
    accident_score = entry[1][4]
    color = c_map(accident_score)
    patch = pyl.Polygon(polygon_data,
                        facecolor=color,
                        edgecolor=(.3, .3, .3, 1),
                        linewidth=.1)
    pyl.gca().add_patch(patch)

pyl.title('Motor Vehicle Collisions per Zipcode in NYC (2017 - 2018)')
max_accidents = chloro_df.accident_score.max()
cb = pyl.mpl.colorbar.ColorbarBase(cb_axis,
                                   cmap=c_map,
                                   norm=pyl.mpl.colors.Normalize(
                                       vmin=0, vmax=max_accidents))
cb.set_label('Motor Vehicle Collision Risk Severity (Normalized)')
for obj in pyl.gcf().findobj(pyl.matplotlib.text.Text):
    obj.set_fontname('Arial')
    obj.set_fontsize(24)
pyl.savefig('../output/NYC_MVC_Chloropleth_Map_v2.png')
def draw_static_geo(ax_xy, ax_yz, ax_xz):
    Np, ro, tfinal, x_lim, y_lim, z_lim, xi_lim, yi_lim, zi_lim = time_pos_ax_limits(
    )

    # Define electrodes
    poly_cnt = np.array([[-Le / 2, Wg1 / 2], [Le / 2, Wg2 / 2],
                         [Le / 2, -Wg2 / 2], [-Le / 2, -Wg1 / 2]])
    poly_top = np.array([[-Le / 2, Wg1 / 2 + Ws + We],
                         [Le / 2, Wg2 / 2 + Ws + We], [Le / 2, Wg2 / 2 + Ws],
                         [-Le / 2, Wg1 / 2 + Ws]])
    poly_bottom = np.array([[-Le / 2, -Wg1 / 2 - Ws - We],
                            [Le / 2, -Wg2 / 2 - Ws - We],
                            [Le / 2, -Wg2 / 2 - Ws], [-Le / 2, -Wg1 / 2 - Ws]])

    center_electrode = py.Polygon(poly_cnt, closed=True, fc=cl_gold, ec='k')
    top_electrode = py.Polygon(poly_top, closed=True, fc=cl_gold, ec='k')
    bottom_electrode = py.Polygon(poly_bottom, closed=True, fc=cl_gold, ec='k')

    # Draw some fluid walls (not automated yet)
    # fluid_wall_1_yz = py.Rectangle((-fluid_wall_y, 0),  -fluid_wall_yW, fluid_wall_zW, fc=cl_army_green, ec = 'k')
    # fluid_wall_2_yz = py.Rectangle((fluid_wall_y, 0),  fluid_wall_yW, fluid_wall_zW, fc=cl_army_green, ec = 'k')

    py.gcf().sca(ax_yz)
    substrate_yz = py.Rectangle((y_lim[0], z_lim[0]), (y_lim[1] - y_lim[0]),
                                abs(z_lim[0]),
                                fc=cl_dgrey,
                                ec='k')
    py.gca().add_patch(substrate_yz)
    # py.gca().add_patch(fluid_wall_1_yz)
    # py.gca().add_patch(fluid_wall_2_yz)

    py.gcf().sca(ax_xz)
    substrate_xz = py.Rectangle((x_lim[0], z_lim[0]), (x_lim[1] - x_lim[0]),
                                abs(z_lim[0]),
                                fc=cl_dgrey,
                                ec='k')
    py.gca().add_patch(substrate_xz)

    py.gcf().sca(ax_xy)
    substrate_xy = py.Rectangle((x_lim[0], y_lim[0]), (x_lim[1] - x_lim[0]),
                                (y_lim[1] - y_lim[0]),
                                fc=cl_lgrey)
    py.gca().add_patch(substrate_xy)
    py.gca().add_patch(center_electrode)
    py.gca().add_patch(top_electrode)
    py.gca().add_patch(bottom_electrode)

    # Draw fluidic/reflecting geometries
    w_type = geo_element_types()

    # Loop over all types of geometry segments
    for wt in range(w_type.shape[0]):

        fname = 'geo_points' + str(
            w_type[wt]) + '()'  # name of the corresponding geometry function

        # Evaluate geo_points*()function by string name
        p_w, z_w = eval(fname)

        Nwalls = p_w.shape[0]
        # Draw all sements of a particular type of geometry
        for m in range(Nwalls):

            f_wall_xy = py.Polygon(p_w[m],
                                   closed=True,
                                   fc=cl_army_green,
                                   ec='k')
            py.gca().add_patch(f_wall_xy)

    return 0
Ejemplo n.º 19
0
import numpy as np
from scipy import spatial
import pylab as pl

np.random.seed(42)
points2d = np.random.rand(10, 2)
ch2d = spatial.ConvexHull(points2d)
poly = pl.Polygon(points2d[ch2d.vertices],
                  fill=None,
                  lw=2,
                  color='r',
                  alpha=0.5)
ax = pl.subplot(aspect='equal')
pl.plot(points2d[:, 0], points2d[:, 1], 'go')
for i, pos in enumerate(points2d):
    pl.text(pos[0], pos[1], str(i), color='blue')
ax.add_artist(poly)
pl.show()