jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_res_within_group_seperated(self, res_type='avgrtn', flag=1):
        df = self.input_df2.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_res_wt_grp_sep = data_graph

        if res_type in data_graph.columns:
            data_graph = data_graph[res_type].stack().rename(res_type).reset_index()
            g = sn.catplot(data=data_graph, 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)
        else:
            data_graph_melted = data_graph.stack().reset_index().melt(id_vars=['cycle', 'segment', 'user_grp'])
            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)
            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(20, 15)
        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_best_fig(all_data, needed, save_fig=False, save_type='png'):
    apps = list(all_data['app'].unique())
    for app in apps:
        if app == "LINEAR_DAG":
            continue
        __sel = all_data[all_data['app'] == app]
        args = list(__sel['arg'].unique())
        for arg in args:
            __sel_arg = __sel[__sel['arg'] == arg]
            exes = list(__sel_arg['exe'].unique())
            depend_type = None
            for exe in exes:
                if 'task' in exe:
                    depend_type = __sel_arg.loc[__sel_arg[__sel_arg['exe']
                                                          == exe][needed[-6]].idxmin()][needed[:2]]
            __best = __sel_arg[(__sel_arg[needed[0]] == depend_type[needed[0]]) & (
                __sel_arg[needed[1]] == depend_type[needed[1]])]
            graph = sns.factorplot(hue="Type",
                                   y=needed[-6],
                                   order=['Tasking',
                                          'BSP'],
                                   hue_order=["Tasking",
                                              "BSP"],
                                   x="Type",
                                   data=__best,
                                   kind='bar')
            plt.title(app + ": " + arg)
            if save_fig:
                graph.savefig(
                    fname=app +
                    arg +
                    "_best." +
                    save_type,
                    transparent=True,
                    dpi=600,
                    format=save_type,
                    bbox_inches='tight')
//  [python]
def plot_best_fig(all_data, needed, save_fig=False, save_type='png'):
    apps = list(all_data['app'].unique())
    for app in apps:
        if app == "LINEAR_DAG":
            continue
        __sel = all_data[all_data['app'] == app]
        args = list(__sel['arg'].unique())
        for arg in args:
            __sel_arg = __sel[__sel['arg'] == arg]
            exes = list(__sel_arg['exe'].unique())
            depend_type = None
            for exe in exes:
                if 'task' in exe:
                    depend_type = __sel_arg.loc[__sel_arg[__sel_arg['exe']
                                                          == exe][needed[-6]].idxmin()][needed[:2]]
            __best = __sel_arg[(__sel_arg[needed[0]] == depend_type[needed[0]]) & (
                __sel_arg[needed[1]] == depend_type[needed[1]])]
            graph = sns.catplot(hue="Type",
                                   y=needed[-6],
                                   order=['Tasking',
                                          'BSP'],
                                   hue_order=["Tasking",
                                              "BSP"],
                                   x="Type",
                                   data=__best,
                                   kind='bar')
            plt.title(app + ": " + arg)
            if save_fig:
                graph.savefig(
                    fname=app +
                    arg +
                    "_best." +
                    save_type,
                    transparent=True,
                    dpi=600,
                    format=save_type,
                    bbox_inches='tight')
//  [python]
def factorplot_cluster(cluster, cov, palette='Set1', ilogit=False):
    # http://web.stanford.edu/~mwaskom/software/seaborn/tutorial/categorical_linear_models.html
    """
    Create a factor plot.

    .. plot::
        :include-source: true

        >>> import crystal
        >>> import crystal.utils as cu
        >>> covs, cluster = cu.real_cluster()
        >>> formula = "methylation ~ age + gender"
        >>> c = crystal.wrapper(crystal.zscore_cluster, formula, cluster, covs, "gender")
        >>> crystal.plot.factorplot_cluster(c, covs)

    """
    features = cluster['cluster']
    methylation = np.array([f.values for f in features]).T
    if ilogit:
        methylation = 1 / (1 + np.exp(-methylation))
    df = pd.DataFrame(methylation, columns=[f.spos for f in features])
    df['id'] = [str(x) for x in cov['id']]
    var = cluster['var']
    df[var] = [str(x) for x in cov[var]]
    df = pd.melt(df, id_vars=(var, 'id'), var_name='position')

    fp = sns.factorplot('position', 'value', var, df, kind='box',
            palette=palette, legend=False)
    plt.draw()
    ax = fp.fig.axes[0]
    ax.legend(loc='best')
    return fp
//  [python]
def factorplot_cluster(cluster, cov, palette='Set1', ilogit=False):
    features = cluster['cluster']
    methylation = np.array([f.values for f in features]).T
    if ilogit:
        methylation = 1 / (1 + np.exp(-methylation))
    df = pd.DataFrame(methylation, columns=[f.spos for f in features])
    df['id'] = [str(x) for x in cov['id']]
    var = cluster['var']
    df[var] = [str(x) for x in cov[var]]
    df = pd.melt(df, id_vars=(var, 'id'), var_name='position')

    fp = sns.catplot('position', 'value', var, data=df, kind='box',
            palette=palette, legend=False)
    plt.draw()
    ax = fp.fig.axes[0]
    ax.legend(loc='best')
    return fp
//  [python]
g = sns.FacetGrid(train, size=8, aspect=0.5, hue="Survived", 
                  col ="Pclass", margin_titles=True,
                palette=pal)
g.map(plt.scatter, "Fare", "Age",edgecolor="w").add_legend()
g.fig.suptitle("Survived by Pclass, Fare and Age", size = 25)
plt.subplots_adjust(top=0.85)


# In[54]:


g = sns.factorplot(y = "Survived",
               x = "Sex",
               col = "Embarked",
               row = "Cabin",
              data = train, 
              kind = "bar",
              ci = None,
               margin_titles=True,
              size = 4)
