def plot_histogram(hist, width=0.9,
                   title='', xlabel=None, datetime_format="%b %Y",
                   labels=None, color=None, alpha=None, normalize=True, percent=False, padding=0.03, num_labels=24,
                   formatter=None, ylabel_precision=2, resolution=3,
                   figsize=None, line_color='#C0C0C0', bg_color='white', bg_alpha=1, tight_layout=True,
                   ylabel=None, grid='on', rotation=-60, ha='left',
                   save_path='plot_histogram', dpi=200):
    """Plot a bar chart from np.histogram data

    >>> plot_histogram(np.histogram([1]*5+[3]*2+list(range(20))+[19.1]), alpha=1)  # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    ((array([7, 4, 2, 2, 2, 2, 2, 2, 2, 3]),
    array([  0.  ,   1.91,   3.82,   5.73,   7.64,   9.55,  11.46,  13.37,
        15.28,  17.19,  19.1 ])),
    <matplotlib.figure.Figure at ...)
    """
    his0, his1 = hist[0], hist[1]
    if len(his1) == len(his0) + 1:
        his0, his1 = his1[:-1], his0
    elif len(his0) == len(his1) + 1:
        his0 = his0[:-1]

    resolution = resolution or 3
    if labels in (None, 0, 'date', 'datetime'):
        try:
            labels = prettify_datetimes(['-'.join(str(val) for val in datetime_from_ordinal_float(val).timetuple()[:resolution]) for val in his0],
                format=datetime_format, max_nonempty_strings=num_labels)
        except ValueError:
            labels = [('{0:.' + str(resolution) + 'g}').format(val) for val in his0]
    elif labels == False:
        labels = [''] * len(his0)
    if len(labels) != len(his0) or not all(isinstance(val, basestring) for val in labels):
        labels = list(str(s) for s in labels)
        labels += [''] * (len(his0) - len(labels))
    
    labels = thin_string_list(labels, 50)

    fig = plt.gcf()
    if figsize and len(figsize)==2:
        fig.set_size_inches(figsize[0], figsize[1], forward=True)
    if bg_color or bg_alpha:
        fig.set_facecolor(bg_color)
        fig.set_alpha(bg_alpha)
    if not fig.axes:
        ax = fig.add_subplot(111)
    else:
        ax = fig.gca()

    color = color or 'b'
    alpha = alpha or .8
    xlabel = xlabel or ''

    xwidth = (width or 0.9) * pd.np.min(pd.np.diff(his0))

    if not isinstance(ylabel, basestring):
        ylabel = 'Count (Number of Occurrences)'


    xwidth = (width or 0.9) * pd.np.min(pd.np.diff(his0))

    ax.bar(his0, his1, width=xwidth, color=color, alpha=alpha)

    print(his0)
    plt.xticks([dy + padding*xwidth for dy in his0], labels, rotation=rotation, ha=ha)
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if title:
        plt.title(title)
    if formatter and callable(formatter):
        ax.yaxis.set_major_formatter(plt.matplotlib.ticker.FuncFormatter(formatter))
    ax.grid(grid, color=(line_color or 'gray'))

    # set all the colors and transparency values 
    fig.patch.set_facecolor(bg_color)
    fig.patch.set_alpha(bg_alpha)
    ax.patch.set_alpha(bg_alpha)
    ax.patch.set_facecolor(bg_color)

    if line_color:
        for spine in ax.spines.values():
            spine.set_color(line_color)
        ax.tick_params(axis='x', colors=line_color)
        ax.tick_params(axis='y', colors=line_color)
        ax.xaxis.label.set_color(line_color)
        ax.yaxis.label.set_color(line_color)
        ax.title.set_color(line_color)

    if tight_layout:
        plt.tight_layout()

    try:
        # ipython notebook overrides plt.show and doesn't have a block kwarg
        plt.show(block=False)
    except TypeError:
        plt.show()

    if save_path:
        if os.path.isfile(save_path + '.png'):
            i = 2
            save_path2 = save_path + '--{0}'.format(i)
            while os.path.isfile(save_path2 + '.png'):
                i += 1
                save_path2 = save_path + '--{0}'.format(i)
            save_path = save_path2
        plt.savefig(save_path, facecolor=fig.get_facecolor(), edgecolor='none', dpi=dpi)

    # return in standard numpy histogram format, values before bins, and bins include all fenceposts (edges)
    his0, his1 = pd.np.array(his0), pd.np.array(his1)
    his0 = np.append(his0, 2 * his0[-1] - his0[-2])
    return (his1, his0), fig
