jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_despine_side_specific_offset(self):

        f, ax = plt.subplots()
        utils.despine(ax=ax, offset=dict(left=self.offset))

        for side in self.sides:
            is_visible = ax.spines[side].get_visible()
            new_position = ax.spines[side].get_position()
            if is_visible and side == "left":
                assert new_position == self.offset_position
            else:
                assert new_position == self.original_position
//  [python]
def test_despine_with_offset_specific_axes(self):
        f, (ax1, ax2) = plt.subplots(2, 1)

        s.despine(offset=self.offset, ax=ax2)

        for side in self.sides:
            pos1 = ax1.spines[side].get_position()
            pos2 = ax2.spines[side].get_position()
            assert pos1 == self.original_position
            if ax2.spines[side].get_visible():
                assert pos2 == self.offset_position
            else:
                assert pos2 == self.original_position
//  [python]
def test_despine_with_offset_specific_axes(self):
        f, (ax1, ax2) = plt.subplots(2, 1)

        utils.despine(offset=self.offset, ax=ax2)

        for side in self.sides:
            pos1 = ax1.spines[side].get_position()
            pos2 = ax2.spines[side].get_position()
            assert pos1 == self.original_position
            if ax2.spines[side].get_visible():
                assert pos2 == self.offset_position
            else:
                assert pos2 == self.original_position