//  [python]
g = sns.catplot(y = "Survived",
               x = "Sex",
               col = "Embarked",
               row = "Cabin",
              data = train, 
              kind = "bar",
              ci = None,
               margin_titles=True,
              height = 4)
//  [python]
def plot_sweep_fig(all_data, needed, save_fig=False, save_type='png'):
    apps = list(all_data['app'].unique())
    for app in apps:
        __sel = all_data[all_data['app'] == app]
        exes = list(__sel['exe'].unique()).sort()
        args = list(__sel['arg'].unique())
        print(app)
        for x_arg in [0, 1]:
            if app == "LINEAR_DAG":
                __sel['Per-Kernel Time (ms)'] = __sel[needed[3]]
                for arg in args:
                    val = int(arg.strip().split()[0])
                    __sel.loc[(__sel['arg'] == arg), 'Per-Kernel Time (ms)'] = __sel[__sel['arg']
                                                                                     == arg]['Per-Kernel Time (ms)'] / val
                graph = sns.factorplot(
                    hue=needed[0],
                    y='Per-Kernel Time (ms)',
                    order=exes,
                    x=needed[1],
                    col="arg",
                    data=__sel,
                    kind='bar')
                if save_fig:
                    graph.savefig(
                        fname=app +
                        "_sweep." +
                        save_type,
                        transparent=True,
                        frameon=False,
                        dpi=600,
                        format=save_type,
                        bbox_inches='tight')
                # plt.title(app)
            else:
                graph = sns.factorplot(hue="Type",
                                       y=needed[-6],
                                       hue_order=["Tasking",
                                                  "BSP"],
                                       x=needed[x_arg],
                                       col="arg",
                                       data=__sel,
                                       kind='bar')
                if save_fig:
                    graph.savefig(
                        fname=app +
                        "_" +
                        needed[x_arg] +
                        "_sweep." +
                        save_type,
                        transparent=True,
                        frameon=False,
                        dpi=600,
                        format=save_type,
                        bbox_inches='tight')
//  [python]
def plot_sweep_fig(all_data, needed, save_fig=False, save_type='png'):
    apps = list(all_data['app'].unique())
    for app in apps:
        __sel = all_data[all_data['app'] == app]
        exes = list(__sel['exe'].unique()).sort()
        args = list(__sel['arg'].unique())
        print(app)
        for x_arg in [0, 1]:
            if app == "LINEAR_DAG":
                __sel['Per-Kernel Time (ms)'] = __sel[needed[3]]
                for arg in args:
                    val = int(arg.strip().split()[0])
                    __sel.loc[(__sel['arg'] == arg), 'Per-Kernel Time (ms)'] = __sel[__sel['arg']
                                                                                     == arg]['Per-Kernel Time (ms)'] / val
                graph = sns.catplot(
                    hue=needed[0],
                    y='Per-Kernel Time (ms)',
                    order=exes,
                    x=needed[1],
                    col="arg",
                    data=__sel,
                    kind='bar')
                if save_fig:
                    graph.savefig(
                        fname=app +
                        "_sweep." +
                        save_type,
                        transparent=True,
                        frameon=False,
                        dpi=600,
                        format=save_type,
                        bbox_inches='tight')
                # plt.title(app)
            else:
                graph = sns.catplot(hue="Type",
                                       y=needed[-6],
                                       hue_order=["Tasking",
                                                  "BSP"],
                                       x=needed[x_arg],
                                       col="arg",
                                       data=__sel,
                                       kind='bar')
                if save_fig:
                    graph.savefig(
                        fname=app +
                        "_" +
                        needed[x_arg] +
                        "_sweep." +
                        save_type,
                        transparent=True,
                        frameon=False,
                        dpi=600,
                        format=save_type,
                        bbox_inches='tight')
//  [python]
def getTop10HighBudgetMovie(self,data):
        sns.factorplot(aspect=1.5,y='title',x='budget_in_millions',data=data.sort_values(['budget_in_millions'],ascending=False).drop(['genre'],axis=1).drop_duplicates().head(10),palette="ch:.25",kind='bar')
        sns.set_style("ticks",{"xtick.major.size":8,"ytick.major.size":8})
        plt.title('Top 10 High Budget Movies',fontsize=20)
        plt.ylabel('Title',fontsize=15)
        plt.xlabel('Budget In Millions',fontsize=15)
        sns.despine(trim=True,left=True)
        plt.show()
//  [python]
def getTop10HighBudgetMovie(self,data):
        sns.catplot(aspect=1.5,y='title',x='budget_in_millions',data=data.sort_values(['budget_in_millions'],ascending=False).drop(['genre'],axis=1).drop_duplicates().head(10),palette="ch:.25",kind='bar')
        sns.set_style("ticks",{"xtick.major.size":8,"ytick.major.size":8})
        plt.title('Top 10 High Budget Movies',fontsize=20)
        plt.ylabel('Title',fontsize=15)
        plt.xlabel('Budget In Millions',fontsize=15)
        sns.despine(trim=True,left=True)
        plt.show()
//  [python]
def getTop10(self,data):
        p=sns.factorplot(aspect=1.5,y='title',x='audience_rating',data=data.sort_values(['audience_rating','critic_rating'],ascending=False).drop(['genre'],axis=1).drop_duplicates().head(10),palette="ch:.25",kind='bar')
        p.set(xlim=(10,100))
        sns.set_style("ticks",{"xtick.major.size":8,"ytick.major.size":8})
        plt.title('Top 10 Rated Movies',fontsize=20)
        plt.ylabel('Title',fontsize=15)
        plt.xlabel('Audience Rating',fontsize=15)
        sns.despine(trim=True,left=True)
        plt.show()