def plot_histogram ( hist , width = 0.9 , title = '' , xlabel = None , datetime_format = "%b %Y" , labels = None , color = None , alpha = None , normalize = True , percent = False , padding = 0.03 , num_labels = 24 , formatter = None , ylabel_precision = 2 , resolution = 3 , figsize = None , line_color = '#C0C0C0' , bg_color = 'white' , bg_alpha = 1 , tight_layout = True , ylabel = None , grid = 'on' , rotation = - 60 , ha = 'left' , save_path = 'plot_histogram' , dpi = 200 ) : his0 , his1 = hist [ 0 ] , hist [ 1 ] if len ( his1 ) == len ( his0 ) + 1 : his0 , his1 = his1 [ : - 1 ] , his0 elif len ( his0 ) == len ( his1 ) + 1 : his0 = his0 [ : - 1 ] resolution = resolution or 3 if labels in ( None , 0 , 'date' , 'datetime' ) : try : labels = prettify_datetimes ( [ '-' . join ( str ( val ) for val in datetime_from_ordinal_float ( val ) . timetuple ( ) [ : resolution ] ) for val in his0 ] , format = datetime_format , max_nonempty_strings = num_labels ) except ValueError : labels = [ ( '{0:.' + str ( resolution ) + 'g}' ) . format ( val ) for val in his0 ] elif labels == False : labels = [ '' ] * len ( his0 ) if len ( labels ) != len ( his0 ) or not all ( isinstance ( val , basestring ) for val in labels ) : labels = list ( str ( s ) for s in labels ) labels += [ '' ] * ( len ( his0 ) - len ( labels ) ) labels = thin_string_list ( labels , 50 ) fig = plt . gcf ( ) if figsize and len ( figsize ) == 2 : fig . set_size_inches ( figsize [ 0 ] , figsize [ 1 ] , forward = True ) if bg_color or bg_alpha : fig . set_facecolor ( bg_color ) fig . set_alpha ( bg_alpha ) if not fig . axes : ax = fig . add_subplot ( 111 ) else : ax = fig . gca ( ) color = color or 'b' alpha = alpha or .8 xlabel = xlabel or '' xwidth = ( width or 0.9 ) * pd . np . min ( pd . np . diff ( his0 ) ) if not isinstance ( ylabel , basestring ) : ylabel = 'Count (Number of Occurrences)' xwidth = ( width or 0.9 ) * pd . np . min ( pd . np . diff ( his0 ) ) ax . bar ( his0 , his1 , width = xwidth , color = color , alpha = alpha ) print ( his0 ) plt . xticks ( [ dy + padding * xwidth for dy in his0 ] , labels , rotation = rotation , ha = ha ) if xlabel : plt . xlabel ( xlabel ) if ylabel : plt . ylabel ( ylabel ) if title : plt . title ( title ) if formatter and callable ( formatter ) : ax . yaxis . set_major_formatter ( plt . matplotlib . ticker . FuncFormatter ( formatter ) ) ax . grid ( grid , color = ( line_color or 'gray' ) ) fig . patch . set_facecolor ( bg_color ) fig . patch . set_alpha ( bg_alpha ) ax . patch . set_alpha ( bg_alpha ) ax . patch . set_facecolor ( bg_color ) if line_color : for spine in ax . spines . values ( ) : spine . set_color ( line_color ) ax . tick_params ( axis = 'x' , colors = line_color ) ax . tick_params ( axis = 'y' , colors = line_color ) ax . xaxis . label . set_color ( line_color ) ax . yaxis . label . set_color ( line_color ) ax . title . set_color ( line_color ) if tight_layout : plt . tight_layout ( ) try : plt . show ( block = False ) except TypeError : plt . show ( ) if save_path : if os . path . isfile ( save_path + '.png' ) : i = 2 save_path2 = save_path + '--{0}' . format ( i ) while os . path . isfile ( save_path2 + '.png' ) : i += 1 save_path2 = save_path + '--{0}' . format ( i ) save_path = save_path2 plt . savefig ( save_path , facecolor = fig . get_facecolor ( ) , edgecolor = 'none' , dpi = dpi ) his0 , his1 = pd . np . array ( his0 ) , pd . np . array ( his1 ) his0 = np . append ( his0 , 2 * his0 [ - 1 ] - his0 [ - 2 ] ) return ( his1 , his0 ) , fig
Plot a bar chart from np.histogram data

    >>> plot_histogram(np.histogram([1]*5+[3]*2+list(range(20))+[19.1]), alpha=1)  # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    ((array([7, 4, 2, 2, 2, 2, 2, 2, 2, 3]),
    array([  0.  ,   1.91,   3.82,   5.73,   7.64,   9.55,  11.46,  13.37,
        15.28,  17.19,  19.1 ])),
    <matplotlib.figure.Figure at ...)