//  [python]
def test_despine_trim_spines(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_xlim(.75, 3.25)

        s.despine(trim=True)
        for side in self.inner_sides:
            bounds = ax.spines[side].get_bounds()
            assert bounds == (1, 3)
//  [python]
def test_despine_trim_spines(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_xlim(.75, 3.25)

        utils.despine(trim=True)
        for side in self.inner_sides:
            bounds = ax.spines[side].get_bounds()
            assert bounds == (1, 3)
//  [python]
def test_despine_trim_inverted(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_ylim(.85, 3.15)
        ax.invert_yaxis()

        s.despine(trim=True)
        for side in self.inner_sides:
            bounds = ax.spines[side].get_bounds()
            assert bounds == (1, 3)
//  [python]
def test_despine_trim_inverted(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_ylim(.85, 3.15)
        ax.invert_yaxis()

        utils.despine(trim=True)
        for side in self.inner_sides:
            bounds = ax.spines[side].get_bounds()
            assert bounds == (1, 3)
//  [python]
def test_despine_trim_noticks(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_yticks([])
        s.despine(trim=True)
        assert ax.get_yticks().size == 0
//  [python]
def test_despine_trim_noticks(self):

        f, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set_yticks([])
        utils.despine(trim=True)
        assert ax.get_yticks().size == 0
//  [python]
def test_despine_trim_categorical(self):

        f, ax = plt.subplots()
        ax.plot(["a", "b", "c"], [1, 2, 3])

        s.despine(trim=True)

        bounds = ax.spines["left"].get_bounds()
        assert bounds == (1, 3)

        bounds = ax.spines["bottom"].get_bounds()
        assert bounds == (0, 2)
//  [python]
def test_despine_trim_categorical(self):

        f, ax = plt.subplots()
        ax.plot(["a", "b", "c"], [1, 2, 3])

        utils.despine(trim=True)

        bounds = ax.spines["left"].get_bounds()
        assert bounds == (1, 3)

        bounds = ax.spines["bottom"].get_bounds()
        assert bounds == (0, 2)
//  [python]
def test_despine_moved_ticks(self):

        f, ax = plt.subplots()
        for t in ax.yaxis.majorTicks:
            t.tick1line.set_visible(True)
        s.despine(ax=ax, left=True, right=False)
        for t in ax.yaxis.majorTicks:
            assert t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.yaxis.majorTicks:
            t.tick1line.set_visible(False)
        s.despine(ax=ax, left=True, right=False)
        for t in ax.yaxis.majorTicks:
            assert not t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.xaxis.majorTicks:
            t.tick1line.set_visible(True)
        s.despine(ax=ax, bottom=True, top=False)
        for t in ax.xaxis.majorTicks:
            assert t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.xaxis.majorTicks:
            t.tick1line.set_visible(False)
        s.despine(ax=ax, bottom=True, top=False)
        for t in ax.xaxis.majorTicks:
            assert not t.tick2line.get_visible()
        plt.close(f)
//  [python]
def test_despine_moved_ticks(self):

        f, ax = plt.subplots()
        for t in ax.yaxis.majorTicks:
            t.tick1line.set_visible(True)
        utils.despine(ax=ax, left=True, right=False)
        for t in ax.yaxis.majorTicks:
            assert t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.yaxis.majorTicks:
            t.tick1line.set_visible(False)
        utils.despine(ax=ax, left=True, right=False)
        for t in ax.yaxis.majorTicks:
            assert not t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.xaxis.majorTicks:
            t.tick1line.set_visible(True)
        utils.despine(ax=ax, bottom=True, top=False)
        for t in ax.xaxis.majorTicks:
            assert t.tick2line.get_visible()
        plt.close(f)

        f, ax = plt.subplots()
        for t in ax.xaxis.majorTicks:
            t.tick1line.set_visible(False)
        utils.despine(ax=ax, bottom=True, top=False)
        for t in ax.xaxis.majorTicks:
            assert not t.tick2line.get_visible()
        plt.close(f)
//  [python]
titanic_all['Title'] = titanic_all['Name'].map(extract_title)

tmp_df = titanic_all[0:titanic_train.shape[0]]
sns.FacetGrid(tmp_df, row="Survived",size=8).map(sns.kdeplot, "FamilySize").add_legend()
sns.factorplot(x="Title", hue="Survived", data=tmp_df, kind="count", size=6)
//  [python]
titanic_all['Title'] = titanic_all['Name'].map(extract_title)

tmp_df = titanic_all[0:titanic_train.shape[0]]
sns.FacetGrid(tmp_df, row="Survived",size=8).map(sns.kdeplot, "FamilySize").add_legend()
sns.catplot(x="Title", hue="Survived", data=tmp_df, kind="count", size=6)
//  [python]
def _plotWeekdayStats(stats, columns, groupBy=True):
    dataToPlot = stats.copy()
    # Group by weekday and rename date column
    if groupBy:
        dataToPlot = dataToPlot.groupby(stats['date'].dt.weekday).mean()
        dataToPlot = dataToPlot.reset_index().rename(columns={'date':'weekday'})

    # change stats from columns to row attribute
    dataToPlot = pd.melt(dataToPlot, id_vars=['weekday'], value_vars=columns,
                         var_name='stats', value_name='val')
    # Rename stats and weekdays
    dataToPlot['stats'].replace(NAMES, inplace=True)
    dataToPlot['weekday'].replace(dayOfWeek, inplace=True)
    # Plot
    g = sns.factorplot(data=dataToPlot, x="weekday", y="val", col="stats",
                       order=dayOfWeekOrder, kind="point", sharey=False, col_wrap=3)
    g.set_xticklabels(rotation=45)
    g.set(xlabel='')
    return g
//  [python]
def _plotWeekdayStats(stats, columns, groupBy=True):
    dataToPlot = stats.copy()
    # Group by weekday and rename date column
    if groupBy:
        dataToPlot = dataToPlot.groupby(stats['date'].dt.weekday).mean()
        dataToPlot = dataToPlot.reset_index().rename(columns={'date':'weekday'})

    # change stats from columns to row attribute
    dataToPlot = pd.melt(dataToPlot, id_vars=['weekday'], value_vars=columns,
                         var_name='stats', value_name='val')
    # Rename stats and weekdays
    dataToPlot['stats'].replace(NAMES, inplace=True)
    dataToPlot['weekday'].replace(dayOfWeek, inplace=True)
    # Plot
    g = sns.catplot(data=dataToPlot, x="weekday", y="val", col="stats",
                       order=dayOfWeekOrder, kind="point", sharey=False, col_wrap=3)
    g.set_xticklabels(rotation=45)
    g.set(xlabel='')
    return g
//  [python]
def joint_plot(ratio=1, height=3.):
    """Taken from Seaborn JointGrid"""
    fig = plt.figure(figsize=(height, height))
    gsp = plt.GridSpec(ratio+1, ratio+1)

    ax_joint = fig.add_subplot(gsp[1:, :-1])
    ax_marg_x = fig.add_subplot(gsp[0, :-1], sharex=ax_joint)
    ax_marg_y = fig.add_subplot(gsp[1:, -1], sharey=ax_joint)

    # Turn off tick visibility for the measure axis on the marginal plots
    plt.setp(ax_marg_x.get_xticklabels(), visible=False)
    plt.setp(ax_marg_y.get_yticklabels(), visible=False)

    # Turn off the ticks on the density axis for the marginal plots
    plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)
    plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)
    plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)
    plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)
    plt.setp(ax_marg_x.get_yticklabels(), visible=False)
    plt.setp(ax_marg_y.get_xticklabels(), visible=False)
    ax_marg_x.yaxis.grid(False)
    ax_marg_y.xaxis.grid(False)

    # Make the grid look nice
    # utils.despine(fig)
    s.despine(ax=ax_marg_x, left=True)
    s.despine(ax=ax_marg_y, bottom=True)
    fig.tight_layout(h_pad=0, w_pad=0)

    ax_marg_y.tick_params(axis='y', which='major', direction='out')
    ax_marg_x.tick_params(axis='x', which='major', direction='out')
    ax_marg_y.tick_params(axis='y', which='minor', direction='out')
    ax_marg_x.tick_params(axis='x', which='minor', direction='out')
    ax_marg_y.margins(x=0.1, y=0.)

    fig.subplots_adjust(hspace=0, wspace=0)

    return fig, ax_joint, ax_marg_x, ax_marg_y
//  [python]
def joint_plot(ratio=1, height=3.):
    """Taken from Seaborn JointGrid"""
    fig = plt.figure(figsize=(height, height))
    gsp = plt.GridSpec(ratio+1, ratio+1)

    ax_joint = fig.add_subplot(gsp[1:, :-1])
    ax_marg_x = fig.add_subplot(gsp[0, :-1], sharex=ax_joint)
    ax_marg_y = fig.add_subplot(gsp[1:, -1], sharey=ax_joint)

    # Turn off tick visibility for the measure axis on the marginal plots
    plt.setp(ax_marg_x.get_xticklabels(), visible=False)
    plt.setp(ax_marg_y.get_yticklabels(), visible=False)

    # Turn off the ticks on the density axis for the marginal plots
    plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)
    plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)
    plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)
    plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)
    plt.setp(ax_marg_x.get_yticklabels(), visible=False)
    plt.setp(ax_marg_y.get_xticklabels(), visible=False)
    ax_marg_x.yaxis.grid(False)
    ax_marg_y.xaxis.grid(False)

    # Make the grid look nice
    # utils.despine(fig)
    utils.despine(ax=ax_marg_x, left=True)
    utils.despine(ax=ax_marg_y, bottom=True)
    fig.tight_layout(h_pad=0, w_pad=0)

    ax_marg_y.tick_params(axis='y', which='major', direction='out')
    ax_marg_x.tick_params(axis='x', which='major', direction='out')
    ax_marg_y.tick_params(axis='y', which='minor', direction='out')
    ax_marg_x.tick_params(axis='x', which='minor', direction='out')
    ax_marg_y.margins(x=0.1, y=0.)

    fig.subplots_adjust(hspace=0, wspace=0)

    return fig, ax_joint, ax_marg_x, ax_marg_y
//  [python]
def plotYearAndMonthStatsSleep(stats, columns=None):
    """
    Plot aggregated (mean) stats by year and month.
    :param stats: data to plot
    """
    if not columns:
        columns = ['sleep_efficiency', 'sleep_hours']

    dataToPlot = _prepareYearAndMonthStats(stats, columns)
    # Plot
    g = sns.factorplot(data=dataToPlot, x="date", y="val", row="stats", kind="point", sharey=False)
    g.set_xticklabels(rotation=45)
    for ax in g.axes.flat:
        ax.grid(b=True)
    return g
