<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:

import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram

def make_figfunction(figuretype):
    """
    A function to pack figure factory, make it easier to use
 
    Parameters:
    -----------
    figuretype: 'corr', correlation plots
                'mat', matrix plot
                'bar', plot bar
                'hist', histogram
                'hierarchy', hierarchy maps
                'line', line maps
                'scatter', scatter maps

    Return:
    -------
    figinstance: figure function

    Example:
    --------
    >>> plotcorr = make_figfunction('corr')
    """
    figFact = _FigureFactory()
    return figFact.createfactory(figuretype)

class _FigureFactory(object):
    """
    A Factory for Figures
    ----------------------------
    Example:
        >>> figFact = plotfig.FigureFactory()
        >>> plotmat = figFact.createfactory('mat')
    """
    def __init__(self):
	    pass

    def __str__(self):
        return 'A factory for plotting figures'

    def createfactory(self, figuretype):
        """
        Create factory by this function
        ------------------------------------
        Parameters:
            figuretype: 'corr', correlation plots
                        'mat', matrix plot
                        'bar', plot bar
                        'hist', histogram
                        'hierarchy', hierarchy maps
                        'line', line maps
                        'scatter', scatter maps
        """
        figure = self._Figures()
        if figuretype == 'corr':
            figuror = figure._corr_plotting
        elif figuretype == 'mat':
            figuror = figure._mat_plotting
        elif figuretype == 'bar':
            figuror = figure._bar_plotting
        elif figuretype == 'hist':
            figuror = figure._hist_plotting
        elif figuretype == 'hierarchy':
            figuror = figure._hierarchy_plotting
        elif figuretype == 'line':
            figuror = figure._simpleline_plotting
        elif figuretype == 'scatter':
            figuror = figure._scatter_plotting
        else:
              raise Exception('wrong parameter input!')
        return figuror

    class _Figures(object):
        def __init__(self):
            pass    
    
        def _corr_plotting(self, meas1, meas2, labels=['',''], method = 'pearson'):
            """
            Make scatter plot and give a fit on it.
            ------------------------------------------
            Paramters:
                meas1: feature measurement
                meas2: feature measurement
                labels: A list contains two labels.
                        labels[0] means label of meas1, labels[1] means label of meas2.
                method: 'pearson' or 'spearman' correlation
            Example:
                >>> plotcorr(data1, data2, labels = label, method = 'pearson')
            """
            plt.rc('xtick', labelsize = 14)
            plt.rc('ytick', labelsize = 14)
            if (meas1.dtype != 'O') | (meas2.dtype != 'O'):
                samp_sel = ~np.isnan(meas1*meas2)
                x = meas1[samp_sel]
                y = meas2[samp_sel]
            else:
                x = meas1
                y = meas2
            if method == 'pearson':
                corr, pval = stats.pearsonr(x, y)
            elif method == 'spearman':
                corr, pval = stats.spearmanr(x, y)
            else:
                raise Exception('Wrong method you used')
            fig, ax = plt.subplots()
            plt.scatter(x, y)
            plt.plot(x, np.poly1d(np.polyfit(x,y,1))(x))
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            ax.set_aspect((x1-x0)/(y1-y0))
            ax.text(x0+0.1*(x1-x0), y0+0.9*(y1-y0), 'r = %.3f, p = %.3f' % (corr, pval))
            plt.xlabel(labels[0])
            plt.ylabel(labels[1])
            plt.title(method.capitalize()+' Correlation')

            plt.show()

        def _mat_plotting(self, data, xlabel='', ylabel=''):
            """
            Plot matrix using heatmap
            ------------------------------------
            Paramters:
                data: raw data
                xlabel: xlabels
                ylabel: ylabels
            Example:
                >>> plotmat(data, xlabel = xlabellist, ylabel = ylabellist)
            """
            plt.rc('xtick', labelsize=14)
            plt.rc('ytick', labelsize=14)
            sns.heatmap(data, xticklabels = xlabel, yticklabels = ylabel)
            plt.show()

        def _bar_plotting(self, data, title = '', xlabels = '', ylabels = '', legendname = None, legendpos = 'upper left', err=None):
            """
            Do barplot
            --------------------------
            Parameters:
                data: raw data
                title: title of figures
                xlabels, ylabels: xlabel and ylabel of figures
                legendname: identified legend name
                err: error of data estimation. Used for errorbar
            Example:
                >>> plotbar(data, title = titletxt, xlabels = xlabel, ylabels = ylabel, legendname = legendnametxt, err = errdata)
            """
            plt.rc('xtick', labelsize=14)
            plt.rc('ytick', labelsize=14)
            color = ['#BDBDBD', '#575757', '#404040', '#080808', '#919191']
            if isinstance(data, list):
                data = np.array(data)
            if data.ndim == 1:
                data = np.expand_dims(data, axis = 1)
            ind = np.arange(data.shape[0])
            width = 0.70/data.shape[1]
            fig, ax = plt.subplots() 
            rects = []
            if err is None:
                for i in range(data.shape[1]):
                    if legendname is None:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5])
                    else:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5], label = legendname[i])
                    ax.legend(loc=legendpos) 
            else:
                for i in range(data.shape[1]):
                    rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5], yerr = err[:,i], error_kw=dict(ecolor = '#757575', capthick=1), label = legendname[i])
                    ax.legend(loc=legendpos)
            
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            ax.set_aspect((x1-x0)/(y1-y0))
            ax.set_ylabel(ylabels)
            ax.set_xticks(ind + width)
            if np.min(data)<0:
                ax.set_ylim([1.33*np.min(data), 1.33*np.max(data)])
            else:
                ax.set_ylim([0, 1.33*np.max(data)])
            plt.xticks(rotation = 45)<commit_msg>do modification on bar chart<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:

