Create a plot canvas with the histogram plot of given data.
@param data a sample set.
@param k the number of bins.
@param prob if true, the z-axis will be in the probability scale.
@param palette the color palette.
430449
public static PlotCanvas plot(double[][] data, int k, boolean prob, Color[] palette) {
        return plot(data, k, k, prob, palette);
    }
776318
public static PlotCanvas plot(double[][] z) {
        double[] lowerBound = {0, 0};
        double[] upperBound = {z[0].length, z.length};
        PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false);
        canvas.add(new Heatmap(z));

        canvas.getAxis(0).setFrameVisible(false);
        canvas.getAxis(0).setLabelVisible(false);
        canvas.getAxis(0).setGridVisible(false);
        canvas.getAxis(1).setFrameVisible(false);
        canvas.getAxis(1).setLabelVisible(false);
        canvas.getAxis(1).setGridVisible(false);

        return canvas;
    }
1187492
public static PlotCanvas plot(String id, double[] data, String[] labels) {
        if (data.length != labels.length) {
            throw new IllegalArgumentException("Data size and label size don't match.");
        }

        double[] lowerBound = {0, Math.min(data)};
        double[] upperBound = {data.length, Math.max(data)};
        PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound);

        BarPlot plot = new BarPlot(labels, data);
        plot.setID(id);
        canvas.add(plot);

        double[] locations = new double[labels.length];
        for (int i = 0; i < labels.length; i++) {
            locations[i] = i + 0.5;
        }

        canvas.getAxis(0).addLabel(labels, locations);

        canvas.getAxis(0).setGridVisible(false);
        return canvas;
    }
440846
public static PlotCanvas plot(String id, double[] data, double[] breaks) {
        return plot(id, data, breaks, true);
    }
939616
def scatterplot(self, x, y, **kw):
        
        self.panel.scatterplot(x, y, **kw)
98931
function KDE( canvas, width, height, left, top ) {

		var graph, data, area, rug, edges, axes, annotations, title, text;

		// [1] Instantiate a new graph generator and configure:
		graph = xfig.graph( canvas )
			.width( width )
			.height( height )
			.position({
				'left': left,
				'top': top
			})
			.xMin( 0 )
			.xMax( 1 )
			.yMin( 0 );

		// Create the graph:
		graph.create( 'kde' );

		// Get data:
		d3.json( 'data/kde.data.json', function ( error, json ) {

			var max;

			// [2] Instantiate a new data generator and configure:
			data = xfig.data( json )
				.accessors( 'x', function ( d ) {
					return d[ 0 ];
				})
				.accessors( 'y', function ( d ) {
					return d[ 1 ];
				});

			// Format the data and calculate the KDE:
			data.format( [ 'x', 'y' ] )
				.kde(
					function ( d ) {
						return d[ 1 ];
					}, 0, 1
				);

			// Bind the data instance to the graph:
			max = data.max( function ( d ) {
				return d[ 1 ];
			});
			max += max * 0.05;
			graph.data( data )
				.yMax( max );

			// [3] Instantiate a new area chart generator and configure:
			area = xfig.area( graph )
				.labels( [ 'data 0' ] );

			// Create the area chart:
			area.create();

			// [4] Instantiate a new data generator and configure:
			data = xfig.data( json )
				.accessors( 'x', function ( d ) {
					return d[ 0 ];
				})
				.accessors( 'y', function ( d ) {
					return d[ 1 ];
				});

			// Format the data:
			data.format( [ 'x', 'y' ] )
				.extract( function ( d ) {
					return d[ 1 ];
				});

			// Bind the data instance to the graph:
			graph.data( data );

			// [5] Instantiate a new rug chart generator and configure:
			rug = xfig.rug( graph )
				.labels( [ 'data 0' ] );

			// Create the rug chart:
			rug.create();

			// [6] Instantiate a new axes generator and configure:
			axes = xfig.axes( graph )
				.yLabel( 'density' );

			// Create the axes:
			axes.create();

			// [7] Instantiate a new annotations generator and configure:
			annotations = xfig.annotations( graph );

			// Create the annotations element:
			annotations.create();

			// [7.1] Instantiate a new title instance and configure:
			title = annotations.title()
				.top( -30 )
				.left( 250 );

			// Add a (sub)title:
			title.create( 'KDE' );

			// [7.2] Instantiate a new text instance and configure:
			text = annotations.text()
				.width( 200 )
				.height( 100 )
				.top( 50 )
				.left( 310 );

			// Add a text annotation:
			text.create( 'This is another text annotation, which may run multiple lines.' );

		});

	}
