Draw an RGB triangle legend on the desired axis
439144
def _rgb_triangle(ax, r_label, g_label, b_label, loc):
        
        if not loc in range(1, 11):
            loc = 2

        from mpl_toolkits.axes_grid1.inset_locator import inset_axes
        inset_ax = inset_axes(ax, width=1, height=1, loc=loc)
        mesh = 35
        x = []
        y = []
        color = []
        for r in range(0, mesh):
            for g in range(0, mesh):
                for b in range(0, mesh):
                    if not (r == 0 and b == 0 and g == 0):
                        r1 = r / (r + g + b)
                        g1 = g / (r + g + b)
                        b1 = b / (r + g + b)
                        x.append(0.33 * (2. * g1 + r1) / (r1 + b1 + g1))
                        y.append(0.33 * np.sqrt(3) * r1 / (r1 + b1 + g1))
                        rc = math.sqrt(r ** 2 / (r ** 2 + g ** 2 + b ** 2))
                        gc = math.sqrt(g ** 2 / (r ** 2 + g ** 2 + b ** 2))
                        bc = math.sqrt(b ** 2 / (r ** 2 + g ** 2 + b ** 2))
                        color.append([rc, gc, bc])

        # x = [n + 0.25 for n in x]  # nudge x coordinates
        # y = [n + (max_y - 1) for n in y]  # shift y coordinates to top
        # plot the triangle
        inset_ax.scatter(x, y, s=7, marker='.', edgecolor=color)
        inset_ax.set_xlim([-0.35, 1.00])
        inset_ax.set_ylim([-0.35, 1.00])

        # add the labels
        inset_ax.text(0.70, -0.2, g_label, fontsize=13,
                      family='Times New Roman', color=(0, 0, 0),
                      horizontalalignment='left')
        inset_ax.text(0.325, 0.70, r_label, fontsize=13,
                      family='Times New Roman', color=(0, 0, 0),
                      horizontalalignment='center')
        inset_ax.text(-0.05, -0.2, b_label, fontsize=13,
                      family='Times New Roman', color=(0, 0, 0),
                      horizontalalignment='right')

        inset_ax.get_xaxis().set_visible(False)
        inset_ax.get_yaxis().set_visible(False)
130919
def plot_band(plt_in, band_name, rsr_obj, **kwargs):
    """"""
    if 'platform_name_in_legend' in kwargs:
        platform_name_in_legend = kwargs['platform_name_in_legend']
    else:
        platform_name_in_legend = False

    detectors = rsr_obj.rsr[band_name].keys()
    # for det in detectors:
    det = sorted(detectors)[0]
    resp = rsr_obj.rsr[band_name][det]['response']
    wvl = rsr_obj.rsr[band_name][det]['wavelength']

    resp = np.ma.masked_less_equal(resp, minimum_response)
    wvl = np.ma.masked_array(wvl, resp.mask)
    resp.compressed()
    wvl.compressed()

    if platform_name_in_legend:
        plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
            platform=rsr_obj.platform_name, band=band_name))
    else:
        plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))

    return plt_in
289
function (legend) {

            var options = this.options,
              markerOptions = options.marker,
              radius,
              legendOptions = legend.options,
              legendSymbol,
              symbolWidth = legend.symbolWidth,
              renderer = this.chart.renderer,
              legendItemGroup = this.legendGroup,
              verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3),
              attr;

            // Draw the line
            if (options.lineWidth) {
                attr = {
                    'stroke-width': options.lineWidth
                };
                if (options.dashStyle) {
                    attr.dashstyle = options.dashStyle;
                }
                this.legendLine = renderer.path([
                      M,
                      0,
                      verticalCenter,
                      L,
                      symbolWidth,
                      verticalCenter
                  ])
                  .attr(attr)
                  .add(legendItemGroup);
            }

            // Draw the marker
            if (markerOptions && markerOptions.enabled !== false) {
                radius = markerOptions.radius;
                this.legendSymbol = legendSymbol = renderer.symbol(
                  this.symbol,
                    (symbolWidth / 2) - radius,
                    verticalCenter - radius,
                    2 * radius,
                    2 * radius
                  )
                  .add(legendItemGroup);
                legendSymbol.isMarker = true;
            }
        }