//  [python]
def plotYearAndMonthStatsSleep(stats, columns=None):
    """
    Plot aggregated (mean) stats by year and month.
    :param stats: data to plot
    """
    if not columns:
        columns = ['sleep_efficiency', 'sleep_hours']

    dataToPlot = _prepareYearAndMonthStats(stats, columns)
    # Plot
    g = sns.catplot(data=dataToPlot, x="date", y="val", row="stats", kind="point", sharey=False)
    g.set_xticklabels(rotation=45)
    for ax in g.axes.flat:
        ax.grid(b=True)
    return g
//  [python]
def _plotMonthlyStats(stats, columns, groupBy=True):
    dataToPlot = stats.copy()
    # Group by month and rename date column
    if groupBy:
        dataToPlot = dataToPlot.groupby(stats['date'].dt.month).mean()
        dataToPlot = dataToPlot.reset_index().rename(columns={'date': 'month'})

    # change stats from columns to row attribute
    dataToPlot = pd.melt(dataToPlot, id_vars=['month'], value_vars=columns,
                         var_name='stats', value_name='val')
    # Rename stats and weekdays
    dataToPlot['stats'].replace(NAMES, inplace=True)
    dataToPlot['month'].replace(months, inplace=True)
    order = [m for m in monthsOrder if m in dataToPlot['month'].unique()]
    # Plot
    g = sns.factorplot(data=dataToPlot, x="month", y="val", col="stats", order=order, kind="bar", sharey=False)
    g.set_xticklabels(rotation=45)
    g.set(xlabel='')
    return g
//  [python]
def _plotMonthlyStats(stats, columns, groupBy=True):
    dataToPlot = stats.copy()
    # Group by month and rename date column
    if groupBy:
        dataToPlot = dataToPlot.groupby(stats['date'].dt.month).mean()
        dataToPlot = dataToPlot.reset_index().rename(columns={'date': 'month'})

    # change stats from columns to row attribute
    dataToPlot = pd.melt(dataToPlot, id_vars=['month'], value_vars=columns,
                         var_name='stats', value_name='val')
    # Rename stats and weekdays
    dataToPlot['stats'].replace(NAMES, inplace=True)
    dataToPlot['month'].replace(months, inplace=True)
    order = [m for m in monthsOrder if m in dataToPlot['month'].unique()]
    # Plot
    g = sns.catplot(data=dataToPlot, x="month", y="val", col="stats", order=order, kind="bar", sharey=False)
    g.set_xticklabels(rotation=45)
    g.set(xlabel='')
    return g
//  [python]
def visualize_variable_relationships(train_data, viz_type, quantitative_vars, category_vars=None):
    """
    Generates plots showing the relationship between several variables.
    """
    # compare the continuous variable distributions using a violin plot
    sub_data = train_data[quantitative_vars]
    fig, ax = plt.subplots(1, 1, figsize=(16, 12))
    sb.violinplot(sub_data, ax=ax)
    fig.tight_layout()

    # if categorical variables were provided, visualize the quantitative distributions by category
    if category_vars is not None:
        fig, ax = plt.subplots(len(quantitative_vars), len(category_vars), figsize=(16, 12))
        for i, var in enumerate(quantitative_vars):
            for j, cat in enumerate(category_vars):
                sb.violinplot(train_data[var], train_data[cat], ax=ax[i, j])
        fig.tight_layout()

    # generate plots to directly compare the variables
    if category_vars is None:
        if len(quantitative_vars) == 2:
            sb.jointplot(quantitative_vars[0], quantitative_vars[1], train_data, kind=viz_type, size=16)
        else:
            sb.pairplot(train_data, vars=quantitative_vars, kind='scatter',
                        diag_kind='kde', size=16 / len(quantitative_vars))
    else:
        if len(quantitative_vars) == 1:
            if len(category_vars) == 1:
                sb.factorplot(category_vars[0], quantitative_vars[0], None,
                              train_data, kind='auto', size=16)
            else:
                sb.factorplot(category_vars[0], quantitative_vars[0], category_vars[1],
                              train_data, kind='auto', size=16)
        if len(quantitative_vars) == 2:
            if len(category_vars) == 1:
                sb.lmplot(quantitative_vars[0], quantitative_vars[1], train_data,
                          col=None, row=category_vars[0], size=16)
            else:
                sb.lmplot(quantitative_vars[0], quantitative_vars[1], train_data,
                          col=category_vars[0], row=category_vars[1], size=16)
        else:
            sb.pairplot(train_data, hue=category_vars[0], vars=quantitative_vars, kind='scatter',
                        diag_kind='kde', size=16 / len(quantitative_vars))
//  [python]
def visualize_variable_relationships(train_data, viz_type, quantitative_vars, category_vars=None):
    """
    Generates plots showing the relationship between several variables.
    """
    # compare the continuous variable distributions using a violin plot
    sub_data = train_data[quantitative_vars]
    fig, ax = plt.subplots(1, 1, figsize=(16, 12))
    sb.violinplot(sub_data, ax=ax)
    fig.tight_layout()

    # if categorical variables were provided, visualize the quantitative distributions by category
    if category_vars is not None:
        fig, ax = plt.subplots(len(quantitative_vars), len(category_vars), figsize=(16, 12))
        for i, var in enumerate(quantitative_vars):
            for j, cat in enumerate(category_vars):
                sb.violinplot(train_data[var], train_data[cat], ax=ax[i, j])
        fig.tight_layout()

    # generate plots to directly compare the variables
    if category_vars is None:
        if len(quantitative_vars) == 2:
            sb.jointplot(quantitative_vars[0], quantitative_vars[1], train_data, kind=viz_type, size=16)
        else:
            sb.pairplot(train_data, vars=quantitative_vars, kind='scatter',
                        diag_kind='kde', size=16 / len(quantitative_vars))
    else:
        if len(quantitative_vars) == 1:
            if len(category_vars) == 1:
                sb.catplot(category_vars[0], quantitative_vars[0], None,
                              train_data, kind='auto', size=16)
            else:
                sb.catplot(category_vars[0], quantitative_vars[0], category_vars[1],
                              train_data, kind='auto', size=16)
        if len(quantitative_vars) == 2:
            if len(category_vars) == 1:
                sb.lmplot(quantitative_vars[0], quantitative_vars[1], train_data,
                          col=None, row=category_vars[0], size=16)
            else:
                sb.lmplot(quantitative_vars[0], quantitative_vars[1], train_data,
                          col=category_vars[0], row=category_vars[1], size=16)
        else:
            sb.pairplot(train_data, hue=category_vars[0], vars=quantitative_vars, kind='scatter',
                        diag_kind='kde', size=16 / len(quantitative_vars))