1071964
function (data, width, height, normalize, colorFunc, isInRange) {
        var brush = this._getBrush();
        var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
        var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
        var r = this.pointSize + this.blurSize;

        var canvas = this.canvas;
        var ctx = canvas.getContext('2d');
        var len = data.length;
        canvas.width = width;
        canvas.height = height;
        for (var i = 0; i < len; ++i) {
            var p = data[i];
            var x = p[0];
            var y = p[1];
            var value = p[2];

            // calculate alpha using value
            var alpha = normalize(value);

            // draw with the circle brush with alpha
            ctx.globalAlpha = alpha;
            ctx.drawImage(brush, x - r, y - r);
        }

        if (!canvas.width || !canvas.height) {
            // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
            // 'CanvasRenderingContext2D': The source height is 0."
            return canvas;
        }

        // colorize the canvas using alpha value and set with gradient
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        var pixels = imageData.data;
        var offset = 0;
        var pixelLen = pixels.length;
        var minOpacity = this.minOpacity;
        var maxOpacity = this.maxOpacity;
        var diffOpacity = maxOpacity - minOpacity;

        while (offset < pixelLen) {
            var alpha = pixels[offset + 3] / 256;
            var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
            // Simple optimize to ignore the empty data
            if (alpha > 0) {
                var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
                // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
                alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
                pixels[offset++] = gradient[gradientOffset];
                pixels[offset++] = gradient[gradientOffset + 1];
                pixels[offset++] = gradient[gradientOffset + 2];
                pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
            }
            else {
                offset += 4;
            }
        }
        ctx.putImageData(imageData, 0, 0);

        return canvas;
    }
1118388
public static <T> Multiset<Integer> histogram(Multiset<T> data) {
    return histogram(data, Ordering.<Integer>natural());
  }
266699
private static double[][] histogram(double[] data, int k, boolean prob) {
        double[][] hist = smile.math.Histogram.histogram(data, k);

        // The number of bins may be extended to cover all data.
        k = hist[0].length;
        double[][] freq = new double[k][2];
        for (int i = 0; i < k; i++) {
            freq[i][0] = (hist[0][i] + hist[1][i]) / 2.0;
            freq[i][1] = hist[2][i];
        }

        if (prob) {
            double n = data.length;
            for (int i = 0; i < k; i++) {
                freq[i][1] /= n;
            }
        }

        return freq;
    }
1087624
public ByteBuffer interpolateColorMap( int mapType, ByteBuffer data, int dataOffset ) {
        int dataLength = data.capacity() - dataOffset;
        /* Allocate colour map output buffer using 4 bytes per cell value (RGBA) */
        ByteBuffer cmapBuffer = ByteBuffer.allocate(dataLength);

        /* Set buffer position */
        data.position(dataOffset);

        if (mapType > 0) {
            while( data.hasRemaining() ) {
                /*
                 * For each value in the array get the index from the rules map and then translate
                 * the rule.
                 */
                int f = data.getInt();

                cmapBuffer.put(f == Integer.MAX_VALUE ? blank : getColor((float) f));
            }
        } else if (mapType == -1) {
            while( data.hasRemaining() ) {
                /*
                 * For each value in the array get the index from the rules map and then translate
                 * the rule.
                 */
                float f = data.getFloat();
                cmapBuffer.put(Float.isNaN(f) ? blank : getColor(f));
            }
        } else if (mapType == -2) {
            while( data.hasRemaining() ) {
                /*
                 * For each value in the array get the index from the rules map and then translate
                 * the rule.
                 */
                float f = (float) data.getDouble();
                cmapBuffer.put(Float.isNaN(f) ? blank : getColor(f));

                // if (!Float.isNaN(f) && f > 0)
                // System.out.println("COLOR-TABLE->" + f + " has color "
                // + (Float.isNaN(f) ? blank : getColor(f)));

                /*
                 * test the data map
                 */
                /*
                 * System.out.print(f + " "); if (counter == 1024) { System.out.println(); counter =
                 * 1; } else { counter++; }
                 */

            }
        }
        return cmapBuffer;
    }