//  [python]
def getTop10(self,data):
        p=sns.catplot(aspect=1.5,y='title',x='audience_rating',data=data.sort_values(['audience_rating','critic_rating'],ascending=False).drop(['genre'],axis=1).drop_duplicates().head(10),palette="ch:.25",kind='bar')
        p.set(xlim=(10,100))
        sns.set_style("ticks",{"xtick.major.size":8,"ytick.major.size":8})
        plt.title('Top 10 Rated Movies',fontsize=20)
        plt.ylabel('Title',fontsize=15)
        plt.xlabel('Audience Rating',fontsize=15)
        sns.despine(trim=True,left=True)
        plt.show()
//  [python]
sns.countplot('Pclass',hue='Survived',data=data,ax=ax[1])
ax[1].set_title('Pclass:Survived vs Dead')
plt.show()


# People say **Money Can't Buy Everything**. But we can clearly see that Passenegers Of Pclass 1 were given a very high priority while rescue. Even though the the number of Passengers in Pclass 3 were a lot higher, still the number of survival from them is very low, somewhere around **25%**.
# 
# For Pclass 1 %survived is around **63%** while for Pclass2 is around **48%**. So money and status matters. Such a materialistic world.
# 
# Lets Dive in little bit more and check for other interesting observations. Lets check survival rate with **Sex and Pclass** Together.

# In[ ]:


pd.crosstab([data.Sex,data.Survived],data.Pclass,margins=True).style.background_gradient(cmap='summer_r')


# In[ ]:


sns.factorplot('Pclass','Survived',hue='Sex',data=data)
//  [python]
sns.catplot('Pclass','Survived',hue='Sex',data=data)
//  [python]
def plotBasicLengthStatsByYearAndMonth(data, yearsToShow=None, targetStats=None,
                                       targetSenders=None):
    df = statsUtil.filter_stats(data, {'sender':targetSenders, 'year':yearsToShow,
                                        'stat':targetStats})

    g = sns.factorplot(x="month", y="val", row="stat", hue='sender', col='year', data=df,
                       kind="bar", size=3, aspect=2.5, legend_out=False)
    g.fig.suptitle('Basic Length Stats')
    sns.plt.show()
//  [python]
def plotBasicLengthStatsByYearAndMonth(data, yearsToShow=None, targetStats=None,
                                       targetSenders=None):
    df = statsUtil.filter_stats(data, {'sender':targetSenders, 'year':yearsToShow,
                                        'stat':targetStats})

    g = sns.catplot(x="month", y="val", row="stat", hue='sender', col='year', data=df,
                       kind="bar", height=3, aspect=2.5, legend_out=False)
    g.fig.suptitle('Basic Length Stats')
    sns.plt.show()
//  [python]
def plotBasicLengthStatsByHour(data, targetStats=None, targetSenders=None, kind='bar'):
    df = statsUtil.filter_stats(data, {'sender':targetSenders, 'stat':targetStats})

    g = sns.factorplot(x="hour", y="val", row="stat", hue='sender', data=df,
                       kind=kind, size=3, aspect=2.5, legend_out=False)
    g.fig.suptitle('Basic Length Stats - Hour')
//  [python]
def plotBasicLengthStatsByHour(data, targetStats=None, targetSenders=None, kind='bar'):
    df = statsUtil.filter_stats(data, {'sender':targetSenders, 'stat':targetStats})

    g = sns.catplot(x="hour", y="val", row="stat", hue='sender', data=df,
                       kind=kind, height=3, aspect=2.5, legend_out=False)
    g.fig.suptitle('Basic Length Stats - Hour')
//  [python]
def plotSentimentStatsByHour(sentimentStats, valueNames):
    data = statsUtil.transformSentimentStats(sentimentStats, valueNames, ['sender', 'hour'])
    ax = sns.factorplot(x="hour", y="val", col="emotion", hue='sender',
                   data=data, kind="point", sharey=False, legend_out=False)
    ax.set(ylabel='mean(val)')
    sns.plt.show()
//  [python]
def plotSentimentStatsByHour(sentimentStats, valueNames):
    data = statsUtil.transformSentimentStats(sentimentStats, valueNames, ['sender', 'hour'])
    ax = sns.catplot(x="hour", y="val", col="emotion", hue='sender',
                   data=data, kind="point", sharey=False, legend_out=False)
    ax.set(ylabel='mean(val)')
    sns.plt.show()
//  [python]
def _genericFactorPlot(data, xTarget, yTarget, filters, title, yLabel, col=None, row=None,
                       kind='point'):
    df = statsUtil.filter_stats(data, filters)

    g = sns.factorplot(x=xTarget, y=yTarget, col=col, row=row, hue='sender',
                        data=df, kind=kind, legend_out=False)
    g.set(ylabel=yLabel)
    g.fig.suptitle(title)
    sns.plt.show()
//  [python]
def _genericFactorPlot(data, xTarget, yTarget, filters, title, yLabel, col=None, row=None,
                       kind='point'):
    df = statsUtil.filter_stats(data, filters)

    g = sns.catplot(x=xTarget, y=yTarget, col=col, row=row, hue='sender',
                        data=df, kind=kind, legend_out=False)
    g.set(ylabel=yLabel)
    g.fig.suptitle(title)
    sns.plt.show()
//  [python]
def plotRichnessVariation(data, targetLabel, yearsToShow=None, targetSenders=None):
    df = data.reset_index()
    df = statsUtil.filter_stats(df, {'year':yearsToShow, 'sender':targetSenders})

    g = sns.factorplot(x=targetLabel, y="lexicalRichness", col="year", hue='sender',
                   data=df, kind="point", legend_out=False)
    g.set(ylabel='lexical richness (%)')
    g.fig.suptitle('Vocabulary Richness')
    sns.plt.show()
