Draw histograms of each category in a column.
174209
def pivot_hist(self, pivot_column_label, value_column_label, overlay=True, width=6, height=4, **vargs):
        """"""
        warnings.warn("pivot_hist is deprecated; use "
                      "hist(value_column_label, group=pivot_column_label), or "
                      "with side_by_side=True if you really want side-by-side "
                      "bars.")
        pvt_labels = np.unique(self[pivot_column_label])
        pvt_columns = [self[value_column_label][np.where(self[pivot_column_label] == pivot)] for pivot in pvt_labels]
        n = len(pvt_labels)
        colors = list(itertools.islice(itertools.cycle(self.chart_colors), n))
        if overlay:
            plt.figure(figsize=(width, height))
            vals, bins, patches = plt.hist(pvt_columns, color=colors, **vargs)
            plt.legend(pvt_labels)
        else:
            _, axes = plt.subplots(n, 1, figsize=(width, height * n))
            vals = []
            bins = None
            for axis, label, column, color in zip(axes, pvt_labels, pvt_columns, colors):
                if isinstance(bins, np.ndarray):
                    avals, abins, patches = axis.hist(column, color=color, bins=bins, **vargs)
                else:
                    avals, abins, patches = axis.hist(column, color=color, **vargs)
                axis.set_xlabel(label, fontsize=16)
                vals.append(avals)
                if not isinstance(bins, np.ndarray):
                    bins = abins
                else:
                    assert bins.all() == abins.all(), "Inconsistent bins in hist"
        t = type(self)()
        t['start'] = bins[0:-1]
        t['end'] = bins[1:]
        for label, column in zip(pvt_labels,vals):
            t[label] = column
147771
def categorize(
    data, col_name: str = None, new_col_name: str = None,
    categories: dict = None, max_categories: float = 0.15
):
    

    _categories = {}
    if col_name is None:
        if categories is not None:
            raise Exception(
                'col_name is None when categories was defined.'
            )
        # create a list of cols with all object columns
        cols = [
            k for k in data.keys()
            if data[k].dtype == 'object' and
            (data[k].unique() / data[k].count()) <= max_categories
        ]
    else:
        # create a list with col_name
        if new_col_name is not None:
            data[new_col_name] = data[col_name]
            col_name = new_col_name

        cols = [col_name]

    for c in cols:
        if categories is not None:
            # assert all keys is a number
            assert all(type(k) in (int, float) for k in categories.keys())
            # replace values using given categories dict
            data[c].replace(categories, inplace=True)
            # change column to categorical type
            data[c] = data[c].astype('category')
            # update categories information
            _categories.update({c: categories})
        else:
            # change column to categorical type
            data[c] = data[c].astype('category')
            # change column to categorical type
            _categories.update({
                c: dict(enumerate(
                    data[c].cat.categories,
                ))
            })
    return _categories
308724
def _with_columns(self, columns):
        """"""
        table = type(self)()
        for label, column in zip(self.labels, columns):
            self._add_column_and_format(table, label, column)
        return table
1152667
def draw_separators(self):
        """"""
        total = 1
        self._timeline.create_line((0, 1, self.pixel_width, 1))
        for index, (category, label) in enumerate(self._category_labels.items()):
            height = label.winfo_reqheight()
            self._rows[category] = (total, total + height)
            total += height
            self._timeline.create_line((0, total, self.pixel_width, total))
        pixel_height = total
        self._timeline.config(height=pixel_height)
565077
def _histplot_op(ax, data, **kwargs):
    """"""
    bins = get_bins(data)
    ax.hist(data, bins=bins, align="left", density=True, **kwargs)
    return ax
596283
public static void histogram( GrayS8 input , int minValue , int histogram[] ) {
		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplImageStatistics_MT.histogram(input,minValue,histogram);
		} else {
			ImplImageStatistics.histogram(input,minValue,histogram);
		}
	}
509555
def _get_unique_categories(self, df):
        """"""

        categories = []
        for col in self._categorical_columns:
            categocial = pd.Categorical(df[col])
            col_categories = list(map(str, categocial.categories))
            col_categories.append('_UNKNOWN')
            categories.append(col_categories)
        return categories
156967
def horiz_rows(labels, data, normal_dat, args, colors):
    """"""
    val_min = find_min(data)

    for i in range(len(labels)):
        if args['no_labels']:
            # Hide the labels.
            label = ''
        else:
            label = "{:<{x}}: ".format(labels[i],
                                       x=find_max_label_length(labels))

        values = data[i]
        num_blocks = normal_dat[i]

        for j in range(len(values)):
            # In Multiple series graph 1st category has label at the beginning,
            # whereas the rest categories have only spaces.
            if j > 0:
                len_label = len(label)
                label = ' ' * len_label
            tail = ' {}{}'.format(args['format'].format(values[j]),
                                  args['suffix'])
            if colors:
                color = colors[j]
            else:
                color = None

            if not args['vertical']:
                print(label, end="")

            yield(values[j], int(num_blocks[j]), val_min, color)

            if not args['vertical']:
                print(tail)