103104
def draw(self, X, y, **kwargs):
        
        # Convert from dataframe
        if is_dataframe(X):
            X = X.values

        # Clean out nans and warn that the user they aren't plotted
        nan_warnings.warn_if_nans_exist(X)
        X, y = nan_warnings.filter_missing(X, y)

        # Get the shape of the data
        nrows, ncols = X.shape

        # Set the axes limits
        self.ax.set_xlim([-1,1])
        self.ax.set_ylim([-1,1])

        # Create the colors
        # TODO: Allow both colormap, listed colors, and palette definition
        # TODO: Make this an independent function or property for override!
        color_values = resolve_colors(
            n_colors=len(self.classes_), colormap=self.colormap, colors=self.color
        )
        self._colors = dict(zip(self.classes_, color_values))

        # Create a data structure to hold scatter plot representations
        to_plot = {}
        for kls in self.classes_:
            to_plot[kls] = [[], []]

        # Compute the arcs around the circumference for each feature axis
        # TODO: make this an independent function for override
        s = np.array([
                (np.cos(t), np.sin(t))
                for t in [
                    2.0 * np.pi * (i / float(ncols))
                    for i in range(ncols)
                ]
            ])

        # Compute the locations of the scatter plot for each class
        # Normalize the data first to plot along the 0, 1 axis
        for i, row in enumerate(self.normalize(X)):
            row_ = np.repeat(np.expand_dims(row, axis=1), 2, axis=1)
            xy   = (s * row_).sum(axis=0) / row.sum()
            kls = self.classes_[y[i]]

            to_plot[kls][0].append(xy[0])
            to_plot[kls][1].append(xy[1])

        # Add the scatter plots from the to_plot function
        # TODO: store these plots to add more instances to later
        # TODO: make this a separate function
        for i, kls in enumerate(self.classes_):
            self.ax.scatter(
                to_plot[kls][0], to_plot[kls][1], color=self._colors[kls],
                label=str(kls), alpha=self.alpha, **kwargs
            )

        # Add the circular axis path
        # TODO: Make this a seperate function (along with labeling)
        self.ax.add_patch(patches.Circle(
            (0.0, 0.0), radius=1.0, facecolor='none', edgecolor='grey', linewidth=.5
        ))

        # Add the feature names
        for xy, name in zip(s, self.features_):
            # Add the patch indicating the location of the axis
            self.ax.add_patch(patches.Circle(xy, radius=0.025, facecolor='#777777'))

            # Add the feature names offset around the axis marker
            if xy[0] < 0.0 and xy[1] < 0.0:
                self.ax.text(xy[0] - 0.025, xy[1] - 0.025, name, ha='right', va='top', size='small')
            elif xy[0] < 0.0 and xy[1] >= 0.0:
                self.ax.text(xy[0] - 0.025, xy[1] + 0.025, name, ha='right', va='bottom', size='small')
            elif xy[0] >= 0.0 and xy[1] < 0.0:
                self.ax.text(xy[0] + 0.025, xy[1] - 0.025, name, ha='left', va='top', size='small')
            elif xy[0] >= 0.0 and xy[1] >= 0.0:
                self.ax.text(xy[0] + 0.025, xy[1] + 0.025, name, ha='left', va='bottom', size='small')

        self.ax.axis('equal')
411878
def plot_data(self, proj, ax):
        
        x, y = proj
        ax.scatter(self.ig.independent_data[x],
                   self.ig.dependent_data[y], c='b')
995088
public static void histogram( GrayU8 input , int minValue , int histogram[] ) {
		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplImageStatistics_MT.histogram(input,minValue,histogram);
		} else {
			ImplImageStatistics.histogram(input,minValue,histogram);
		}
	}