//  [python]
def plot_data():
    """Plot prices and items over time"""
    
    # Load data
    prices,items,_ = load_data()
    
    # Price trends for different time periods
    prices['year'] = prices.ts.dt.year
    prices['month'] = prices.ts.dt.month
    prices['dayofweek'] = prices.ts.dt.dayofweek
    prices['hour'] = prices.ts.dt.hour
    
    prices.groupby('year',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                              "median_price":np.median}).plot(kind='line', x="year")
    prices.groupby('month',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                               "median_price":np.median}).plot(kind='line', x="month")
    prices.groupby('dayofweek',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                                   "median_price":np.median}).plot(kind='line', x="dayofweek")
    prices.groupby('hour',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                              "median_price":np.median}).plot(kind='line', x="hour")
    sns.FacetGrid(prices.groupby(["dayofweek","hour"])["price"] \
        .aggregate({"mean_price":np.mean, "median_price":np.median}).reset_index(), row="dayofweek") \
        .map(plt.plot, "hour", "median_price") \
        .set(xlim=(0, 23))
        
    # Grades
    item_order = items.loc[items.consumption.argsort()[::-1], 'item']
    sns.factorplot(x="item", y="consumption", data=items, kind="bar", order=item_order)
//  [python]
def plot_data():
    """Plot prices and items over time"""
    
    # Load data
    prices,items,_ = load_data()
    
    # Price trends for different time periods
    prices['year'] = prices.ts.dt.year
    prices['month'] = prices.ts.dt.month
    prices['dayofweek'] = prices.ts.dt.dayofweek
    prices['hour'] = prices.ts.dt.hour
    
    prices.groupby('year',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                              "median_price":np.median}).plot(kind='line', x="year")
    prices.groupby('month',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                               "median_price":np.median}).plot(kind='line', x="month")
    prices.groupby('dayofweek',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                                   "median_price":np.median}).plot(kind='line', x="dayofweek")
    prices.groupby('hour',as_index=False)['price'].aggregate({"mean_price":np.mean, 
                                                              "median_price":np.median}).plot(kind='line', x="hour")
    sns.FacetGrid(prices.groupby(["dayofweek","hour"])["price"] \
        .aggregate({"mean_price":np.mean, "median_price":np.median}).reset_index(), row="dayofweek") \
        .map(plt.plot, "hour", "median_price") \
        .set(xlim=(0, 23))
        
    # Grades
    item_order = items.loc[items.consumption.argsort()[::-1], 'item']
    sns.catplot(x="item", y="consumption", data=items, kind="bar", order=item_order)
//  [python]
def plotGenes(self):

        res = self.getFiltered()
        names = res.name[:50]
        counts = self.table.model.df
        m = melt_samples(counts, self.labels, names, samplecol=self.samplecol)
        import seaborn as sns
        kind = self.tkvars['plot_kind'].get()
        xorder = self.conditions

        g = sns.factorplot(self.factorcol,'read count', data=m, col='name', kind=kind,
                                col_wrap=5, size=3, aspect=.9,
                                legend_out=True,sharey=False, order=xorder)
        plt.show()
        return
//  [python]
def plotGenes(self):

        res = self.getFiltered()
        names = res.name[:50]
        counts = self.table.model.df
        m = melt_samples(counts, self.labels, names, samplecol=self.samplecol)
        import seaborn as sns
        kind = self.tkvars['plot_kind'].get()
        xorder = self.conditions

        g = sns.catplot(x=self.factorcol, y='read count', data=m, col='name', kind=kind,
                                col_wrap=5, height=3, aspect=.9,
                                legend_out=True,sharey=False, order=xorder)
        plt.show()
        return
//  [python]
def plot_res_between_groups_seperated(self, flag=1, figsize=(10, 5)):
        if flag in self.data_bt_grp_sep.keys():
            data_graph = self.data_bt_grp_sep[flag]
        else:
            df = self.input_data2.copy()
            raw_df_grp = df.groupby('user_grp', sort=False)
            data_graph = raw_df_grp.apply(lambda x: self.__calc_all_res_between_group(x, flag))
            self.data_bt_grp_sep[flag] = data_graph.copy()

        data_graph_melted = data_graph.stack().reset_index().rename(columns={0: 'value'})
        g = sn.factorplot(data=data_graph_melted, x='user_grp', y='value', hue='cycle',
                          kind='bar', alpha=0.3, dodge=True, sharex=True, sharey=False,
                          margin_titles=True, legend=False, palette=self.palette0)

        fig_title = self.fig_title_by_flags[flag]
        g.fig.suptitle(fig_title + '\nPerformance by User-defined Group', x=0.8, y=0.99, fontsize=12)
        g.fig.set_size_inches(figsize[0], figsize[1])
        g.fig.autofmt_xdate()
        g.fig.tight_layout(rect=(0.01, 0.01, 0.95, 0.92))
        g.add_legend()
        return g