//  [python]
def plotRichnessVariation(data, targetLabel, yearsToShow=None, targetSenders=None):
    df = data.reset_index()
    df = statsUtil.filter_stats(df, {'year':yearsToShow, 'sender':targetSenders})

    g = sns.catplot(x=targetLabel, y="lexicalRichness", col="year", hue='sender',
                   data=df, kind="point", legend_out=False)
    g.set(ylabel='lexical richness (%)')
    g.fig.suptitle('Vocabulary Richness')
    sns.plt.show()
//  [python]
def save_plot(df, title, filename, x="Threads", hue="Benchmark", col=param_pool_size, col_wrap=2, print_data=False,
              formatter=tkr.FuncFormatter(lambda y, p: "{:,}".format(y)), left=left_adjust_multiple):
    unit = df['Unit'].unique()[0]
    print("Creating chart: " + title + ", filename: " + filename + ".")
    if print_data:
        print_dataframe(df)
    fig, ax = plt.subplots()
    g = sns.factorplot(x=x, y="Score", hue=hue, col=col, data=df, kind='bar',
                       size=5, aspect=1, col_wrap=col_wrap, legend=False)
    for ax in g.axes.flatten():
        ax.yaxis.set_major_formatter(formatter)
    g.set_axis_labels(y_var="Score (" + unit + ")")
    plt.subplots_adjust(top=0.9, left=left)
    g.fig.suptitle(title)
    plt.legend(loc='best', title=hue, frameon=True)
    plt.savefig(filename)
    plt.clf()
    plt.close(fig)
//  [python]
def save_plot(df, title, filename, x="Threads", hue="Benchmark", col=param_pool_size, col_wrap=2, print_data=False,
              formatter=tkr.FuncFormatter(lambda y, p: "{:,}".format(y)), left=left_adjust_multiple):
    unit = df['Unit'].unique()[0]
    print("Creating chart: " + title + ", filename: " + filename + ".")
    if print_data:
        print_dataframe(df)
    fig, ax = plt.subplots()
    g = sns.catplot(x=x, y="Score", hue=hue, col=col, data=df, kind='bar',
                       height=5, aspect=1, col_wrap=col_wrap, legend=False)
    for ax in g.axes.flatten():
        ax.yaxis.set_major_formatter(formatter)
    g.set_axis_labels(y_var="Score (" + unit + ")")
    plt.subplots_adjust(top=0.9, left=left)
    g.fig.suptitle(title)
    plt.legend(loc='best', title=hue, frameon=True)
    plt.savefig(filename)
    plt.clf()
    plt.close(fig)
//  [python]
def plotSentimentStatsByYearAndMonth(sentimentStats, valueNames):
    data = statsUtil.transformSentimentStats(sentimentStats, valueNames, ['sender', 'year', 'month'])
    sns.factorplot(x="month", y="val", row="emotion", hue='sender', col='year',
                   data=data, kind="point", sharey=False, legend_out=False)
    sns.plt.show()
//  [python]
def plotSentimentStatsByYearAndMonth(sentimentStats, valueNames):
    data = statsUtil.transformSentimentStats(sentimentStats, valueNames, ['sender', 'year', 'month'])
    sns.catplot(x="month", y="val", row="emotion", hue='sender', col='year',
                   data=data, kind="point", sharey=False, legend_out=False)
    sns.plt.show()
//  [python]
def PlotFeatureImp(feature_importance_table):
    sns.set_style("darkgrid")
    sns.factorplot(x="importance", y="feature_name",data=feature_importance_table, kind="bar")
    plt.savefig('./fig/5_Feature_Imp_XGB.png',dpi=100)
//  [python]
def PlotFeatureImp(feature_importance_table):
    sns.set_style("darkgrid")
    sns.catplot(x="importance", y="feature_name",data=feature_importance_table, kind="bar")
    plt.savefig('./fig/5_Feature_Imp_XGB.png',dpi=100)
//  [python]
def CountPlot(dataset, column, label, s, a):   #Day of Week_Count_Plot
    sns.set_style("darkgrid")
    sns_plot = sns.factorplot(x=column,data=dataset,kind='count', palette="muted",size = s, aspect = a)
    plt.xlabel(label)
    plt.ylabel('Frequency')
    plt.tight_layout()
    sns_plot.savefig('./fig/'+label + '_Count_Plot.png',dpi=100)
//  [python]
def CountPlot(dataset, column, label, s, a):   #Day of Week_Count_Plot
    sns.set_style("darkgrid")
    sns_plot = sns.catplot(x=column,data=dataset,kind='count', palette="muted",size = s, aspect = a)
    plt.xlabel(label)
    plt.ylabel('Frequency')
    plt.tight_layout()
    sns_plot.savefig('./fig/'+label + '_Count_Plot.png',dpi=100)
//  [python]
def plot_factor(self,title_,df,feat_X,feat_Y,feat_Group,ext_info=""):
        label='%.4f'
        if feat_Y=="memory":
            label='%.2f M'
        elif feat_Y=="accuracy":
            label='AUC=%.4f'
        elif feat_Y=="time":
            label='%.2f s'
        df_1 = df[[feat_X,feat_Y,feat_Group]]
        #df_2 = pd.melt(df_1, id_vars="method", var_name="dataset", value_name="accuracy")
        sns.factorplot(feat_X, feat_Y, col=feat_Group, data=df_1, kind="bar")
        # Get current axis on current figure
        y_max = df_1[feat_Y].max() 
                
        axes = plt.gcf().get_axes()
        for ax in axes:
            ax.set_ylim([0, y_max*1.2])    
            # Iterate through the list of axes' patches
            for p in ax.patches:            
                height = p.get_height() # height of bar, which is basically the data value
                ax.text(p.get_x() + p.get_width()/2., height, label%height, 
                        fontsize=16, color='red', ha='center', va='bottom')

        plt.savefig(f"{title_}___{feat_Y}@{feat_X}@{feat_Group}.jpg")
        plt.show()
        plt.close()
