Filled contour plot on a 2D triangle of a function evaluated at
    barycentric 2-simplex points.

    Function signature is identical to :func:`contour` with the caveat that
    ``**kwargs`` are passed on to :func:`plt.tricontourf`.
556210
def contourf(f, vertexlabels=None, **kwargs):
    ''''''
    return _contour(f, vertexlabels, contourfunc=plt.tricontourf, **kwargs)
22421
def show(self, *args, **kwargs):
        
        plt = self.get_pourbaix_plot(*args, **kwargs)
        plt.show()
593651
def plotEz(self,*args,**kwargs):
        
        if kwargs.pop('normed',False):
            kwargs['d2']= 'Eznorm'
        else:
            kwargs['d2']= 'Ez'
        return self.plot(*args,**kwargs)
911364
def plot(corners, f, n=100):
    
    import matplotlib.tri
    import matplotlib.pyplot as plt

    # discretization points
    def partition(boxes, balls):
        # <https://stackoverflow.com/a/36748940/353337>
        def rec(boxes, balls, parent=tuple()):
            if boxes > 1:
                for i in range(balls + 1):
                    for x in rec(boxes - 1, i, parent + (balls - i,)):
                        yield x
            else:
                yield parent + (balls,)

        return list(rec(boxes, balls))

    bary = numpy.array(partition(3, n)).T / n
    X = numpy.sum([numpy.outer(bary[k], corners[:, k]) for k in range(3)], axis=0).T

    # plot the points
    # plt.plot(X[0], X[1], 'xk')

    x = numpy.array(X[0])
    y = numpy.array(X[1])
    z = numpy.array(f(bary), dtype=float)

    triang = matplotlib.tri.Triangulation(x, y)
    plt.tripcolor(triang, z, shading="flat")
    plt.colorbar()

    # Choose a diverging colormap such that the zeros are clearly
    # distinguishable.
    plt.set_cmap("coolwarm")
    # Make sure the color map limits are symmetric around 0.
    clim = plt.gci().get_clim()
    mx = max(abs(clim[0]), abs(clim[1]))
    plt.clim(-mx, mx)

    # triangle outlines
    X = numpy.column_stack([corners, corners[:, 0]])
    plt.plot(X[0], X[1], "-k")

    plt.gca().set_aspect("equal")
    plt.axis("off")
    return
717109
def get_contour_pd_plot(self):
        
        from scipy import interpolate
        from matplotlib import cm

        pd = self._pd
        entries = pd.qhull_entries
        data = np.array(pd.qhull_data)

        plt = self._get_2d_plot()
        data[:, 0:2] = triangular_coord(data[:, 0:2]).transpose()
        for i, e in enumerate(entries):
            data[i, 2] = self._pd.get_e_above_hull(e)

        gridsize = 0.005
        xnew = np.arange(0, 1., gridsize)
        ynew = np.arange(0, 1, gridsize)

        f = interpolate.LinearNDInterpolator(data[:, 0:2], data[:, 2])
        znew = np.zeros((len(ynew), len(xnew)))
        for (i, xval) in enumerate(xnew):
            for (j, yval) in enumerate(ynew):
                znew[j, i] = f(xval, yval)

        plt.contourf(xnew, ynew, znew, 1000, cmap=cm.autumn_r)

        plt.colorbar()
        return plt
814452
def calc_2dsplinecoeffs_c(array2d):
    
    #Set up result arrays
    out= copy.copy(array2d)
    out= numpy.require(out,dtype=numpy.float64,requirements=['C','W'])

    #Set up the C code
    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')
    interppotential_calc_2dsplinecoeffs= _lib.samples_to_coefficients
    interppotential_calc_2dsplinecoeffs.argtypes= [ndpointer(dtype=numpy.float64,flags=ndarrayFlags),
                                                   ctypes.c_int,
                                                   ctypes.c_int]

    #Run the C code
    interppotential_calc_2dsplinecoeffs(out,out.shape[1],out.shape[0])

    return out
1303067
def extrap1d(interpolator):
    
    
    xs = interpolator.x
    ys = interpolator.y

    def pointwise(x):
        if x < xs[0]:
            return ys[0] # +(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
        elif x > xs[-1]:
            return ys[-1] # +(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
        else:
            return interpolator(x)

    def ufunclike(xs):
        return N.array(map(pointwise, N.array(xs)))

    return ufunclike
