Adds a color bar or a legend to the given ax. A legend is added when the
    data is categorical and a color bar is added when a continuous value was used.
17247
def _add_legend_or_colorbar(adata, ax, cax, categorical, value_to_plot, legend_loc,
                            scatter_array, legend_fontweight, legend_fontsize,
                            groups, multi_panel):
    
    # add legends or colorbars
    if categorical is True:
        # add legend to figure
        categories = list(adata.obs[value_to_plot].cat.categories)
        colors = adata.uns[value_to_plot + '_colors']

        if multi_panel is True:
            # Shrink current axis by 10% to fit legend and match
            # size of plots that are not categorical
            box = ax.get_position()
            ax.set_position([box.x0, box.y0, box.width * 0.91, box.height])

        if groups is not None:
            # only label groups with the respective color
            colors = [colors[categories.index(x)] for x in groups]
            categories = groups

        if legend_loc == 'right margin':
            for idx, label in enumerate(categories):
                color = colors[idx]
                # use empty scatter to set labels
                ax.scatter([], [], c=color, label=label)
            ax.legend(
                frameon=False, loc='center left',
                bbox_to_anchor=(1, 0.5),
                ncol=(1 if len(categories) <= 14
                      else 2 if len(categories) <= 30 else 3),
                fontsize=legend_fontsize)

        if legend_loc == 'on data':
            # identify centroids to put labels
            all_pos = np.zeros((len(categories), 2))
            for ilabel, label in enumerate(categories):
                _scatter = scatter_array[adata.obs[value_to_plot] == label, :]
                x_pos, y_pos = np.median(_scatter, axis=0)

                ax.text(x_pos, y_pos, label,
                        weight=legend_fontweight,
                        verticalalignment='center',
                        horizontalalignment='center',
                        fontsize=legend_fontsize)

                all_pos[ilabel] = [x_pos, y_pos]
            # this is temporary storage for access by other tools
            utils._tmp_cluster_pos = all_pos
    else:
        # add colorbar to figure
        pl.colorbar(cax, ax=ax, pad=0.01, fraction=0.08, aspect=30)
36815
function addStyle(element) {
			if (parent.legendScale === null) {
				return false;
			}

			element.attr("fill", function(d) {
				if (d.v === null && (options.hasOwnProperty("considerMissingDataAsZero") && !options.considerMissingDataAsZero)) {
					if (options.legendColors.hasOwnProperty("base")) {
						return options.legendColors.base;
					}
				}

				if (options.legendColors !== null && options.legendColors.hasOwnProperty("empty") &&
					(d.v === 0 || (d.v === null && options.hasOwnProperty("considerMissingDataAsZero") && options.considerMissingDataAsZero))
				) {
					return options.legendColors.empty;
				}

				if (d.v < 0 && options.legend[0] > 0 && options.legendColors !== null && options.legendColors.hasOwnProperty("overflow")) {
					return options.legendColors.overflow;
				}

				return parent.legendScale(Math.min(d.v, options.legend[options.legend.length-1]));
			});
		}
213711
function drawTick(y) {
    barGroup.appendChild(
      svgElement(
        legend,
        "line",
        {
          x1: legend.itemWidth,
          x2: legend.itemWidth + 5,
          y1: y,
          y2: y
        },
        "tick-mark"
      )
    );
  }
1149644
function (legend, item) {
		var radius = pInt(legend.itemStyle.fontSize) / 2;
		
		item.legendSymbol = this.chart.renderer.circle(
			radius,
			legend.baseline - radius,
			radius
		).attr({
			zIndex: 3
		}).add(item.legendGroup);
		item.legendSymbol.isMarker = true;	
		
	}