23014
function (data) {

            if (this.initialized === true) {
                return;
            }

            // to automatically increment z index
            var zOrder = 0;
            var self = this;

            // Tileset information
            if (!this.tilesets) {
                // make sure we have a TilesetGroup Object
                this.tilesets = new me.TMXTilesetGroup();
            }

            // parse all tileset objects
            if (typeof (data.tilesets) !== "undefined") {
                var tilesets = data.tilesets;
                tilesets.forEach(function (tileset) {
                    // add the new tileset
                    self.tilesets.add(readTileset(tileset));
                });
            }

            // check if a user-defined background color is defined
            if (this.backgroundcolor) {
                this.layers.push(
                    me.pool.pull("me.ColorLayer",
                        "background_color",
                        this.backgroundcolor,
                        zOrder++
                    )
                );
            }

            // check if a background image is defined
            if (this.background_image) {
                // add a new image layer
                this.layers.push(
                    me.pool.pull("me.ImageLayer",
                        0, 0, {
                            name : "background_image",
                            image : this.background_image,
                            z : zOrder++
                        }
                ));
            }

            data.layers.forEach(function (layer) {
                switch (layer.type) {
                    case "imagelayer":
                        self.layers.push(readImageLayer(self, layer, zOrder++));
                        break;

                    case "tilelayer":
                        self.layers.push(readLayer(self, layer, zOrder++));
                        break;

                    // get the object groups information
                    case "objectgroup":
                        self.objectGroups.push(readObjectGroup(self, layer, zOrder++));
                        break;

                    // get the object groups information
                    case "group":
                        self.objectGroups.push(readObjectGroup(self, layer, zOrder++));
                        break;

                    default:
                        break;
                }
            });

            this.initialized = true;
        }
50888
def plot_data(self, proj, ax):
        
        x, y = proj
        x_data = self.ig.independent_data[x]
        y_data = self.ig.dependent_data[y]
        projected_data = np.column_stack((x_data, y_data)).T
        kde = gaussian_kde(projected_data)

        xx, yy = np.meshgrid(self.ig._x_points[x], self.ig._y_points[y])
        x_grid = xx.flatten()
        y_grid = yy.flatten()

        contour_grid = kde.pdf(np.column_stack((x_grid, y_grid)).T)
        # This is an fugly kludge, but it seems nescessary to make low density
        # areas show up.
        if self.ig.log_contour:
            contour_grid = np.log(contour_grid)
            vmin = -7
        else:
            vmin = None
        ax.contourf(xx, yy, contour_grid.reshape(xx.shape),
                    50, vmin=vmin, cmap='Blues')
203320
def make_palette_chunks(palette):
    

    p = bytearray()
    t = bytearray()

    for x in palette:
        p.extend(x[0:3])
        if len(x) > 3:
            t.append(x[3])
    if t:
        return p, t
    return p, None