//  [python]
def plot_factor(self,title_,df,feat_X,feat_Y,feat_Group,ext_info=""):
        label='%.4f'
        if feat_Y=="memory":
            label='%.2f M'
        elif feat_Y=="accuracy":
            label='AUC=%.4f'
        elif feat_Y=="time":
            label='%.2f s'
        df_1 = df[[feat_X,feat_Y,feat_Group]]
        #df_2 = pd.melt(df_1, id_vars="method", var_name="dataset", value_name="accuracy")
        sns.catplot(x=feat_X, y=feat_Y, col=feat_Group, data=df_1, kind="bar")
        # Get current axis on current figure
        y_max = df_1[feat_Y].max() 
                
        axes = plt.gcf().get_axes()
        for ax in axes:
            ax.set_ylim([0, y_max*1.2])    
            # Iterate through the list of axes' patches
            for p in ax.patches:            
                height = p.get_height() # height of bar, which is basically the data value
                ax.text(p.get_x() + p.get_width()/2., height, label%height, 
                        fontsize=16, color='red', ha='center', va='bottom')

        plt.savefig(f"{title_}___{feat_Y}@{feat_X}@{feat_Group}.jpg")
        plt.show()
        plt.close()
//  [python]
def factorplots(wine_set):
    seaborn.factorplot(x="quality", y="alcohol", data=wine_set, kind="strip")
    plt.xlabel("Quality level of wine, 0-10 scale")
    plt.ylabel("Alcohol level in wine, % ABV")
    if wine_set.equals(red):
        plt.title("Alcohol percent in each level of red wine's quality")
    else:
        plt.title("Alcohol percent in each level of white wine's quality")
    plt.show()
//  [python]
def factorplots(wine_set):
    seaborn.catplot(x="quality", y="alcohol", data=wine_set, kind="strip")
    plt.xlabel("Quality level of wine, 0-10 scale")
    plt.ylabel("Alcohol level in wine, % ABV")
    if wine_set.equals(red):
        plt.title("Alcohol percent in each level of red wine's quality")
    else:
        plt.title("Alcohol percent in each level of white wine's quality")
    plt.show()
//  [python]
def plot_res_between_groups_seperated(self, flag=1):
        df = self.input_df2.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 = 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)
        fig_title = {1: 'Processed by Overall Samples', 2: 'Processed by Individual and Concatenate'}[flag]
        g.fig.suptitle(fig_title + '\nPerformance by User-defined Group', x=0.8, y=0.99, fontsize=12)
        g.fig.set_size_inches(18, 4)
        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):
        df = self.input_df2.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 = 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)
        fig_title = {1: 'Processed by Overall Samples', 2: 'Processed by Individual and Concatenate'}[flag]
        g.fig.suptitle(fig_title + '\nPerformance by User-defined Group', x=0.8, y=0.99, fontsize=12)
        g.fig.set_size_inches(18, 4)
        g.fig.autofmt_xdate()
        g.fig.tight_layout(rect=(0.01, 0.01, 0.95, 0.92))
        g.add_legend()
        return g
//  [python]
def mem_svg(self, table, column, outfile):
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        import seaborn as sb
        sb.set(style="whitegrid")
        
        svgdat = (table.
            rename(columns={ column : 'Memory' }).
            groupby(['Dataset', 'Threads', 'Program']).
            agg({ 'Memory' : max }).
            reset_index())
        svgdat = svgdat.assign(MemoryMB=svgdat['Memory'] / 1000000)
        
        threads = svgdat.Threads.unique()
        if len(threads) == 1:
            plot = sb.factorplot(
                x='Program', y='MemoryMB', col="Dataset", 
                data=svgdat, kind="bar", ci=None, sharey=True)
        else:
            plot = sb.factorplot(
                x='Threads', y='MemoryMB', col="Dataset", hue="Program", 
                data=svgdat, kind="bar", ci=None, sharey=True)

        if len(threads) == 1:
            plot = plot.set_titles('')

        plot = plot.set_xlabels('Threads')
        plot = plot.set_ylabels('Memory (MB)')
        plot = plot.set_xticklabels(rotation=90)
        plot.fig.subplots_adjust(wspace=0.35)
        plot.savefig(outfile)
//  [python]
def mem_svg(self, table, column, outfile):
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        import seaborn as sb
        sb.set(style="whitegrid")
        
        svgdat = (table.
            rename(columns={ column : 'Memory' }).
            groupby(['Dataset', 'Threads', 'Program']).
            agg({ 'Memory' : max }).
            reset_index())
        svgdat = svgdat.assign(MemoryMB=svgdat['Memory'] / 1000000)
        
        threads = svgdat.Threads.unique()
        if len(threads) == 1:
            plot = sb.catplot(
                x='Program', y='MemoryMB', col="Dataset", 
                data=svgdat, kind="bar", ci=None, sharey=True)
        else:
            plot = sb.catplot(
                x='Threads', y='MemoryMB', col="Dataset", hue="Program", 
                data=svgdat, kind="bar", ci=None, sharey=True)

        if len(threads) == 1:
            plot = plot.set_titles('')

        plot = plot.set_xlabels('Threads')
        plot = plot.set_ylabels('Memory (MB)')
        plot = plot.set_xticklabels(rotation=90)
        plot.fig.subplots_adjust(wspace=0.35)
        plot.savefig(outfile)