815074
function _legends(id, makeSVG) {
  let classed = 'chart-legends', 
      theme = 'light',
      background = undefined,
      width = DEFAULT_SIZE,
      height = null,
      margin = DEFAULT_MARGIN,
      inset = DEFAULT_INSET,
      padding = DEFAULT_INSET,
      textPadding = DEFAULT_INSET,
      style = undefined,
      legendSize = DEFAULT_LEGEND_SIZE,
      radius = DEFAULT_LEGEND_RADIUS,
      msize = DEFAULT_LEGEND_TEXT_SCALE,
      fontSize = undefined,
      fontFill = undefined,
      orientation = 'bottom',
      fill = null,
      scale = 1.0;
 
  function _makeFillFn() {
    let colors = () => fill;
    if (fill == null) {
      let c = presentation10.standard;
      colors = (d, i) => (c[i % c.length]);
    } else if (typeof fill === 'function') {
      colors = fill;
    } else if (Array.isArray(fill)) {
      colors = (d, i) => fill[ i % fill.length ];
    }
    return colors;  
  }  

  function _impl(context) {
    let selection = context.selection ? context.selection() : context,
        transition = (context.selection !== undefined);
      
    let _inset = _impl.canonicalInset();
    let _style = style;
    if (_style === undefined) {
      _style = _impl.defaultStyle();
    }       
    selection.each(function() {
      let node = select(this);  
      let _height = height || Math.round(width * DEFAULT_ASPECT);
      
      let elmS = node,
          w = width,
          h = _height;
          
      if (makeSVG === true) {
        let _background = background;
        if (_background === undefined) {
          _background = display[theme].background;
        }
        // SVG element
        let sid = null;
        if (id) sid = 'svg-' + id;
        let root = chartSVG(sid).width(w).height(h).margin(margin).scale(scale).style(_style).background(_background);
        let tnode = node;
        if (transition === true) {
          tnode = node.transition(context);
        }
        tnode.call(root);
        
        elmS = node.select(root.self()).select(root.child());
        w = root.childWidth();
        h = root.childHeight();
      }
      
      // Create required elements
      let g = elmS.select(_impl.self())
      if (g.empty()) {
        g = elmS.append('g').attr('class', classed).attr('id', id);
      }

      let legend = node.datum() || [];
      
      let lg = g.selectAll('g').data(legend);
      lg.exit().remove();
      let newlg = lg.enter().append('g');
      
      newlg.append('rect');
      newlg.append('text')
        .attr('dominant-baseline', 'central');
            
      let rect = g.selectAll('g rect').data(legend);
      let text = g.selectAll('g text').data(legend).text(d => d);

      let lens = legend.map(d => d == null ?  0 : d.length * msize + legendSize + textPadding + padding);
      
      if (orientation === 'left' || orientation === 'right') {
        let groups = g.selectAll('g').data(lens);
        groups = transition === true ? groups.transition(context) : groups;

        let idx = -1;
        let remap = legend.map(d => (d == null ? idx : ++idx));
        groups.attr('transform', (d, i) => 'translate(' + 0 + ',' + (remap[i] * (legendSize + padding)) + ')');
      } else {
        let clens = []
        let total = lens.reduce((p, c) => (clens.push(p) , p + c), 0) - padding; // trim the last padding
        let offset = -total / 2;
        let groups = g.selectAll('g').data(clens);
        
        groups = transition === true ? groups.transition(context) : groups;
        groups.attr('transform', (d) => 'translate(' + (offset + d) + ',0)');
      }
            
      if (transition === true) {
          g = g.transition(context);
          rect = rect.transition(context);
          text = text.transition(context);
      }      
      
      if (orientation === 'top') {
        g.attr('transform', 'translate(' + (w/2) + ',' + (_inset.top) + ')');
      } else if (orientation === 'left') {
        g.attr('transform', 'translate(' + _inset.left + ',' + ((h - legend.length * (legendSize + padding) + padding)/2) + ')');
      } else if (orientation === 'right') {
        g.attr('transform', 'translate(' + (w - _inset.right - legendSize) + ',' + ((h - legend.length * (legendSize + padding) + padding)/2) + ')');
      } else {
        g.attr('transform', 'translate(' + (w/2) + ',' + (h - _inset.bottom - legendSize) + ')');
      }

      let colors = _makeFillFn();
      
      rect.attr('rx', radius)
            .attr('ry', radius)
            .attr('width', d => d != null ? legendSize : 0)
            .attr('height', d => d != null ? legendSize : 0)
            .attr('fill', colors);

      text.attr('y', legendSize / 2)
          .attr('fill', fontFill === undefined ? display[theme].text : fontFill)
          .attr('font-size', fontSize === undefined ? fonts.fixed.sizeForWidth(w) : fontSize);
      if (orientation === 'right') {
        text.attr('x', () => -textPadding).attr('text-anchor', 'end');
      } else {
        text.attr('x', () => legendSize + textPadding).attr('text-anchor', 'start');
      }
      


    });
    
  }
  
  _impl.self = function() { return 'g' + (id ?  '#' + id : '.' + classed); }

  _impl.id = function() {
    return id;
  };
  
  _impl.defaultStyle = () => `${fonts.fixed.cssImport}
                              ${_impl.self()} text { 
                                font-family: ${fonts.fixed.family}; 
                                font-weight: ${fonts.fixed.weightMonochrome}; }
  `;
      
  _impl.childWidth = function() {
    let _inset = _impl.canonicalInset();
    return _inset.left + _inset.right + legendSize;
  };
  
  _impl.childHeight = function() {
    let _inset = _impl.canonicalInset();
    return _inset.top + _inset.bottom + legendSize;
  };
  
  _impl.childInset = function(inset) {
    if (inset == null) inset = 0;
    
    if (typeof inset !== 'object') {
      inset = { top: inset, left: inset, right: inset, bottom: inset };
    } else {
      inset = { top: inset.top, left: inset.left, right: inset.right, bottom: inset.bottom };
    }
    let legendOrientation = _impl.orientation();
    if (legendOrientation === 'top') {
      inset.top = inset.top + _impl.childHeight();
    } else if (legendOrientation === 'left') {
      inset.left = inset.left + _impl.childWidth();
    } else if (legendOrientation === 'right') { 
      inset.right = inset.right + _impl.childWidth();
    } else {
      inset.bottom = inset.bottom + _impl.childHeight();
    }   
    return inset;
  };        

  _impl.canonicalMargin = function() {
    let _margin = margin;
    if (_margin == null) _margin = 0;
    if (typeof _margin === 'object') {
      _margin = { top: _margin.top, bottom: _margin.bottom, left: _margin.left, right: _margin.right };
    } else {
      _margin = { top: _margin, bottom: _margin, left: _margin, right: _margin };
    }
    
    return _margin;    
  };  

  _impl.canonicalInset = function() {
    let _inset = inset;
    if (_inset == null) _inset = 0;
    if (typeof _inset === 'object') {
      _inset = { top: _inset.top, bottom: _inset.bottom, left: _inset.left, right: _inset.right };
    } else {
      _inset = { top: _inset, bottom: _inset, left: _inset, right: _inset };
    }
    
    return _inset;    
  };  
    
  _impl.classed = function(value) {
    return arguments.length ? (classed = value, _impl) : classed;
  };
    
  _impl.background = function(value) {
    return arguments.length ? (background = value, _impl) : background;
  };

  _impl.theme = function(value) {
    return arguments.length ? (theme = value, _impl) : theme;
  };  

  _impl.size = function(value) {
    return arguments.length ? (width = value, height = null, _impl) : width;
  };
    
  _impl.width = function(value) {
    return arguments.length ? (width = value, _impl) : width;
  };  

  _impl.height = function(value) {
    return arguments.length ? (height = value, _impl) : height;
  }; 

  _impl.scale = function(value) {
    return arguments.length ? (scale = value, _impl) : scale;
  }; 

  _impl.margin = function(value) {
    return arguments.length ? (margin = value, _impl) : margin;
  };   

  _impl.inset = function(value) {
    return arguments.length ? (inset = value, _impl) : inset;
  };  

  _impl.style = function(value) {
    return arguments.length ? (style = value, _impl) : style;
  }; 
  
  _impl.padding = function(value) {
    return arguments.length ? (padding = value, _impl) : padding;
  };   
  
  _impl.fill = function(value) {
    return arguments.length ? (fill = value, _impl) : fill;
  };    

  _impl.textPadding = function(value) {
    return arguments.length ? (textPadding = value, _impl) : textPadding;
  };  

  _impl.msize = function(value) {
    return arguments.length ? (msize = value, _impl) : msize;
  };   

  _impl.legendSize = function(value) {
    return arguments.length ? (legendSize = value, _impl) : legendSize;
  };  
      
  _impl.radius = function(value) {
    return arguments.length ? (radius = value, _impl) : radius;
  };    
  
  _impl.inset = function(value) {
    return arguments.length ? (inset = value, _impl) : inset;
  }; 
  
  _impl.orientation = function(value) {
    return arguments.length ? (orientation = value, _impl) : orientation;
  };     
              
  _impl.fontSize = function(value) {
    return arguments.length ? (fontSize = value, _impl) : fontSize;
  };                 

  _impl.fontFill = function(value) {
    return arguments.length ? (fontFill = value, _impl) : fontFill;
  };  

              
  return _impl;
}
276845
def relevant_legend_info(layers, categories=(@options[:category] ? [@options[:category]] : @options[:categories]))
      legend_info = layers.inject([]) do |arr, layer|
        if categories.nil? ||
         (categories.include?(layer.options[:category]) ||
         (layer.options[:categories] && (categories & layer.options[:categories]).size > 0) )
          
          data = layer.legend_data
          arr << data if data.is_a?(Hash)
          arr = arr + data if data.is_a?(Array)
        end
        arr
      end
    end