//  [python]
def plot_res_between_groups_seperated(self, flag=1, figsize=(10, 5)):
        if flag in self.data_bt_grp_sep.keys():
            data_graph = self.data_bt_grp_sep[flag]
        else:
            df = self.input_data2.copy()
            raw_df_grp = df.groupby('user_grp', sort=False)
            data_graph = raw_df_grp.apply(lambda x: self.__calc_all_res_between_group(x, flag))
            self.data_bt_grp_sep[flag] = data_graph.copy()

        data_graph_melted = data_graph.stack().reset_index().rename(columns={0: 'value'})
        g = sn.catplot(data=data_graph_melted, x='user_grp', y='value', hue='cycle',
                          kind='bar', alpha=0.3, dodge=True, sharex=True, sharey=False,
                          margin_titles=True, legend=False, palette=self.palette0)

        fig_title = self.fig_title_by_flags[flag]
        g.fig.suptitle(fig_title + '\nPerformance by User-defined Group', x=0.8, y=0.99, fontsize=12)
        g.fig.set_size_inches(figsize[0], figsize[1])
        g.fig.autofmt_xdate()
        g.fig.tight_layout(rect=(0.01, 0.01, 0.95, 0.92))
        g.add_legend()
        return g
//  [python]
def plot_optimum():
    df = pd.read_pickle(os.path.join(DF_Dir, 'df_n_optimum.pkl'))
    plt.close('all')
    sns.factorplot(data=df, x='block', y='n_optimum', hue='learner', aspect=2.5)
    plt.savefig(os.path.join(Fig_Dir, 'n_optimum.pdf'))
    plt.show()
//  [python]
def plot_optimum():
    df = pd.read_pickle(os.path.join(DF_Dir, 'df_n_optimum.pkl'))
    plt.close('all')
    sns.catplot(data=df, x='block', y='n_optimum', hue='learner', aspect=2.5, kind='point')
    plt.savefig(os.path.join(Fig_Dir, 'n_optimum.pdf'))
    plt.show()
//  [python]
def plot_res_within_group_seperated(self, flag=1, res_type='avgrtn', figsize=None):
        data_key = '_'.join(map(str, [flag, res_type]))
        if data_key in self.data_wt_grp_sep.keys():
            data_graph = self.data_wt_grp_sep[data_key]
        else:
            df = self.input_data2.rename(columns={'segment' + str(flag): 'segment'})
            raw_df_grp = df.groupby('user_grp')
            data_graph = raw_df_grp.apply(lambda x: self._calc_all_res_within_group(x, flag))
            self.data_wt_grp_sep[data_key] = data_graph.copy()

        if figsize is None:
            figsize = (4 * len(self.ts_cycle_list), 4 * len(np.unique(list(self.regroup.values()))))

        if res_type in data_graph.columns:
            data_graph_melted = data_graph[res_type].stack().rename(res_type).reset_index()
            data_graph_melted['cycle'] = data_graph_melted['cycle'].astype(int)
            g = sn.factorplot(data=data_graph_melted, x='segment', y=res_type,
                              row='user_grp', col='cycle', hue='segment',
                              kind='bar', alpha=0.8, dodge=False,
                              legend=False, sharex=True, sharey=False,
                              margin_titles=True, palette=self.palette1)
        else:
            data_graph_melted = data_graph.stack().reset_index().melt(id_vars=['cycle', 'segment', 'user_grp'])
            data_graph_melted['cycle'] = data_graph_melted['cycle'].astype(int)
            g = sn.FacetGrid(data=data_graph_melted, row='type', col='cycle', hue='user_grp',
                             size=2, aspect=3, sharex=False, sharey=False,
                             legend_out=True, margin_titles=True, palette=self.palette1)
            g.map(plt.scatter, 'segment', 'value', alpha=0.8)

        ttl_2nd = '\nby Segmentation within User-defined Groups'
        g.fig.suptitle(self.fig_title_by_flags[flag] + ttl_2nd, y=0.99, fontsize=12)
        g.fig.set_size_inches(figsize[0], figsize[1])
        g.fig.autofmt_xdate()
        g.fig.tight_layout(rect=(0.01, 0.01, 0.95, 0.97))
        g.add_legend()
        return g
//  [python]
def plot_res_within_group_seperated(self, flag=1, res_type='avgrtn', figsize=None):
        data_key = '_'.join(map(str, [flag, res_type]))
        if data_key in self.data_wt_grp_sep.keys():
            data_graph = self.data_wt_grp_sep[data_key]
        else:
            df = self.input_data2.rename(columns={'segment' + str(flag): 'segment'})
            raw_df_grp = df.groupby('user_grp')
            data_graph = raw_df_grp.apply(lambda x: self._calc_all_res_within_group(x, flag))
            self.data_wt_grp_sep[data_key] = data_graph.copy()

        if figsize is None:
            figsize = (4 * len(self.ts_cycle_list), 4 * len(np.unique(list(self.regroup.values()))))

        if res_type in data_graph.columns:
            data_graph_melted = data_graph[res_type].stack().rename(res_type).reset_index()
            data_graph_melted['cycle'] = data_graph_melted['cycle'].astype(int)
            g = sn.catplot(data=data_graph_melted, x='segment', y=res_type,
                              row='user_grp', col='cycle', hue='segment',
                              kind='bar', alpha=0.8, dodge=False,
                              legend=False, sharex=True, sharey=False,
                              margin_titles=True, palette=self.palette1)
        else:
            data_graph_melted = data_graph.stack().reset_index().melt(id_vars=['cycle', 'segment', 'user_grp'])
            data_graph_melted['cycle'] = data_graph_melted['cycle'].astype(int)
            g = sn.FacetGrid(data=data_graph_melted, row='type', col='cycle', hue='user_grp',
                             size=2, aspect=3, sharex=False, sharey=False,
                             legend_out=True, margin_titles=True, palette=self.palette1)
            g.map(plt.scatter, 'segment', 'value', alpha=0.8)

        ttl_2nd = '\nby Segmentation within User-defined Groups'
        g.fig.suptitle(self.fig_title_by_flags[flag] + ttl_2nd, y=0.99, fontsize=12)
        g.fig.set_size_inches(figsize[0], figsize[1])
        g.fig.autofmt_xdate()
        g.fig.tight_layout(rect=(0.01, 0.01, 0.95, 0.97))
        g.add_legend()
        return g