11411
def ranges(self):
        """"""
        bucket_fns = {
            'boolean': linear_buckets,
            'flag': linear_buckets,
            'count': linear_buckets,
            'enumerated': linear_buckets,
            'categorical': linear_buckets,
            'linear': linear_buckets,
            'exponential': exponential_buckets,
        }

        if self._kind not in bucket_fns:
            raise ParserError('Unknown kind "%s" for histogram "%s".' % (self._kind, self._name))

        fn = bucket_fns[self._kind]
        return fn(self.low(), self.high(), self.n_buckets())
588680
function () {
		
		var columns = this.columns,
			firstCol,
			type,
			options = this.options,
			valueCount,
			series,
			data,
			i,
			j,
			seriesIndex;
			
		
		if (options.complete) {

			this.getColumnDistribution();
			
			// Use first column for X data or categories?
			if (columns.length > 1) {
				firstCol = columns.shift();
				if (this.headerRow === 0) {
					firstCol.shift(); // remove the first cell
				}
				
				
				if (firstCol.isDatetime) {
					type = 'datetime';
				} else if (!firstCol.isNumeric) {
					type = 'category';
				}
			}

			// Get the names and shift the top row
			for (i = 0; i < columns.length; i++) {
				if (this.headerRow === 0) {
					columns[i].name = columns[i].shift();
				}
			}
			
			// Use the next columns for series
			series = [];
			for (i = 0, seriesIndex = 0; i < columns.length; seriesIndex++) {

				// This series' value count
				valueCount = Highcharts.pick(this.valueCount.individual[seriesIndex], this.valueCount.global);
				
				// Iterate down the cells of each column and add data to the series
				data = [];
				for (j = 0; j < columns[i].length; j++) {
					data[j] = [
						firstCol[j], 
						columns[i][j] !== undefined ? columns[i][j] : null
					];
					if (valueCount > 1) {
						data[j].push(columns[i + 1][j] !== undefined ? columns[i + 1][j] : null);
					}
					if (valueCount > 2) {
						data[j].push(columns[i + 2][j] !== undefined ? columns[i + 2][j] : null);
					}
					if (valueCount > 3) {
						data[j].push(columns[i + 3][j] !== undefined ? columns[i + 3][j] : null);
					}
					if (valueCount > 4) {
						data[j].push(columns[i + 4][j] !== undefined ? columns[i + 4][j] : null);
					}
				}

				// Add the series
				series[seriesIndex] = {
					name: columns[i].name,
					data: data
				};

				i += valueCount;
			}
			
			// Do the callback
			options.complete({
				xAxis: {
					type: type
				},
				series: series
			});
		}
	}
553305
def get_category(self, column):
        
        result = pd.Series(index=column.index)

        for category, stats in self.probability_map.items():
            start, end = stats[0]
            result[(start < column) & (column < end)] = category

        return result
315882
def chart(colors, data, args, labels):
    """"""
    len_categories = len(data[0])
    if len_categories > 1:
        # Stacked graph
        if args['stacked']:
            normal_dat = normalize(data, args['width'])
            stacked_graph(labels, data, normal_dat, len_categories,
                          args, colors)
            return

        if not colors:
            colors = [None] * len_categories

        # Multiple series graph with different scales
        # Normalization per category
        if args['different_scale']:
            for i in range(len_categories):
                cat_data = []
                for dat in data:
                    cat_data.append([dat[i]])

                # Normalize data, handle negatives.
                normal_cat_data = normalize(cat_data, args['width'])

                # Generate data for a row.
                for row in horiz_rows(labels, cat_data, normal_cat_data,
                                      args, [colors[i]]):
                    # Print the row
                    if not args['vertical']:
                        print_row(*row)
                    else:
                        vertic = vertically(*row, args=args)

                # Vertical graph
                if args['vertical']:
                    print_vertical(vertic, labels, colors[i], args)

                print()
                value_list.clear(), zipped_list.clear(), vertical_list.clear()
                return

    # One category/Multiple series graph with same scale
    # All-together normalization
    if not args['stacked']:
        normal_dat = normalize(data, args['width'])
        for row in horiz_rows(labels, data, normal_dat, args, colors):
            if not args['vertical']:
                print_row(*row)
            else:
                vertic = vertically(*row, args=args)

        if args['vertical'] and len_categories == 1:
            if colors:
                color = colors[0]
            else:
                color = None

            print_vertical(vertic, labels, color, args)

        print()