822593
function (legend, item) {
		
		item.legendSymbol = this.chart.renderer.rect(
			0,
			legend.baseline - 11,
			legend.options.symbolWidth,
			12,
			2
		).attr({
			zIndex: 3
		}).add(item.legendGroup);		
		
	}
1245116
def add_text(self, text, x, y, side='left', size=None,
                 rotation=None, ha='left', va='center',
                 family=None, **kws):
        """"""
        axes = self.axes
        if side == 'right':
            axes = self.get_right_axes()
        dynamic_size = False
        if size is None:
            size = self.conf.legendfont.get_size()
            dynamic_size = True
        t = axes.text(x, y, text, ha=ha, va=va, size=size,
                      rotation=rotation, family=family, **kws)
        self.conf.added_texts.append((dynamic_size, t))
        self.draw()
402391
def add_stats_plot(self):
        """"""

        keys = OrderedDict()
        keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'}
        keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'}
        keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'}

        plot_config = {
            'id': "disambiguated_alignments",
            'title': "Disambiguate: Alignment Counts",
            'cpswitch_counts_label': "# Reads",
            'ylab': "# Reads"
        }

        self.add_section(
            plot=bargraph.plot(self.data, keys, plot_config)
        )
755383
def color_text_boxes(ax, labels, colors, color_arrow=True):
    
    assert len(labels) == len(colors), \
        "Equal no. of colors and lables must be given"
    boxes = ax.findobj(mpl.text.Annotation)
    box_labels = lineid_plot.unique_labels(labels)
    for box in boxes:
        l = box.get_label()
        try:
            loc = box_labels.index(l)
        except ValueError:
            continue  # No changes for this box
        box.set_color(colors[loc])
        if color_arrow:
            box.arrow_patch.set_color(colors[loc])

    ax.figure.canvas.draw()