//  [python]
def plot_grid_scores(model, x, y=None, hue=None, row=None, col=None, col_wrap=None,
                     **kwargs):
    '''
    Wrapper around seaborn.factorplot.

    Parameters
    ----------
    model : Pipeline or Estimator
    x, hue, row, col : str
        parameters grid searched over
    y : str
        the target of interest, default `'mean_'`

    Returns
    -------
    g : seaborn.FacetGrid
    '''
    scores = unpack_grid_scores(model)
    y = y or 'mean_'
    return sns.factorplot(x=x, y=y, hue=hue, row=row, col=col, data=scores,
                          col_wrap=col_wrap, **kwargs)
//  [python]
def plot_grid_scores(model, x, y=None, hue=None, row=None, col=None, col_wrap=None,
                     **kwargs):
    '''
    Wrapper around seaborn.factorplot.

    Parameters
    ----------
    model : Pipeline or Estimator
    x, hue, row, col : str
        parameters grid searched over
    y : str
        the target of interest, default `'mean_'`

    Returns
    -------
    g : seaborn.FacetGrid
    '''
    scores = unpack_grid_scores(model)
    y = y or 'mean_'
    return sns.catplot(x=x, y=y, hue=hue, row=row, col=col, data=scores,
                          col_wrap=col_wrap, kind="bar", **kwargs)
//  [python]
def plot_models(accs):
    cv_df = pd.DataFrame(accs, columns=['model','pipeline', 'score'])
    sns.factorplot(x='model',y='score', hue='pipeline', data=cv_df, kind='bar')
//  [python]
def plot_models(accs):
    cv_df = pd.DataFrame(accs, columns=['model','pipeline', 'score'])
    sns.catplot(x='model',y='score', hue='pipeline', data=cv_df, kind='bar')
//  [python]
def plot_mushra_boxplots(data, size=5, output_file=None):
    """
    Plot the MUSHRA ratings as a grid of boxplots. If `output_file` is defined, then save the plot to file.

    Parameters
    ----------
    data: pandas.DataFrame
        The ratings data obtained from `get_ratings_data`.

    size : float
        Height of each boxplot in inches. (default is 5)

    output_file: str
        Path to the output file location. (default is None)

    Returns
    -------
    g : seaborn.axisgrid.FacetGrid
    """
    g = sns.factorplot(x='stimulus', y='rating', data=data, row='condition_id', kind='box', notch=True, size=size)
    g.set(ylim=(app.config['MIN_RATING_VALUE'], app.config['MAX_RATING_VALUE']))

    if output_file is not None:
        g.savefig(output_file)
//  [python]
def plot_mushra_boxplots(data, size=5, output_file=None):
    """
    Plot the MUSHRA ratings as a grid of boxplots. If `output_file` is defined, then save the plot to file.

    Parameters
    ----------
    data: pandas.DataFrame
        The ratings data obtained from `get_ratings_data`.

    size : float
        Height of each boxplot in inches. (default is 5)

    output_file: str
        Path to the output file location. (default is None)

    Returns
    -------
    g : seaborn.axisgrid.FacetGrid
    """
    g = sns.catplot(x='stimulus', y='rating', data=data, row='condition_id', kind='box', notch=True, height=size)
    g.set(ylim=(app.config['MIN_RATING_VALUE'], app.config['MAX_RATING_VALUE']))

    if output_file is not None:
        g.savefig(output_file)
//  [python]
def plot_liquid_comparison(data_filename, plot_filename, verbose):
        # Use latex font
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif')

        # sns.set_context("paper", rc={"font.size": 80,
        #                              "axes.titlesize": 80,
        #                              "axes.labelsize": 50})

        # Set up Seaborn style
        sns.set(style="darkgrid")

        # Import the dataframe
        dataframe = pd.read_csv(data_filename, header=0)

        # Keep the data we want
        dataframe = dataframe.loc[(dataframe['algorithm'] != 'quickbb')]
        dataframe = dataframe.loc[dataframe['vertices'].isin([10, 14, 18,
                                                              22, 26, 30])]

        dataframe['algorithm'] =\
            np.vectorize(algorithm_font)(dataframe['algorithm'])
        dataframe['runtime'] =\
            np.vectorize(runtime)(dataframe['tree-decomp-time'],
                                  dataframe['simulation-time'])
        if verbose:
            print(dataframe)

        # Compute the plot
        facet_kws = dict()
        warnings.simplefilter(action='ignore', category=FutureWarning)
        plot = sns.factorplot(data=dataframe,
                              row="regularity",
                              x="vertices",
                              y="runtime",
                              hue="algorithm",
                              palette=[colors[x] for x in ['freetdi', 'meiji', 'liquid']],
                              facet_kws=facet_kws,
                              kind="strip",
                              dodge=True,
                              jitter=True,
                              alpha=0.7,
                              linewidth=0.1,
                              aspect=1.7,
                              size=2.5,
                              hue_order=['\\textsf{qTorch-freetdi}',
                                         '\\textsf{qTorch-meiji-e}',
                                         '\\textsf{LIQUID}'],
                              legend=False)

        # Manually add dashed lines to facets
        for axis in plot.fig.get_axes():
            for i in range(len(dataframe["vertices"]) - 1):
                axis.axvline(x=i+.5, c="white", dashes=(2, 1))
                axis.axhline(y=600, c='black', dashes=(3, 3))

        # Set axis lengths and format
        plot.set(ylim=(.01, 1000000), yscale='log')

        # Set axis labels
        plot.fig.get_axes()[-1].set(xlabel="Vertices")
        for axis in plot.fig.get_axes():
            axis.set(ylabel="Total Simulation Time (sec)")

        # Set axis labels
        plot.set_titles(row_template="{row_name}-Regular")

        # Add legend
        plot.fig.get_axes()[0].legend(loc="upper left")

        # Save figure
        for extension in ['.pdf', '.png']:
            plot.savefig(plot_filename + extension)