1142394
def voronoi_filled(points_or_voronoi, colors, show_points=False,
                   padding_fraction=0.05, cmap=None, ax=None, alpha=None,
                   edgecolor=None):
  '''
  '''
  from scipy.spatial import Voronoi  # Late import; scipy is optional

  # Disambiguate the first parameter
  if isinstance(points_or_voronoi, Voronoi):
    vor = points_or_voronoi
  else:
    points = np.asanyarray(points_or_voronoi)
    assert points.shape[1] == 2, 'Input points must be 2D'
    vor = Voronoi(points)

  # Borrowed from http://nbviewer.ipython.org/gist/pv/8037100
  regions = []
  vertices = vor.vertices.tolist()

  center = vor.points.mean(axis=0)
  radius = vor.points.ptp().max()*2

  # Construct a map containing all ridges for a given point
  all_ridges = {}
  for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
    all_ridges.setdefault(p1, []).append((p2, v1, v2))
    all_ridges.setdefault(p2, []).append((p1, v1, v2))

  # Reconstruct infinite regions
  for p1, region in enumerate(vor.point_region):
    verts = vor.regions[region]
    if all(v >= 0 for v in verts):
      # finite region
      regions.append(verts)
      continue

    # reconstruct a non-finite region
    ridges = all_ridges[p1]
    new_region = [v for v in verts if v >= 0]

    for p2, v1, v2 in ridges:
      if v2 < 0:
        v1, v2 = v2, v1
      if v1 >= 0:
        # finite ridge: already in the region
        continue

      # Compute the missing endpoint of an infinite ridge
      t = vor.points[p2] - vor.points[p1]  # tangent
      t /= np.linalg.norm(t)
      n = np.array([-t[1], t[0]])  # normal

      midpoint = vor.points[[p1, p2]].mean(axis=0)
      direction = np.sign((midpoint - center).dot(n)) * n
      far_point = vor.vertices[v2] + direction * radius

      new_region.append(len(vertices))
      vertices.append(far_point.tolist())

    # sort region counterclockwise
    vs = np.asarray([vertices[v] for v in new_region])
    vs -= vs.mean(axis=0)
    angle_order = np.argsort(np.arctan2(vs[:,1], vs[:,0]))
    new_region = np.array(new_region)[angle_order]

    # finish
    regions.append(new_region)
  vertices = np.asarray(vertices)

  # Plot colored polygons
  if ax is None:
    ax = plt.gca()
  polys = PatchCollection([Polygon(vertices[region]) for region in regions],
                          cmap=cmap, alpha=alpha, edgecolor=edgecolor)
  polys.set_array(np.asanyarray(colors))
  ax.add_collection(polys)

  if show_points:
    ax.plot(vor.points[:,0], vor.points[:,1], 'ko')

  # Zoom to a reasonable scale.
  pad = padding_fraction * (vor.max_bound - vor.min_bound)
  mins = vor.min_bound - pad
  maxes = vor.max_bound + pad
  ax.set_xlim(mins[0], maxes[0])
  ax.set_ylim(mins[1], maxes[1])
  return polys
320445
def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):
        
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
854041
def p_function_expr_2(self, p):
        
        if len(p) == 8:
            p[0] = self.asttypes.FuncExpr(
                identifier=p[2], parameters=None, elements=p[6])
        else:
            p[0] = self.asttypes.FuncExpr(
                identifier=p[2], parameters=p[4], elements=p[7])
        p[0].setpos(p)
1060775
def plotER(self,*args,**kwargs):
        
        if kwargs.pop('normed',False):
            kwargs['d2']= 'ERnorm'
        else:
            kwargs['d2']= 'ER'
        return self.plot(*args,**kwargs)
313003
def compose(*funcs):
    
    # slightly optimized for most common cases and hence verbose
    if len(funcs) == 2: f0,f1=funcs; return lambda *a,**kw: f0(f1(*a,**kw))
    elif len(funcs) == 3: f0,f1,f2=funcs; return lambda *a,**kw: f0(f1(f2(*a,**kw)))
    elif len(funcs) == 0: return lambda x:x     # XXX single kwarg
    elif len(funcs) == 1: return funcs[0]
    else:
        def composed(*args,**kwargs):
            y = funcs[-1](*args,**kwargs)
            for f in funcs[:0:-1]: y = f(y)
            return y
        return composed
966788
def _function(self, x, a, b, c, d, s):
        
        return c/(np.pi*self._g_a(x, a, b, s)*(1.0+((x-a)/(self._g_a(x, a, b, s)))**2))+d
1291837
private static final void fill(Shape shape, PointCallback callback) {
    	Triangulator tris = shape.getTriangles();

        GL.glBegin(SGL.GL_TRIANGLES);
        for (int i=0;i<tris.getTriangleCount();i++) {
        	for (int p=0;p<3;p++) {
        		float[] pt = tris.getTrianglePoint(i, p);
        		float[] np = callback.preRenderPoint(shape, pt[0],pt[1]);
        		
        		if (np == null) {
        			GL.glVertex2f(pt[0],pt[1]);
        		} else {
        			GL.glVertex2f(np[0],np[1]);
        		}
        	}
        }
        GL.glEnd();
    }
578774
def _build_discrete_cmap(cmap, levels, extend, filled):
    
    import matplotlib as mpl

    if not filled:
        # non-filled contour plots
        extend = 'max'

    if extend == 'both':
        ext_n = 2
    elif extend in ['min', 'max']:
        ext_n = 1
    else:
        ext_n = 0

    n_colors = len(levels) + ext_n - 1
    pal = _color_palette(cmap, n_colors)

    new_cmap, cnorm = mpl.colors.from_levels_and_colors(
        levels, pal, extend=extend)
    # copy the old cmap name, for easier testing
    new_cmap.name = getattr(cmap, 'name', cmap)

    return new_cmap, cnorm
603499
def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs):
        
        import matplotlib.pyplot as pp
        grid_width = max(maxx-minx, maxy-miny) / 200.0

        ax = kwargs.pop('ax', None)

        xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width]
        V = self.potential(xx, yy)
        # clip off any values greater than 200, since they mess up
        # the color scheme
        if ax is None:
            ax = pp

        ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs)
437604
function triangleDraw(c, params)
{
    const size = params.size
    const half = params.size / 2
    c.beginPath()
    c.fillStyle = '#' + params.color.toString(16)
    c.moveTo(half, 0)
    c.lineTo(0, size)
    c.lineTo(size, size)
    c.closePath()
    c.fill()
    c.fillStyle = 'white'
    c.font = '40px Arial'
    const measure = c.measureText(n)
    c.fillText(n++, size / 2 - measure.width / 2, size / 2 + 10)
}