762438
public void point(char legend, Color color, double... coord) {
        add(new Point(legend, color, coord));
    }
1358152
def _update(self, axes_list):
        
        plot_type = self.settings['plot_style']
        if plot_type == '2D':
            # we expect exactely one image in the axes object (see ScriptDummy.plot)
            implot = axes_list[1].get_images()[0]
            # now update the data
            implot.set_data(self.data['random data'])

            colorbar = implot.colorbar

            if not colorbar is None:
                colorbar.update_bruteforce(implot)

        else:
            # fall back to default behaviour
            Script._update(self, axes_list)
465425
def add_chart(self, chart, row, col):
        
        self.__charts.append((chart, (row, col)))
567980
def add_segmented_colorbar(da, colors, direction):
    
    nbreak = len(colors)
    if direction == 'vertical':
        linewidth = da.height/nbreak
        verts = [None] * nbreak
        x1, x2 = 0, da.width
        for i, color in enumerate(colors):
            y1 = i * linewidth
            y2 = y1 + linewidth
            verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1))
    else:
        linewidth = da.width/nbreak
        verts = [None] * nbreak
        y1, y2 = 0, da.height
        for i, color in enumerate(colors):
            x1 = i * linewidth
            x2 = x1 + linewidth
            verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1))

    coll = mcoll.PolyCollection(verts,
                                facecolors=colors,
                                linewidth=0,
                                antialiased=False)
    da.add_artist(coll)