//  [python]
def plot_liquid_comparison(data_filename, plot_filename, verbose):
        # Use latex font
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif')

        # sns.set_context("paper", rc={"font.size": 80,
        #                              "axes.titlesize": 80,
        #                              "axes.labelsize": 50})

        # Set up Seaborn style
        sns.set(style="darkgrid")

        # Import the dataframe
        dataframe = pd.read_csv(data_filename, header=0)

        # Keep the data we want
        dataframe = dataframe.loc[(dataframe['algorithm'] != 'quickbb')]
        dataframe = dataframe.loc[dataframe['vertices'].isin([10, 14, 18,
                                                              22, 26, 30])]

        dataframe['algorithm'] =\
            np.vectorize(algorithm_font)(dataframe['algorithm'])
        dataframe['runtime'] =\
            np.vectorize(runtime)(dataframe['tree-decomp-time'],
                                  dataframe['simulation-time'])
        if verbose:
            print(dataframe)

        # Compute the plot
        facet_kws = dict()
        warnings.simplefilter(action='ignore', category=FutureWarning)
        plot = sns.catplot(data=dataframe,
                              row="regularity",
                              x="vertices",
                              y="runtime",
                              hue="algorithm",
                              palette=[colors[x] for x in ['freetdi', 'meiji', 'liquid']],
                              facet_kws=facet_kws,
                              kind="strip",
                              dodge=True,
                              jitter=True,
                              alpha=0.7,
                              linewidth=0.1,
                              aspect=1.7,
                              height=2.5,
                              hue_order=['\\textsf{qTorch-freetdi}',
                                         '\\textsf{qTorch-meiji-e}',
                                         '\\textsf{LIQUID}'],
                              legend=False)

        # Manually add dashed lines to facets
        for axis in plot.fig.get_axes():
            for i in range(len(dataframe["vertices"]) - 1):
                axis.axvline(x=i+.5, c="white", dashes=(2, 1))
                axis.axhline(y=600, c='black', dashes=(3, 3))

        # Set axis lengths and format
        plot.set(ylim=(.01, 1000000), yscale='log')

        # Set axis labels
        plot.fig.get_axes()[-1].set(xlabel="Vertices")
        for axis in plot.fig.get_axes():
            axis.set(ylabel="Total Simulation Time (sec)")

        # Set axis labels
        plot.set_titles(row_template="{row_name}-Regular")

        # Add legend
        plot.fig.get_axes()[0].legend(loc="upper left")

        # Save figure
        for extension in ['.pdf', '.png']:
            plot.savefig(plot_filename + extension)
//  [python]
def hist(data, field, filename):
	#sns.distplot(x)

	# Draw a count plot to show the number of planets discovered each year
	g = sns.factorplot(x=field, data=data, kind="count",
                   palette="BuPu", size=6, aspect=1.5)
	plt.savefig(filename)
//  [python]
def hist(data, field, filename):
	g = sns.catplot(x=field, data=data, kind="count",
                   palette="BuPu", height=6, aspect=1.5)
	plt.savefig(filename)
//  [python]
def monthly_fuel_gen(gen_df, fuel, folder, file_date, file_type='pdf', dpi=350,
                     save=False):
    """
    Make a FacetGrid plot of monthly generation for a single fuel category

    inputs:
        gen_df (dataframe): monthly generation for all fuels
        fuel (string): name of the fuel category to plot
        folder (path): folder where the plot should be saved
        file_type (string): file format (e.g. pdf, png, etc)
        dpi (int): dots per inch resolution for saved file (if not pdf)
        save (bool): if True, save the file

    """
    order = ['USA', 'SPP', 'MRO', 'RFC', 'SERC', 'TRE', 'FRCC', 'WECC', 'NPCC']
    temp = gen_df.loc[idx[:, fuel, :], :].reset_index()
    temp['Month'] = temp['datetime'].dt.month
    temp['Year'] = temp['datetime'].dt.year
    temp['million mwh'] = temp['generation (mwh)'] / 1e6

    with sns.plotting_context('paper', font_scale=1):

        g = sns.factorplot(x='Month', y='million mwh', hue='Year', sharey=False,
                           data=temp, col='nerc', col_wrap=3, col_order=order,
                           palette='viridis_r', scale=0.5, size=2)

        axes = g.axes.flatten()
        for ax, title in zip(axes, order):
            ax.set_title(title)
            ax.set_ylim(0, None)
    #         ax.set_ylim(0, 1050)
            if title in ['USA', 'RFC', 'FRCC']:
                ax.set_ylabel('Million MWh\n({})'.format(fuel))

    path = join(folder, 'Monthly {} gen {}.{}'.format(fuel, file_date, file_type))
    if save:
        plt.savefig(path, bbox_inches='tight', dpi=dpi)
//  [python]
def monthly_fuel_gen(gen_df, fuel, folder, file_date, file_type='pdf', dpi=350,
                     save=False):
    """
    Make a FacetGrid plot of monthly generation for a single fuel category

    inputs:
        gen_df (dataframe): monthly generation for all fuels
        fuel (string): name of the fuel category to plot
        folder (path): folder where the plot should be saved
        file_type (string): file format (e.g. pdf, png, etc)
        dpi (int): dots per inch resolution for saved file (if not pdf)
        save (bool): if True, save the file

    """
    order = ['USA', 'SPP', 'MRO', 'RFC', 'SERC', 'TRE', 'FRCC', 'WECC', 'NPCC']
    temp = gen_df.loc[idx[:, fuel, :], :].reset_index()
    temp['Month'] = temp['datetime'].dt.month
    temp['Year'] = temp['datetime'].dt.year
    temp['million mwh'] = temp['generation (mwh)'] / 1e6

    with sns.plotting_context('paper', font_scale=1):

        g = sns.catplot(x='Month', y='million mwh', hue='Year', sharey=False,
                           data=temp, col='nerc', col_wrap=3, col_order=order,
                           palette='viridis_r', height=2, aspect=1.2)

        axes = g.axes.flatten()
        for ax, title in zip(axes, order):
            ax.set_title(title)
            ax.set_ylim(0, None)
    #         ax.set_ylim(0, 1050)
            if title in ['USA', 'RFC', 'FRCC']:
                ax.set_ylabel('Million MWh\n({})'.format(fuel))

    path = join(folder, 'Monthly {} gen {}.{}'.format(fuel, file_date, file_type))
    if save:
        plt.savefig(path, bbox_inches='tight', dpi=dpi)