//  [python]
def plot_one_company(company, n=20):
    df_one_company = df_small.loc[df_small['BrandName'].isin([company])]
    pivot = pd.pivot_table(df_one_company,
            values = ['Rating', 'ReviewVotes'],
            index =  ['ProductName'],
                       columns= [],
                       aggfunc=[np.sum, np.mean, np.count_nonzero, np.std], 
                       margins=True, fill_value=0).sort_values(by=('count_nonzero', 'Rating'), ascending=False).fillna('')
    top_10_prods = pivot.reindex().head(n=20)
    top_10_prods = top_10_prods.reset_index()
    tt_prods = top_10_prods['ProductName']
    tt_prods2 = tt_prods.reset_index()
    top_10_prods_list = list(set(tt_prods2['ProductName']))
    #top_30_prod_list

    try:
        aa= df_one_company[df_one_company['ProductName'].isin(top_10_prods_list)]
        g = sns.factorplot(x='ProductName', 
                           y='Rating',
                           data=aa, 
                           saturation=1, 
                           kind="bar", 
                           ci=None, 
                           aspect=4, 
                           linewidth=1) 
        locs, labels = plt.xticks()
        plt.setp(labels, rotation=90)
    except: 
        pass
//  [python]
def plot_one_company(company, n=20):
    df_one_company = df_small.loc[df_small['BrandName'].isin([company])]
    pivot = pd.pivot_table(df_one_company,
            values = ['Rating', 'ReviewVotes'],
            index =  ['ProductName'],
                       columns= [],
                       aggfunc=[np.sum, np.mean, np.count_nonzero, np.std], 
                       margins=True, fill_value=0).sort_values(by=('count_nonzero', 'Rating'), ascending=False).fillna('')
    top_10_prods = pivot.reindex().head(n=20)
    top_10_prods = top_10_prods.reset_index()
    tt_prods = top_10_prods['ProductName']
    tt_prods2 = tt_prods.reset_index()
    top_10_prods_list = list(set(tt_prods2['ProductName']))
    #top_30_prod_list

    try:
        aa= df_one_company[df_one_company['ProductName'].isin(top_10_prods_list)]
        g = sns.catplot(x='ProductName', 
                           y='Rating',
                           data=aa, 
                           saturation=1, 
                           kind="bar", 
                           ci=None, 
                           aspect=4, 
                           linewidth=1) 
        locs, labels = plt.xticks()
        plt.setp(labels, rotation=90)
    except: 
        pass
//  [python]
def Axis_FactorPlot(data, x, y=None, hue=None, row=None, col=None, kind="point"):
    sns.set(style="ticks")
    ax = sns.factorplot(x=x, y=y, hue=hue, data=data, kind=kind, row=row, col=col)
    d = mpld3.fig_to_dict(ax.fig)
    return d
//  [python]
def Axis_FactorPlot(data, x, y=None, hue=None, row=None, col=None, kind="point"):
    sns.set(style="ticks")
    ax = sns.catplot(x=x, y=y, hue=hue, data=data, kind=kind, row=row, col=col)
    d = mpld3.fig_to_dict(ax.fig)
    return d
//  [python]
def _plot(self):
        """Do plot"""

        import seaborn as sns
        self.applyOptions()
        kwds = self.kwds
        fontscale = kwds['fontscale']
        font = kwds['font']
        self.setDefaultStyle(fontscale=fontscale, font=font)

        df = self.table.getPlotData()
        #dtypes = list(df.dtypes)
        col = kwds['col']
        wrap=int(kwds['wrap'])
        ci = kwds['ci']
        logy = kwds['logy']
        melt = kwds['melt']
        if col == '':
            col = None
            wrap = 1
        if wrap == 1:
            row=col
            col=None
            wrap=None
        else:
            row=None
        hue = kwds['hue']
        kind = kwds['kind']
        x = kwds['x']
        order = None
        if x == '':
            x = 'var'
        aspect = float(kwds['aspect'])
        palette=kwds['palette']
        xlabelrot = kwds['rot']
        if hue == '':
            hue=None
        if col == '':
            col=None

        labels = list(df.select_dtypes(include=['object','category']).columns)
        if melt == True:
            t = pd.melt(df,id_vars=labels, var_name='var',value_name='value')
        else:
            t = df
        try:
            g = sns.factorplot(x=x,y='value',data=t, hue=hue, col=col, row=row,
                            col_wrap=wrap, kind=kind,size=3, aspect=float(aspect),
                            legend_out=False, sharey='all', palette=palette, order=order,
                            ci=ci)
            self.g = g
        except Exception as e:
            self.showWarning(e)
            return

        #need to always make a new canvas to get size right
        for child in self.pf.winfo_children():
            child.destroy()
        self.fig, self.canvas = plotting.addFigure(self.pf, g.fig)
        plt.suptitle(kwds['title'], fontsize=14*fontscale)
        plt.legend(loc='best')

        ylabel = kwds['ylabel']
        for ax in g.axes.flatten():
            for t in ax.get_xticklabels():
                t.set(rotation=xlabelrot)
            if ylabel != '':
                ax.set_ylabel(ylabel)
            if logy == True:
                ax.set_yscale('log')

        plt.tight_layout()
        bottom = 0.1
        if xlabelrot>30:
            bottom=0.2
        self.fig.subplots_adjust(top=0.9, bottom=bottom)
        self.canvas.draw()
        return