57866
def plot_legend(ax, no_legend=True, legend_arg=None):
    
    legend_arg = dict_if_none(legend_arg)

    if not no_legend:
        ax.legend(**legend_arg)
223033
function (legend, item) {
		var padding = legend.padding,
			legendOptions = legend.options,
			horiz = this.horiz,
			box,
			width = pick(legendOptions.symbolWidth, horiz ? 200 : 12),
			height = pick(legendOptions.symbolHeight, horiz ? 12 : 200),
			labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
			itemDistance = pick(legendOptions.itemDistance, 10);

		this.setLegendColor();

		// Create the gradient
		item.legendSymbol = this.chart.renderer.rect(
			0,
			legend.baseline - 11,
			width,
			height
		).attr({
			zIndex: 1
		}).add(item.legendGroup);
		box = item.legendSymbol.getBBox();

		// Set how much space this legend item takes up
		this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding);
		this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
	}
598800
def draw_color(self):
        """"""
        rgba = ffi.new('Uint8[]', 4)
        check_int_err(lib.SDL_GetRenderDrawColor(self._ptr, rgba + 0, rgba + 1, rgba + 2, rgba + 3))
        return (rgba[0], rgba[1], rgba[2], rgba[3])
326565
function drawGradient(legend, barGroup, y) {
  var id = "terriajs-legend-gradient" + ++gradientCount;
  var defs = addSvgElement(legend, "defs", {}); // apparently it's ok to have the defs anywhere in the doc
  var linearGradient = svgElement(legend, "linearGradient", {
    x1: "0",
    x2: "0",
    y1: "1",
    y2: "0",
    id: id
  });
  legend.gradientColorMap.forEach(function(c, i) {
    linearGradient.appendChild(
      svgElement(legend, "stop", {
        offset: c.offset,
        "stop-color": c.color
      })
    );
  });
  defs.appendChild(linearGradient);

  var gradientItems = legend.items.filter(function(item) {
    return !defined(item.color);
  });

  var totalSpacingAbove = gradientItems.reduce(function(prev, item) {
    return prev + (item.spacingAbove || 0);
  }, 0);
  var barHeight = Math.max(
    (legend.computedItemHeight + legend.itemSpacing) * gradientItems.length +
      totalSpacingAbove,
    legend.barHeightMin
  );

  addSvgElement(
    legend,
    "rect",
    {
      x: legend.barLeft,
      y: y,
      width: legend.itemWidth,
      height: barHeight,
      fill: "url(#" + id + ")"
    },
    "gradient-bar"
  );

  return barHeight;
}
190292
function drawRadialProgressBar(context, options) {
    let unit = context.max / 100;
    let rMax = maxRadialRadius(context, options) - 5 * unit;
    let sw = (parseFloat(options.barStrokeWidth) || 0);
    let w = (parseFloat(options.barWidth) || 0) * unit;
    let rMin = rMax - sw * 2 - w;
    let half = (rMax- rMin) / 2;
    let r = rMin + half;
    let delta = sw / r;
    let sa = options.startAngle;
    let ea = options.startAngle + options.ticksAngle;

    context.save();
    context.rotate(HPI);

    if (sw) {
        // draw stroke
        context.beginPath();
        context.arc(0, 0, r, drawings.radians(sa) - delta,
            drawings.radians(ea) + delta, false);
        context.strokeStyle = options.colorBarStroke;
        context.lineWidth = half * 2;
        context.stroke();
        context.closePath();
    }

    if (w) {
        // draw bar
        context.beginPath();
        context.arc(0, 0, r, drawings.radians(sa), drawings.radians(ea), false);
        context.strokeStyle = options.colorBar;
        context.lineWidth = w;
        context.stroke();
        context.closePath();

        if  (options.barShadow) {
            // draw shadow
            context.beginPath();
            context.arc(0, 0, rMax, drawings.radians(sa), drawings.radians(ea),
                false);
            context.clip();

            context.beginPath();
            context.strokeStyle = options.colorBar;
            context.lineWidth = 1;
            context.shadowBlur = options.barShadow;
            context.shadowColor = options.colorBarShadow;
            context.shadowOffsetX = 0;
            context.shadowOffsetY = 0;
            context.arc(0, 0, rMax,
                drawings.radians(options.startAngle),
                drawings.radians(options.startAngle + options.ticksAngle),
                false);
            context.stroke();
            context.closePath();

            context.restore();
            context.rotate(HPI);
        }

        // draw bar progress
        if (options.barProgress) {
            context.beginPath();
            context.arc(0, 0, r,
                drawings.radians(sa),
                drawings.radians(sa +
                    (drawings.normalizedValue(options).normal -
                    options.minValue) / (options.maxValue - options.minValue) *
                    options.ticksAngle),
                false);
            context.strokeStyle = options.colorBarProgress;
            context.lineWidth = w;
            context.stroke();
            context.closePath();
        }
    }

    context.restore();
}
973673
def render(self, **kwargs):
        
        # Calling parent function
        super(VisCurve2D, self).render(**kwargs)

        # Initialize variables
        legend_proxy = []
        legend_names = []

        # Draw control points polygon and the curve
        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)
        ax = fig.gca()

        # Start plotting
        for plot in self._plots:
            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                cpplot, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-.', marker='o')
                legend_proxy.append(cpplot)
                legend_names.append(plot['name'])

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                curveplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-', alpha=self.vconf.alpha)
                legend_proxy.append(curveplt)
                legend_names.append(plot['name'])
                # Debugging for curve directions
                if self.vconf.debug_mode:
                    plt.quiver(pts[0, 0], pts[0, 1], pts[-1, 0] - pts[0, 0], pts[-1, 1] - pts[0, 1],
                               color='k', angles='xy', scale_units='xy', scale=1, width=0.003)

            # Plot bounding box
            if plot['type'] == 'bbox' and self.vconf.display_bbox:
                bboxplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='--')
                legend_proxy.append(bboxplt)
                legend_names.append(plot['name'])

            # Plot extras
            if plot['type'] == 'extras':
                extrasplt, = plt.plot(pts[:, 0], pts[:, 1],
                                      color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])
                legend_proxy.append(extrasplt)
                legend_names.append(plot['name'])

        # Add legend
        if self.vconf.display_legend:
            plt.legend(legend_proxy, legend_names)

        # Remove axes
        if not self.vconf.display_axes:
            plt.axis('off')

        # Set aspect ratio
        if self.vconf.axes_equal:
            ax.set_aspect('equal')

        # Axis labels
        if self.vconf.display_labels:
            ax.set_xlabel('x')
            ax.set_ylabel('y')

        # Process keyword arguments
        fig_filename = kwargs.get('fig_save_as', None)
        fig_display = kwargs.get('display_plot', True)

        # Display the plot
        if fig_display:
            plt.show()
        else:
            fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename

        # Save the figure
        self.vconf.save_figure_as(fig, fig_filename)
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)
}
236769
def drawrectangle(self, xa, xb, ya, yb, colour=None, label = None):
        
    
        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()
        
        (pilxa, pilya) = self.pilcoords((xa,ya))
        (pilxb, pilyb) = self.pilcoords((xb,yb))
        
        self.draw.rectangle([(pilxa, pilyb-1), (pilxb+1, pilya)], outline = colour)
        
        if label != None:
            # The we write it :
            self.loadlabelfont()
            textwidth = self.draw.textsize(label, font = self.labelfont)[0]
            self.draw.text(((pilxa + pilxb)/2.0 - float(textwidth)/2.0 + 1, pilya + 2), label, fill = colour, font = self.labelfont)