//  [python]
tips = sns.load_dataset('tips')
with sns.axes_style(style='ticks'):
    g = sns.factorplot("day", "total_bill", "sex", data=tips, kind="box")
    g.set_axis_labels("Bill Day", "Total Bill Amount");
//  [python]
tips = sns.load_dataset('tips')
with sns.axes_style(style='ticks'):
    g = sns.catplot("day", "total_bill", "sex", data=tips, kind="box")
    g.set_axis_labels("Bill Day", "Total Bill Amount");
//  [python]
plt.figure(figsize=(20,10))
sns.set(font_scale = 2)
sns.countplot(description_text.Litigation)


# In[298]:


# Frequency Countplot for Categorical variable
get_ipython().run_line_magic('matplotlib', 'inline')

# factorplot for all categorical variables
for i in categorical_variables:
    sns.factorplot(data=description_text, x=i ,kind='count', size=6, aspect=2)
//  [python]
plt.figure(figsize=(20,10))
sns.set(font_scale = 2)
sns.countplot(description_text.Litigation)


# In[298]:


# Frequency Countplot for Categorical variable
get_ipython().run_line_magic('matplotlib', 'inline')

# factorplot for all categorical variables
for i in categorical_variables:
    sns.catplot(data=description_text, x=i ,kind='count', height=6, aspect=2)
//  [python]
def factorplot():
    titanic = sns.load_dataset('titanic')
    sns.factorplot(x='age', y='embark_town', 
                   hue='sex', data=titanic,
                   row='class', col='sex', 
                   col_wrap=None, estimator=np.mean, ci=95, 
                   n_boot=1000, units=None, order=None, 
                   hue_order=None, row_order=None, 
                   col_order=None, kind="box", size=4, 
                   aspect=1, orient=None, color=None, 
                   palette=None, legend=True, 
                   legend_out=True, sharex=True, 
                   sharey=True, margin_titles=False, 
                   facet_kws=None)
    sns.plt.show()
//  [python]
def factorplot():
    titanic = sns.load_dataset('titanic')
    sns.catplot(x='age', y='embark_town', 
                   hue='sex', data=titanic,
                   row='class', col='sex', 
                   col_wrap=None, estimator=np.mean, ci=95, 
                   n_boot=1000, units=None, order=None, 
                   hue_order=None, row_order=None, 
                   col_order=None, kind="box", height=4, 
                   aspect=1, orient=None, color=None, 
                   palette=None, legend=True, 
                   legend_out=True, sharex=True, 
                   sharey=True, margin_titles=False, 
                   facet_kws=None)
    sns.plt.show()
//  [python]
def read_length_distributions(path, refs):
    """Get read lengths for all aligned files in path mapped
       to ref db names, assumes the fasta files and sam files are present in the
       target folder
    """

    files = glob.glob(path+'/*.fa')
    fnames = [os.path.splitext(os.path.basename(f))[0] for f in files]
    fnames = [i for i in fnames if not i.endswith('_r')]
    print (fnames)

    res = []
    for n in fnames:
        x = get_aligned_reads_lengths(path, n, refs)
        x = x.ix[10:40]
        x['file'] = n
        res.append(x)
    res = pd.concat(res)
    res = res.reset_index()
    #print res[:60]
    #plot histograms
    m = pd.melt(res, id_vars=['file','length'], value_vars=refs,
                var_name='ref', value_name='freq')
    g = sns.factorplot(y='freq',x='length', data=m, row='ref', kind="bar",
                        size=2,aspect=4,sharex=False,palette='Blues_d')
    plt.savefig(os.path.join(path,'read_lengths.png'))
    return res
//  [python]
def read_length_distributions(path, refs):
    """Get read lengths for all aligned files in path mapped
       to ref db names, assumes the fasta files and sam files are present in the
       target folder
    """

    files = glob.glob(path+'/*.fa')
    fnames = [os.path.splitext(os.path.basename(f))[0] for f in files]
    fnames = [i for i in fnames if not i.endswith('_r')]
    print (fnames)

    res = []
    for n in fnames:
        x = get_aligned_reads_lengths(path, n, refs)
        x = x.ix[10:40]
        x['file'] = n
        res.append(x)
    res = pd.concat(res)
    res = res.reset_index()
    #print res[:60]
    #plot histograms
    m = pd.melt(res, id_vars=['file','length'], value_vars=refs,
                var_name='ref', value_name='freq')
    g = sns.catplot(y='freq',x='length', data=m, row='ref', kind="bar",
                        size=2,aspect=4,sharex=False,palette='Blues_d')
    plt.savefig(os.path.join(path,'read_lengths.png'))
    return res
//  [python]
def plot_accuracies_per_tag(title, **kwargs):
    if kwargs is None:
        print("Need accuracies to plot")
        return

    classes = set(sum([list(kwargs[exp].keys()) for exp in kwargs], []))
    classes = list(classes)
    classes.remove("__OVERALL__")
    classes = ["Overall"] + sorted(classes)

    experiments = {}
    for exp in kwargs:
        experiments[exp] = {
            k: kwargs[exp][k] for k in kwargs[exp] if k != "__OVERALL__"
        }
        experiments[exp]["Overall"] = kwargs[exp]["__OVERALL__"]

    df = pd.DataFrame([{"experiment": exp, **experiments[exp]} for exp in experiments])

    df = pd.melt(df, id_vars="experiment", var_name="type", value_name="accuracy")

    fig, ax = plt.subplots(1, 1, figsize=(16, 6))
    plt.sca(ax)
    ax.tick_params(axis="x", rotation=90)
    ax.set_ylim((0.5, 1.05))
    sns.factorplot(
        ax=ax,
        x="type",
        y="accuracy",
        hue="experiment",
        data=df,
        kind="bar",
        order=classes,
        legend_out=True,
    )

    handles, labels = ax.get_legend_handles_labels()
    l = ax.legend(
        handles=handles,
        labels=labels,
        title=title,
        frameon=True,
        fancybox=True,
        framealpha=0.8,
        facecolor="#FFFFFF",
    )

    return fig