1247695
def _plot_kmf_single(df,
                     condition_col,
                     survival_col,
                     censor_col,
                     threshold,
                     title,
                     xlabel,
                     ylabel,
                     ax,
                     with_condition_color,
                     no_condition_color,
                     with_condition_label,
                     no_condition_label,
                     color_map,
                     label_map,
                     color_palette,
                     ci_show,
                     print_as_title):
    
    # make color inputs consistent hex format
    if colors.is_color_like(with_condition_color):
        with_condition_color = colors.to_hex(with_condition_color)
    if colors.is_color_like(no_condition_color):
        no_condition_color = colors.to_hex(no_condition_color)
    ## prepare data to be plotted; producing 3 outputs:
    # - `condition`, series containing category labels to be plotted
    # - `label_map` (mapping condition values to plot labels)
    # - `color_map` (mapping condition values to plotted colors)
    if threshold is not None:
        is_median = threshold == "median"
        if is_median:
            threshold = df[condition_col].median()
        label_suffix = float_str(threshold)
        condition = df[condition_col] > threshold
        default_label_no_condition = "%s ≤ %s" % (condition_col, label_suffix)
        if is_median:
            label_suffix += " (median)"
        default_label_with_condition = "%s > %s" % (condition_col, label_suffix)
        with_condition_label = with_condition_label or default_label_with_condition
        no_condition_label = no_condition_label or default_label_no_condition
        if not label_map:
            label_map = {False: no_condition_label,
                         True: with_condition_label}
        if not color_map:
            color_map = {False: no_condition_color,
                         True: with_condition_color}
    elif df[condition_col].dtype == 'O' or df[condition_col].dtype.name == "category":
        condition = df[condition_col].astype("category")
        if not label_map:
            label_map = dict()
            [label_map.update({condition_value: '{} = {}'.format(condition_col,
                                                        condition_value)})
                     for condition_value in condition.unique()]
        if not color_map:
            rgb_values = sb.color_palette(color_palette, len(label_map.keys()))
            hex_values = [colors.to_hex(col) for col in rgb_values]
            color_map = dict(zip(label_map.keys(), hex_values))
    elif df[condition_col].dtype == 'bool':
        condition = df[condition_col]
        default_label_with_condition = "= {}".format(condition_col)
        default_label_no_condition = "¬ {}".format(condition_col)
        with_condition_label = with_condition_label or default_label_with_condition
        no_condition_label = no_condition_label or default_label_no_condition
        if not label_map:
            label_map = {False: no_condition_label,
                         True: with_condition_label}
        if not color_map:
            color_map = {False: no_condition_color,
                         True: with_condition_color}
    else:
        raise ValueError('Don\'t know how to plot data of type\
                         {}'.format(df[condition_col].dtype))

    # produce kmf plot for each category (group) identified above
    kmf = KaplanMeierFitter()
    grp_desc = list()
    grp_survival_data = dict()
    grp_event_data = dict()
    grp_names = list(condition.unique())
    for grp_name, grp_df in df.groupby(condition):
        grp_survival = grp_df[survival_col]
        grp_event = (grp_df[censor_col].astype(bool))
        grp_label = label_map[grp_name]
        grp_color = color_map[grp_name]
        kmf.fit(grp_survival, grp_event, label=grp_label)
        desc_str = "# {}: {}".format(grp_label, len(grp_survival))
        grp_desc.append(desc_str)
        grp_survival_data[grp_name] = grp_survival
        grp_event_data[grp_name] = grp_event
        if ax:
            ax = kmf.plot(ax=ax, show_censors=True, ci_show=ci_show, color=grp_color)
        else:
            ax = kmf.plot(show_censors=True, ci_show=ci_show, color=grp_color)

    ## format the plot
    # Set the y-axis to range 0 to 1
    ax.set_ylim(0, 1)
    y_tick_vals = ax.get_yticks()
    ax.set_yticklabels(["%d" % int(y_tick_val * 100) for y_tick_val in y_tick_vals])
    # plot title
    if title:
        ax.set_title(title)
    elif print_as_title:
        ax.set_title(' | '.join(grp_desc))
    else:
        [print(desc) for desc in grp_desc]
    # axis labels
    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)
    
    ## summarize analytical version of results
    ## again using same groups as are plotted
    if len(grp_names) == 2:
        # use log-rank test for 2 groups
        results = logrank_test(grp_survival_data[grp_names[0]],
                               grp_survival_data[grp_names[1]],
                               event_observed_A=grp_event_data[grp_names[0]],
                               event_observed_B=grp_event_data[grp_names[1]])
    elif len(grp_names) == 1:
        # no analytical result for 1 or 0 groups
        results = NullSurvivalResults()
    else:
        # cox PH fitter for >2 groups
        cf = CoxPHFitter()
        cox_df = patsy.dmatrix('+'.join([condition_col, survival_col,
                                         censor_col]),
                               df, return_type='dataframe')
        del cox_df['Intercept']
        results = cf.fit(cox_df, survival_col, event_col=censor_col)
        results.print_summary()
    # add metadata to results object so caller can print them
    results.survival_data_series = grp_survival_data
    results.event_data_series = grp_event_data
    results.desc = grp_desc
    return results