1010275
function drawItemBoxes(legend, barGroup) {
  legend.items.forEach(function(item, i) {
    var itemTop = itemY(legend, i);

    if (defined(item.imageUrl)) {
      barGroup.appendChild(
        svgElement(
          legend,
          "image",
          {
            "xlink:href": item.imageUrl,
            x: 0,
            y: itemTop,
            width: Math.min(item.imageWidth, legend.itemWidth + 4), // let them overlap slightly
            height: Math.min(item.imageHeight, legend.computedItemHeight + 4)
          },
          "item-icon"
        )
      );
      return;
    }

    if (defined(item.multipleColors)) {
      var columns = Math.sqrt(item.multipleColors.length) | 0;
      var rows = Math.ceil(item.multipleColors.length / columns) | 0;

      var colorCount = item.multipleColors.length;
      var index = 0;
      var y = itemTop;

      for (var row = 0; index < colorCount && row < rows; ++row) {
        var height =
          row === rows - 1
            ? legend.computedItemHeight - (y - itemTop)
            : legend.computedItemHeight / rows;

        var x = 0;
        for (var column = 0; index < colorCount && column < columns; ++column) {
          var color = item.multipleColors[index++];

          var width =
            column === columns - 1
              ? legend.itemWidth - x
              : legend.itemWidth / columns;

          barGroup.appendChild(
            svgElement(
              legend,
              "rect",
              {
                fill: color,
                x: x,
                y: y,
                width: width,
                height: height
              },
              "item-box"
            )
          );

          x += width;
        }

        y += height;
      }
    } else if (defined(item.color)) {
      const rectAttributes = {
        fill: item.color,
        x: 0,
        y: itemTop,
        width: legend.itemWidth,
        height: legend.computedItemHeight
      };
      if (defined(item.lineColor)) {
        rectAttributes.stroke = item.lineColor;
      }
      barGroup.appendChild(
        svgElement(legend, "rect", rectAttributes, "item-box")
      );
    }
  });
}
1151061
public CategorySeries addSeries(
      String seriesName,
      List<?> xData,
      List<? extends Number> yData,
      List<? extends Number> errorBars) {

    // Sanity checks
    sanityCheck(seriesName, xData, yData, errorBars);

    CategorySeries series;
    if (xData != null) {

      // Sanity check
      if (xData.size() != yData.size()) {
        throw new IllegalArgumentException("X and Y-Axis sizes are not the same!!!");
      }

      series = new CategorySeries(seriesName, xData, yData, errorBars, getDataType(xData));
    } else { // generate xData
      xData = Utils.getGeneratedDataAsList(yData.size());
      series = new CategorySeries(seriesName, xData, yData, errorBars, getDataType(xData));
    }

    seriesMap.put(seriesName, series);

    return series;
  }
496230
function addLegend(layer, data, options) {
    data = data || {};
    if ( !this.options.fills ) {
      return;
    }

    var html = '<dl>';
    var label = '';
    if ( data.legendTitle ) {
      html = '<h2>' + data.legendTitle + '</h2>' + html;
    }
    for ( var fillKey in this.options.fills ) {

      if ( fillKey === 'defaultFill') {
        if (! data.defaultFillName ) {
          continue;
        }
        label = data.defaultFillName;
      } else {
        if (data.labels && data.labels[fillKey]) {
          label = data.labels[fillKey];
        } else {
          label= fillKey + ': ';
        }
      }
      html += '<dt>' + label + '</dt>';
      html += '<dd style="background-color:' +  this.options.fills[fillKey] + '">&nbsp;</dd>';
    }
    html += '</dl>';

    var hoverover = d3.select( this.options.element ).append('div')
      .attr('class', 'datamaps-legend')
      .html(html);
  }