//  [python]
def _plot(self):
        """Do plot"""

        import seaborn as sns
        self.applyOptions()
        kwds = self.kwds
        fontscale = kwds['fontscale']
        font = kwds['font']
        self.setDefaultStyle(fontscale=fontscale, font=font)

        df = self.table.getPlotData()
        #dtypes = list(df.dtypes)
        col = kwds['col']
        wrap=int(kwds['wrap'])
        ci = kwds['ci']
        logy = kwds['logy']
        melt = kwds['melt']
        if col == '':
            col = None
            wrap = 1
        if wrap == 1:
            row=col
            col=None
            wrap=None
        else:
            row=None
        hue = kwds['hue']
        kind = kwds['kind']
        x = kwds['x']
        order = None
        if x == '':
            x = 'var'
        aspect = float(kwds['aspect'])
        palette=kwds['palette']
        xlabelrot = kwds['rot']
        if hue == '':
            hue=None
        if col == '':
            col=None

        labels = list(df.select_dtypes(include=['object','category']).columns)
        if melt == True:
            t = pd.melt(df,id_vars=labels, var_name='var',value_name='value')
        else:
            t = df
        try:
            g = sns.catplot(x=x,y='value',data=t, hue=hue, col=col, row=row,
                            col_wrap=wrap, kind=kind,height=3, aspect=float(aspect),
                            legend_out=False, sharey='all', palette=palette, order=order,
                            ci=ci)
            self.g = g
        except Exception as e:
            self.showWarning(e)
            return

        #need to always make a new canvas to get size right
        for child in self.pf.winfo_children():
            child.destroy()
        self.fig, self.canvas = plotting.addFigure(self.pf, g.fig)
        plt.suptitle(kwds['title'], fontsize=14*fontscale)
        plt.legend(loc='best')

        ylabel = kwds['ylabel']
        for ax in g.axes.flatten():
            for t in ax.get_xticklabels():
                t.set(rotation=xlabelrot)
            if ylabel != '':
                ax.set_ylabel(ylabel)
            if logy == True:
                ax.set_yscale('log')

        plt.tight_layout()
        bottom = 0.1
        if xlabelrot>30:
            bottom=0.2
        self.fig.subplots_adjust(top=0.9, bottom=bottom)
        self.canvas.draw()
        return
//  [python]
def plot_all_feat_coef(dict, coefficients, names):
    # Prepare Data-frame
    conc_coef = np.vstack(dict[coefficients])
    conc_names = np.vstack(dict[names])
    df_coef = pd.DataFrame(conc_coef, columns=conc_names[0])
    df_coef['fold'] = range(1, len(df_coef)+1)

    # PIVOT Data-frame
    df_pivot = pd.melt(df_coef, id_vars=['fold'])

    # Plot
    ax = sns.factorplot(x="variable", y="value", hue='fold', data=df_pivot)
    ax.set(xlabel='Features', ylabel='Feature Importance Score', title='Visualizing Important Features')
    plt.show()
//  [python]
def plot_all_feat_coef(dict, coefficients, names):
    # Prepare Data-frame
    conc_coef = np.vstack(dict[coefficients])
    conc_names = np.vstack(dict[names])
    df_coef = pd.DataFrame(conc_coef, columns=conc_names[0])
    df_coef['fold'] = range(1, len(df_coef)+1)

    # PIVOT Data-frame
    df_pivot = pd.melt(df_coef, id_vars=['fold'])

    # Plot
    ax = sns.catplot(x="variable", y="value", hue='fold', data=df_pivot)
    ax.set(xlabel='Features', ylabel='Feature Importance Score', title='Visualizing Important Features')
    plt.show()
//  [python]
def error_bars():

    diamonds = sns.load_dataset("diamonds")
    with sns.axes_style("whitegrid"):
        g = sns.factorplot(
            x="carat", y="clarity", hue="clarity", data=diamonds, kind="point",
            size=6, aspect=.7,
            errorbar=("sd", .5), join=False, legend=False,
            palette="ch:s=-.2,r=-.2,d=.4,l=.6_r", scale=.75, capsize=.3,
        )
    g.ax.yaxis.set_inverted(False)
    return g.fig
//  [python]
def error_bars():

    diamonds = sns.load_dataset("diamonds")
    with sns.axes_style("whitegrid"):
        g = sns.catplot(
            diamonds, x="carat", y="clarity", hue="clarity", kind="point",
            errorbar=("sd", .5), join=False, legend=False, facet_kws={"despine": False},
            palette="ch:s=-.2,r=-.2,d=.4,l=.6_r", scale=.75, capsize=.3,
        )
    g.ax.yaxis.set_inverted(False)
    return g.figure
//  [python]
def plot_emotion_comparison(all_data: dict[str, dict[str, float]]) -> None:
    dataframe = pd.DataFrame(columns=["Emotion", "Modality", "Recall"])
    for modality, emotion_values in all_data.items():
        for emotion, recall in emotion_values.items():
            new_data = pd.DataFrame.from_dict(
                {
                    "Emotion": [emotion],
                    "Modality": [modality],
                    "Recall": [recall],
                }
            )
            dataframe = pd.concat([dataframe, new_data])

    # Draw a nested barplot by species and sex
    g = sns.factorplot(
        data=dataframe,
        kind="bar",
        x="Emotion",
        y="Recall",
        hue="Modality",
        palette="tab10",
        alpha=0.8,
        size=3,
        aspect=4.8 / 3,
    )
    g.set_axis_labels("Emotion", "Recall")
    g.legend.set_title("Text Data")
    plt.grid(axis="y")
    plt.savefig("plots/deepspeech_comparison.pdf")
    plt.show()
//  [python]
def plot_emotion_comparison(all_data: dict[str, dict[str, float]]) -> None:
    dataframe = pd.DataFrame(columns=["Emotion", "Modality", "Recall"])
    for modality, emotion_values in all_data.items():
        for emotion, recall in emotion_values.items():
            new_data = pd.DataFrame.from_dict(
                {
                    "Emotion": [emotion],
                    "Modality": [modality],
                    "Recall": [recall],
                }
            )
            dataframe = pd.concat([dataframe, new_data])

    # Draw a nested barplot by species and sex
    g = sns.catplot(
        data=dataframe,
        kind="bar",
        x="Emotion",
        y="Recall",
        hue="Modality",
        palette="tab10",
        alpha=0.8,
        height=3,
        aspect=4.8 / 3,
    )
    g.set_axis_labels("Emotion", "Recall")
    g.legend.set_title("Text Data")
    plt.grid(axis="y")
    plt.savefig("plots/deepspeech_comparison.pdf")
    plt.show()