1342967
def draw(self):
        '''
        
        '''
        if self.__conditional_flag is True:
            return np.concatenate((self.__create_samples(), self.__create_samples()), axis=1)
        else:
            return self.__create_samples()
422728
def triangle_colors(tile_x, tile_y, tile_size, pix):
    
    quad_size = tile_size / 2

    north = []
    for y in xrange(tile_y, tile_y + quad_size):
        x_off = y - tile_y
        for x in xrange(tile_x + x_off, tile_x + tile_size - x_off):
            north.append(pix[x, y])

    south = []
    for y in xrange(tile_y + quad_size, tile_y + tile_size):
        x_off = tile_y + tile_size - y
        for x in xrange(tile_x + x_off, tile_x + tile_size - x_off):
            south.append(pix[x, y])

    east = []
    for x in xrange(tile_x, tile_x + quad_size):
        y_off = x - tile_x
        for y in xrange(tile_y + y_off, tile_y + tile_size - y_off):
            east.append(pix[x, y])

    west = []
    for x in xrange(tile_x + quad_size, tile_x + tile_size):
        y_off = tile_x + tile_size - x
        for y in xrange(tile_y + y_off, tile_y + tile_size - y_off):
            west.append(pix[x, y])

    return map(get_average_color, [north, east, south, west])