import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram

def make_figfunction(figuretype):
    """
    A function to pack figure factory, make it easier to use
 
    Parameters:
    -----------
    figuretype: 'corr', correlation plots
                'mat', matrix plot
                'bar', plot bar
                'hist', histogram
                'hierarchy', hierarchy maps
                'line', line maps
                'scatter', scatter maps

    Return:
    -------
    figinstance: figure function

    Example:
    --------
    >>> plotcorr = make_figfunction('corr')
    """
    figFact = _FigureFactory()
    return figFact.createfactory(figuretype)

class _FigureFactory(object):
    """
    A Factory for Figures
    ----------------------------
    Example:
        >>> figFact = plotfig.FigureFactory()
        >>> plotmat = figFact.createfactory('mat')
    """
    def __init__(self):
	    pass

    def __str__(self):
        return 'A factory for plotting figures'

    def createfactory(self, figuretype):
        """
        Create factory by this function
        ------------------------------------
        Parameters:
            figuretype: 'corr', correlation plots
                        'mat', matrix plot
                        'bar', plot bar
                        'hist', histogram
                        'hierarchy', hierarchy maps
                        'line', line maps
                        'scatter', scatter maps
        """
        figure = self._Figures()
        if figuretype == 'corr':
            figuror = figure._corr_plotting
        elif figuretype == 'mat':
            figuror = figure._mat_plotting
        elif figuretype == 'bar':
            figuror = figure._bar_plotting
        elif figuretype == 'hist':
            figuror = figure._hist_plotting
        elif figuretype == 'hierarchy':
            figuror = figure._hierarchy_plotting
        elif figuretype == 'line':
            figuror = figure._simpleline_plotting
        elif figuretype == 'scatter':
            figuror = figure._scatter_plotting
        else:
              raise Exception('wrong parameter input!')
        return figuror

    class _Figures(object):
        def __init__(self):
            pass    
    
        def _corr_plotting(self, meas1, meas2, labels=['',''], method = 'pearson'):
            """
            Make scatter plot and give a fit on it.
            ------------------------------------------
            Paramters:
                meas1: feature measurement
                meas2: feature measurement
                labels: A list contains two labels.
                        labels[0] means label of meas1, labels[1] means label of meas2.
                method: 'pearson' or 'spearman' correlation
            Example:
                >>> plotcorr(data1, data2, labels = label, method = 'pearson')
            """
            plt.rc('xtick', labelsize = 14)
            plt.rc('ytick', labelsize = 14)
            if (meas1.dtype != 'O') | (meas2.dtype != 'O'):
                samp_sel = ~np.isnan(meas1*meas2)
                x = meas1[samp_sel]
                y = meas2[samp_sel]
            else:
                x = meas1
                y = meas2
            if method == 'pearson':
                corr, pval = stats.pearsonr(x, y)
            elif method == 'spearman':
                corr, pval = stats.spearmanr(x, y)
            else:
                raise Exception('Wrong method you used')
            fig, ax = plt.subplots()
            plt.scatter(x, y)
            plt.plot(x, np.poly1d(np.polyfit(x,y,1))(x))
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            ax.set_aspect((x1-x0)/(y1-y0))
            ax.text(x0+0.1*(x1-x0), y0+0.9*(y1-y0), 'r = %.3f, p = %.3f' % (corr, pval))
            plt.xlabel(labels[0])
            plt.ylabel(labels[1])
            plt.title(method.capitalize()+' Correlation')

            plt.show()

        def _mat_plotting(self, data, xlabel='', ylabel=''):
            """
            Plot matrix using heatmap
            ------------------------------------
            Paramters:
                data: raw data
                xlabel: xlabels
                ylabel: ylabels
            Example:
                >>> plotmat(data, xlabel = xlabellist, ylabel = ylabellist)
            """
            plt.rc('xtick', labelsize=14)
            plt.rc('ytick', labelsize=14)
            sns.heatmap(data, xticklabels = xlabel, yticklabels = ylabel)
            plt.show()

        def _bar_plotting(self, data, title = '', xlabels = '', ylabels = '', legendname = None, legendpos = 'upper left', err=None):
            """
            Do barplot
            --------------------------
            Parameters:
                data: raw data
                title: title of figures
                xlabels, ylabels: xlabel and ylabel of figures
                legendname: identified legend name
                err: error of data estimation. Used for errorbar
            Example:
                >>> plotbar(data, title = titletxt, xlabels = xlabel, ylabels = ylabel, legendname = legendnametxt, err = errdata)
            """
            plt.rc('xtick', labelsize=14)
            plt.rc('ytick', labelsize=14)
            color = ['#BDBDBD', '#575757', '#404040', '#080808', '#919191']
            if isinstance(data, list):
                data = np.array(data)
            if data.ndim == 1:
                data = np.expand_dims(data, axis = 1)
            ind = np.arange(data.shape[0])
            width = 0.70/data.shape[1]
            fig, ax = plt.subplots() 
            rects = []
            if err is None:
                for i in range(data.shape[1]):
                    if legendname is None:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5])
                    else:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5], label = legendname[i])
                    ax.legend(loc=legendpos) 
            else:
                if isinstance(err, list):
                    err = np.array(err)
                if err.ndim == 1:
                    err = np.expand_dims(err, axis = 1)
                for i in range(data.shape[1]):
                    try:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5], yerr = err[:,i], error_kw=dict(ecolor = '#757575', capthick=1), label = legendname[i])
                    except TypeError:
                        rects = ax.bar(ind + i*width, data[:,i], width, color = color[i%5], yerr = err[:,i], error_kw=dict(ecolor = '#757575', capthick=1), label = legendname)                     
                    ax.legend(loc=legendpos)
            
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            ax.set_aspect((x1-x0)/(y1-y0))
            ax.set_ylabel(ylabels)
            ax.set_xticks(ind + width)
            if np.min(data)<0:
                ax.set_ylim([1.33*np.min(data), 1.33*np.max(data)])
            else:
                ax.set_ylim([0, 1.33*np.max(data)])
            plt.xticks(rotation = 45)
{'fraction_non_alphanumeric': 0.13928794503435352, 'fraction_numerical': 0.017627871469220627, 'mean_word_length': 1.391701244813278, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '570764', 'n_tokens_mistral': 4300, 'n_tokens_neox': 4008, 'n_words': 1008}