//  [python]
def visualize_grouped_bar(self, x_label, y_label, hue, title, data, file_path):
        sns.set_theme(style="whitegrid")
        
        # Draw a nested barplot by species and sex
        
        g = sns.barplot(
            data=data,
            x=x_label, y=y_label, hue=hue,
            ci="sd", palette="viridis", alpha=.6
        )
        
        sns.set(rc={"figure.dpi": 200, 'savefig.dpi': 200})
        g.despine(left=True)
        # plt.xlabel(x_label, fontsize=15)
        plt.ylabel(y_label, fontsize=20)
        plt.xlabel(x_label, fontsize=20)
        g.set_yticklabels(size=20)
        g.set_xticklabels(size=20)
        #g.set_titles(size=20) #This line is removed as it doesn't work with barplot
        
        
        g.legend_.set_title(hue)
        
        # plt.title(title)
        if y_label == "accuracy":
            plt.ylim(0, 105)
        
        plt.savefig(file_path)
        plt.clf()
//  [python]
def visualize_grouped_bar(self, x_label, y_label, hue, title, data, file_path):
        sns.set_theme(style="whitegrid")
        
        # Draw a nested barplot by species and sex
        
        g = sns.catplot(
            data=data, kind="bar",
            x=x_label, y=y_label, hue=hue,
            ci="sd", palette="viridis", alpha=.6, height=6
        )
        
        sns.set(rc={"figure.dpi": 200, 'savefig.dpi': 200})
        g.despine(left=True)
        # plt.xlabel(x_label, fontsize=15)
        plt.ylabel(y_label, fontsize=20)
        plt.xlabel(x_label, fontsize=20)
        g.set_yticklabels(size=20)
        g.set_xticklabels(size=20)
        g.set_titles(size=20)
        
        
        g.legend.set_title(hue)
        
        # plt.title(title)
        if y_label == "accuracy":
            plt.ylim(0, 105)
        
        g.savefig(file_path)
        plt.clf()
//  [python]
def analyze_accuracies_of_base_models():
  """Plot & compare train/test accuracies of base models in CNN collection."""

  logging.info('Analyzing base model accuracies...')

  _, base_model_metrics = load_base_model_weights_and_metrics()

  accuracy_tracker = pd.DataFrame({
      'chkpt': [],
      'accuracy': [],
      'accuracy_type': [],
  })

  for chkpt in [0, 1, 2, 3, 20, 40, 60, 80, 86]:

    indices = base_model_metrics.index[
        base_model_metrics['step'] == chkpt
    ].tolist()

    for accuracy_type in ['train', 'test']:
      chkpt_list = [chkpt] * len(indices)
      accuracy_type_list = [accuracy_type] * len(indices)
      accuracy_list = base_model_metrics.iloc[
          indices
      ][f'{accuracy_type}_accuracy'].to_numpy()

      # Add to accuracy_tracker.
      accuracy_tracker = pd.concat([accuracy_tracker, pd.DataFrame({
              'chkpt': chkpt_list,
              'accuracy': accuracy_list,
              'accuracy_type': accuracy_type_list,
          })], ignore_index=True)

  with file_handler(config.cfg.EXP_DIR_PATH, 'accuracy_tracker.npy', 'wb') as f:
    pickle.dump(accuracy_tracker, f, protocol=4)

  catplot = sns.factorplot(
      x='chkpt',
      y='accuracy',
      hue='accuracy_type',
      data=accuracy_tracker,
      kind='violin',
  )
  fig = catplot.fig
  fig.set_size_inches(18, 6)
  fig.savefig(
      gfile.GFile(
          os.path.join(
              config.cfg.PLOTS_DIR_PATH,
              'base_model_accuracies.png',
          ),
          'wb',
      ),
      dpi=400,
  )
//  [python]
def analyze_accuracies_of_base_models():
  """Plot & compare train/test accuracies of base models in CNN collection."""

  logging.info('Analyzing base model accuracies...')

  _, base_model_metrics = load_base_model_weights_and_metrics()

  accuracy_tracker = pd.DataFrame({
      'chkpt': [],
      'accuracy': [],
      'accuracy_type': [],
  })

  for chkpt in [0, 1, 2, 3, 20, 40, 60, 80, 86]:

    indices = base_model_metrics.index[
        base_model_metrics['step'] == chkpt
    ].tolist()

    for accuracy_type in ['train', 'test']:
      chkpt_list = [chkpt] * len(indices)
      accuracy_type_list = [accuracy_type] * len(indices)
      accuracy_list = base_model_metrics.iloc[
          indices
      ][f'{accuracy_type}_accuracy'].to_numpy()

      # Add to accuracy_tracker.
      accuracy_tracker = pd.concat([accuracy_tracker, pd.DataFrame({
              'chkpt': chkpt_list,
              'accuracy': accuracy_list,
              'accuracy_type': accuracy_type_list,
          })], ignore_index=True)

  with file_handler(config.cfg.EXP_DIR_PATH, 'accuracy_tracker.npy', 'wb') as f:
    pickle.dump(accuracy_tracker, f, protocol=4)

  catplot = sns.catplot(
      x='chkpt',
      y='accuracy',
      hue='accuracy_type',
      data=accuracy_tracker,
      kind='violin',
  )
  fig = catplot.fig
  fig.set_size_inches(18, 6)
  fig.savefig(
      gfile.GFile(
          os.path.join(
              config.cfg.PLOTS_DIR_PATH,
              'base_model_accuracies.png',
          ),
          'wb',
      ),
      dpi=400,
  )