682773
def plot(self, ax: GeoAxesSubplot, **kwargs) -> Artist:
        """"""

        if "facecolor" not in kwargs:
            kwargs["facecolor"] = "None"
        if "edgecolor" not in kwargs:
            kwargs["edgecolor"] = ax._get_lines.get_next_color()

        if "projection" in ax.__dict__:
            return ax.add_geometries([self.shape], crs=PlateCarree(), **kwargs)
        else:
            return ax.add_patch(
                MplPolygon(list(self.shape.exterior.coords), **kwargs)
            )
1103640
def _plot(self, xticks=[], yticks=[], minor_xticks=[], minor_yticks=[],
              xlabel='Longitude', ylabel='Latitude', ax=None, ax2=None,
              colorbar=None, cb_orientation=None, cb_label=None, grid=False,
              axes_labelsize=None, tick_labelsize=None, **kwargs):
        """"""

        if ax is None:
            if colorbar is True:
                if cb_orientation == 'horizontal':
                    scale = 0.67
                else:
                    scale = 0.5
            else:
                scale = 0.55
            figsize = (_mpl.rcParams['figure.figsize'][0],
                       _mpl.rcParams['figure.figsize'][0] * scale)
            fig, axes = _plt.subplots(1, 1, figsize=figsize)
        else:
            axes = ax

        deg = '$^{\circ}$'
        xticklabels = [str(int(y)) + deg for y in xticks]
        yticklabels = [str(int(y)) + deg for y in yticks]

        cim = axes.imshow(self.data, origin='upper',
                          extent=(0., 360., -90., 90.), **kwargs)
        axes.set(xticks=xticks, yticks=yticks)
        axes.set_xlabel(xlabel, fontsize=axes_labelsize)
        axes.set_ylabel(ylabel, fontsize=axes_labelsize)
        axes.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axes.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axes.set_xticks(minor_xticks, minor=True)
        axes.set_yticks(minor_yticks, minor=True)
        axes.grid(grid, which='major')

        if colorbar is True:
            if cb_orientation == 'vertical':
                divider = _make_axes_locatable(axes)
                cax = divider.append_axes("right", size="2.5%", pad=0.15)
                cbar = _plt.colorbar(cim, cax=cax, orientation=cb_orientation)
            else:
                divider = _make_axes_locatable(axes)
                cax = divider.append_axes("bottom", size="5%", pad=0.5)
                cbar = _plt.colorbar(cim, cax=cax,
                                     orientation=cb_orientation)
            if cb_label is not None:
                cbar.set_label(cb_label, fontsize=axes_labelsize)
            cbar.ax.tick_params(labelsize=tick_labelsize)

        if ax is None:
            return fig, axes
243471
def plotPixel(self, x, y, color="black"):
        
        p = Point(x, y)
        p.fill(color)
        p.draw(self)
        p.t = lambda v: v
        p.tx = lambda v: v
        p.ty = lambda v: v
554583
def plot(f, lcar=1.0e-1):
    
    import matplotlib
    import matplotlib.pyplot as plt
    import pygmsh

    geom = pygmsh.built_in.Geometry()
    geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True)
    points, cells, _, _, _ = pygmsh.generate_mesh(geom, verbose=True)

    x = points[:, 0]
    y = points[:, 1]
    triang = matplotlib.tri.Triangulation(x, y, cells["triangle"])

    plt.tripcolor(triang, f(points.T), 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)

    # circle outline
    circle = plt.Circle((0, 0), 1.0, edgecolor="k", fill=False)
    plt.gca().add_artist(circle)

    plt.gca().set_aspect("equal")
    plt.axis("off")
    return