535677
def histogram(title, title_x, title_y,
              x, bins_x):
    
    plt.figure()
    plt.hist(x, bins_x)
    plt.xlabel(title_x)
    plt.ylabel(title_y)
    plt.title(title)
1223153
def draw_histogram():
    

    mu, sigma = 100, 15
    x = mu + sigma * numpy.random.randn(10000)
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

    ax.set_xlabel('Random number generated')
    ax.set_ylabel('Probability')
    ax.set_xlim(40, 160)
    ax.set_ylim(0, 0.03)
    ax.grid(True)

    pyplot.savefig(histogram_filename)
48526
def iter_series(self, workbook, row, col):
        
        for series in self.__series:
            series = dict(series)
            series["values"] = series["values"].get_formula(workbook, row, col)
            if "categories" in series:
                series["categories"] = series["categories"].get_formula(workbook, row, col)
            yield series
683628
def draw(self,
             category,
             num_top_words_to_annotate=4,
             words_to_annotate=[],
             scores=None,
             transform=percentile_alphabetical):
        '''
        '''
        try:
            import matplotlib.pyplot as plt
        except:
            raise Exception("matplotlib and mpld3 need to be installed to use this function.")
        try:
            from mpld3 import plugins, fig_to_html
        except:
            raise Exception("mpld3 need to be installed to use this function.")
        all_categories, other_categories = self._get_category_names(category)
        df = self._term_rank_score_and_frequency_df(all_categories, category, other_categories, scores)
        if self.x_coords is None:
            df['x'], df['y'] = self._get_coordinates_from_transform_and_jitter_frequencies \
                (category, df, other_categories, transform)
        df_to_annotate = df[(df['not category score rank'] <= num_top_words_to_annotate)
                            | (df['category score rank'] <= num_top_words_to_annotate)
                            | df['term'].isin(words_to_annotate)]
        words = list(df['term'])

        font = {'family': 'sans-serif',
                'color': 'black',
                'weight': 'normal',
                'size': 'large'}

        fig, ax = plt.subplots()
        plt.figure(figsize=(10, 10))
        plt.gcf().subplots_adjust(bottom=0.2)
        plt.gcf().subplots_adjust(right=0.2)

        points = ax.scatter(self.x_coords,
                            self.y_coords,
                            c=-df['color_scores'],
                            cmap='seismic',
                            s=10,
                            edgecolors='none',
                            alpha=0.9)
        tooltip = plugins.PointHTMLTooltip(points,
                                           ['<span id=a>%s</span>' % w for w in words],
                                           css='#a {background-color: white;}')
        plugins.connect(fig, tooltip)
        ax.set_ylim([-.2, 1.2])
        ax.set_xlim([-.2, 1.2])
        ax.xaxis.set_ticks([0., 0.5, 1.])
        ax.yaxis.set_ticks([0., 0.5, 1.])
        ax.set_ylabel(category.title() + ' Frequency Percentile', fontdict=font, labelpad=20)
        ax.set_xlabel('Not ' + category.title() + ' Frequency Percentile', fontdict=font, labelpad=20)

        for i, row in df_to_annotate.iterrows():
            # alignment_criteria = row['category score rank'] < row['not category score rank']
            alignment_criteria = i % 2 == 0
            horizontalalignment = 'right' if alignment_criteria else 'left'
            verticalalignment = 'bottom' if alignment_criteria else 'top'
            term = row['term']
            ax.annotate(term,
                        (self.x_coords[i], self.y_data[i]),
                        size=15,
                        horizontalalignment=horizontalalignment,
                        verticalalignment=verticalalignment,
                        )
        # texts.append(
        # ax.text(row['dem freq scaled'], row['rep freq scaled'], row['word'])
        # )
        # adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r', lw=0.5))
        plt.show()
        return df, fig_to_html(fig)
457498
void computeDescriptor(int row, int col) {
		// set location to top-left pixel
		locations.grow().set(col* pixelsPerCell,row* pixelsPerCell);

		TupleDesc_F64 d = descriptions.grow();

		int indexDesc = 0;
		for (int i = 0; i < cellsPerBlockY; i++) {
			for (int j = 0; j < cellsPerBlockX; j++) {
				Cell c = cells[(row+i)*cellCols + (col+j)];

				for (int k = 0; k < c.histogram.length; k++) {
					d.value[indexDesc++] = c.histogram[k];
				}
			}
		}

		// Apply SIFT style L2-Hys normalization
		DescribeSiftCommon.normalizeDescriptor(d,0.2);
	}