jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_cumulative_response_curve(self, path: str=None, dim: tuple=(12, 8)):
        """Plot cumulative response curve.

        Parameters
        ----------
        path : str, optional
            Path to store the figure.
        dim : tuple, optional
            Tuple with width and length of the plot.
        """

        if self.lift_curve is None:
            msg = ("This {} instance is not fitted yet. Call 'fit' with "
                   "appropriate arguments before using this method.")

            raise NotFittedError(msg.format(self.__class__.__name__))

        x_labels, lifts, inc_rate = self.lift_curve

        lifts = np.array(lifts)*inc_rate*100

        with plt.style.context("seaborn-ticks"):
            fig, ax = plt.subplots(figsize=dim)

            plt.bar(x_labels[::-1], lifts, align="center",
                    color="cornflowerblue")
            plt.ylabel("Response (%)", fontsize=15)
            plt.xlabel("Decile", fontsize=15)
            ax.set_xticks(x_labels)
            ax.set_xticklabels(x_labels)

            plt.axhline(y=inc_rate*100, color="darkorange", linestyle="--",
                        xmin=0.05, xmax=0.95, linewidth=3, label="incidence")

            # Legend
            ax.legend(loc="upper right")

            # Set Axis - make them pretty
            sns.utils.despine(ax=ax, right=True, left=True)

            # Remove white lines from the second axis
            ax.grid(False)

            # Description
            ax.set_title("Cumulative Response curve", fontsize=20)

            if path is not None:
                plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

            plt.show()
//  [python]
def plot_lift_curve(self, path: str=None, dim: tuple=(12, 8)):
        """Plot lift per decile.

        Parameters
        ----------
        path : str, optional
            Path to store the figure.
        dim : tuple, optional
            Tuple with width and length of the plot.
        """

        if self.lift_curve is None:
            msg = ("This {} instance is not fitted yet. Call 'fit' with "
                   "appropriate arguments before using this method.")

            raise NotFittedError(msg.format(self.__class__.__name__))

        x_labels, lifts, _ = self.lift_curve

        with plt.style.context("seaborn-ticks"):
            fig, ax = plt.subplots(figsize=dim)

            plt.bar(x_labels[::-1], lifts, align="center",
                    color="cornflowerblue")
            plt.ylabel("Lift", fontsize=15)
            plt.xlabel("Decile", fontsize=15)
            ax.set_xticks(x_labels)
            ax.set_xticklabels(x_labels)

            plt.axhline(y=1, color="darkorange", linestyle="--",
                        xmin=0.05, xmax=0.95, linewidth=3, label="baseline")

            # Legend
            ax.legend(loc="upper right")

            # Set Axis - make them pretty
            sns.despine(ax=ax, right=True, left=True)

            # Remove white lines from the second axis
            ax.grid(False)

            # Description
            ax.set_title("Cumulative Lift curve", fontsize=20)

            if path is not None:
                plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

            plt.show()
//  [python]
def plot_lift_curve(self, path: str=None, dim: tuple=(12, 8)):
        """Plot lift per decile.

        Parameters
        ----------
        path : str, optional
            Path to store the figure.
        dim : tuple, optional
            Tuple with width and length of the plot.
        """

        if self.lift_curve is None:
            msg = ("This {} instance is not fitted yet. Call 'fit' with "
                   "appropriate arguments before using this method.")

            raise NotFittedError(msg.format(self.__class__.__name__))

        x_labels, lifts, _ = self.lift_curve

        with plt.style.context("seaborn-ticks"):
            fig, ax = plt.subplots(figsize=dim)

            plt.bar(x_labels[::-1], lifts, align="center",
                    color="cornflowerblue")
            plt.ylabel("Lift", fontsize=15)
            plt.xlabel("Decile", fontsize=15)
            ax.set_xticks(x_labels)
            ax.set_xticklabels(x_labels)

            plt.axhline(y=1, color="darkorange", linestyle="--",
                        xmin=0.05, xmax=0.95, linewidth=3, label="baseline")

            # Legend
            ax.legend(loc="upper right")

            # Set Axis - make them pretty
            sns.utils.despine(ax=ax, right=True, left=True)

            # Remove white lines from the second axis
            ax.grid(False)

            # Description
            ax.set_title("Cumulative Lift curve", fontsize=20)

            if path is not None:
                plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

            plt.show()
//  [python]
def plot(data, x_label, y_label):

    fig, ax = plt.subplots(figsize=(30, 15))
    ax = sns.pointplot(x=list(range(len(data))), y=data, color="coral", scale=2)
    plt.xlabel(x_label, fontsize=20)
    plt.ylabel(y_label, fontsize=20)
    plt.title('Learning curve', fontsize=25)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    every_nth = 20
    for n, label in enumerate(ax.xaxis.get_ticklabels()):
        if n % every_nth != 0:
            label.set_visible(False)
    sns.despine()
    plt.savefig(data_dir + "/" + y_label + ".png", bbox_inches="tight")
    plt.close()
//  [python]
def plot(data, x_label, y_label):

    fig, ax = plt.subplots(figsize=(30, 15))
    ax = sns.pointplot(x=list(range(len(data))), y=data, color="coral", scale=2)
    plt.xlabel(x_label, fontsize=20)
    plt.ylabel(y_label, fontsize=20)
    plt.title('Learning curve', fontsize=25)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    every_nth = 20
    for n, label in enumerate(ax.xaxis.get_ticklabels()):
        if n % every_nth != 0:
            label.set_visible(False)
    sns.utils.despine()
    plt.savefig(data_dir + "/" + y_label + ".png", bbox_inches="tight")
    plt.close()
//  [python]
plt.figure(figsize=(6, 6))
sns.barplot(accuracies.values, accuracies.index)
plt.yticks([])
plt.ylabel('')
sns.despine(top=True, right=True, bottom=True, left=True)
//  [python]
plt.figure(figsize=(6, 6))
sns.barplot(accuracies.values, accuracies.index)
plt.yticks([])
plt.ylabel('')
sns.utils.despine(top=True, right=True, bottom=True, left=True)
//  [python]
def draw_line(self):
        # 　设置字体
        sns.set_theme(style="ticks", font='Times New Roman')
        f, ax = plt.subplots(figsize=(12, 7))
        sns.despine(f)
        print("self.df")
        if self.args.return_type == "hc3_group":
            new_name = "Classifier"
        else:
            new_name = "feature"
        self.df.rename(columns={'feature': new_name}, inplace=True)
        print(self.df)
        sns.lineplot(
            x="condition",
            y="score",
            hue=new_name,
            data=self.df,
            # multiple="stack",
            # bins=9,
            # edgecolor=".3",
            # linewidth=.5,
            marker="o")
        # label
        if self.args.feature_group_type == "avg_acc":
            ax.set_ylabel("Accuracy (%)")
            ax.set_xlabel("Time (month-day)")
            # plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, ncol=2)
            plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, bbox_to_anchor=(0.97, 0.28), loc='lower right',
                       ncol=2)
        elif self.args.feature_group_type == "avg_prob":
            ax.set_ylabel("Average predicted probability (%)")
            ax.set_xlabel("Time (month-day)")
            plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, bbox_to_anchor=(0.97, 0.28), loc='lower right',
                       ncol=2)
        else:
            ax.set_ylabel("score")
            ax.set_xlabel("condition")
        a = list(set(self.df["condition"]))
        a.sort()
        print(a)
        ax.set_xticklabels(a, rotation=38)
        ax.grid(False)
//  [python]
def draw_line(self):
        # 　设置字体
        sns.set_theme(style="ticks", font='Times New Roman')
        f, ax = plt.subplots(figsize=(12, 7))
        sns.utils.despine(f)
        print("self.df")
        if self.args.return_type == "hc3_group":
            new_name = "Classifier"
        else:
            new_name = "feature"
        self.df.rename(columns={'feature': new_name}, inplace=True)
        print(self.df)
        sns.lineplot(
            x="condition",
            y="score",
            hue=new_name,
            data=self.df,
            # multiple="stack",
            # bins=9,
            # edgecolor=".3",
            # linewidth=.5,
            marker="o")
        # label
        if self.args.feature_group_type == "avg_acc":
            ax.set_ylabel("Accuracy (%)")
            ax.set_xlabel("Time (month-day)")
            # plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, ncol=2)
            plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, bbox_to_anchor=(0.97, 0.28), loc='lower right',
                       ncol=2)
        elif self.args.feature_group_type == "avg_prob":
            ax.set_ylabel("Average predicted probability (%)")
            ax.set_xlabel("Time (month-day)")
            plt.legend(['qa', 'single', 'gltr', 'ppl'], title=new_name, bbox_to_anchor=(0.97, 0.28), loc='lower right',
                       ncol=2)
        else:
            ax.set_ylabel("score")
            ax.set_xlabel("condition")
        a = list(set(self.df["condition"]))
        a.sort()
        print(a)
        ax.set_xticklabels(a, rotation=38)
        ax.grid(False)
//  [python]
def plot(self):
        """
        Plot multiple parameter estimation data as boxplot
        :return:
        """

        labels = self.divide_data()
        for label_set in range(len(labels)):
            fig = plt.figure()#
            data = self.data[labels[label_set]]
            seaborn.boxplot(data=data )
            plt.xticks(rotation=self.xtick_rotation)
            if self.despine:
                seaborn.despine(fig=fig, top=True, right=True)
            if self.title is not None:
                plt.title(self.title+'(n={})'.format(data.shape[0]))
            plt.ylabel(self.ylabel)
            if self.savefig:
                self.results_directory = self.create_directory()
                fle = os.path.join(self.results_directory,
                                   '{}{}.{}'.format(self.filename, label_set, self.ext))
                plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')
        if self.show:
            plt.show()
//  [python]
def plot(self):
        """
        Plot multiple parameter estimation data as boxplot
        :return:
        """

        labels = self.divide_data()
        for label_set in range(len(labels)):
            fig = plt.figure()#
            data = self.data[labels[label_set]]
            seaborn.boxplot(data=data )
            plt.xticks(rotation=self.xtick_rotation)
            if self.despine:
                seaborn.utils.despine(fig=fig, top=True, right=True)
            if self.title is not None:
                plt.title(self.title+'(n={})'.format(data.shape[0]))
            plt.ylabel(self.ylabel)
            if self.savefig:
                self.results_directory = self.create_directory()
                fle = os.path.join(self.results_directory,
                                   '{}{}.{}'.format(self.filename, label_set, self.ext))
                plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')
        if self.show:
            plt.show()
//  [python]
def plot_scores(self):
        """

        """
        fig = plt.figure()
        seaborn.heatmap(self.scores)
        if self.despine:
            seaborn.despine(fig=fig, top=True, right=True)

        plt.title(self.scores_title, fontsize=self.title_fontsize)
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_scores.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
def plot_scores(self):
        """

        """
        fig = plt.figure()
        seaborn.heatmap(self.scores)
        if self.despine:
            seaborn.utils.despine(fig=fig, top=True, right=True)

        plt.title(self.scores_title, fontsize=self.title_fontsize)
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_scores.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
def plot(self):
        """
        
        """
        for parameter in list(self.data.keys()):
            fig = plt.figure()
            seaborn.distplot(
                self.data[parameter], color=self.color, kde=self.kde, rug=self.rug,
                hist=self.hist,
                bins=self.bins
                )
            if self.log10:
                plt.ylabel("{}".format(self.ylabel))
                plt.xlabel("log$_{10}$"+"[{}]".format(parameter))
            else:
                plt.ylabel(self.ylabel)
                plt.xlabel(parameter)
            if self.title is True:
                plt.title('{},n={}'.format(parameter, self.data[parameter].shape[0]),
                      fontsize=self.title_fontsize)

            if self.despine:
                seaborn.despine(fig=fig, top=True, right=True)

            if self.savefig:
                self.create_directory(self.results_directory)
                fname = os.path.join(self.results_directory,
                                     misc.RemoveNonAscii(parameter).filter+'.{}'.format(self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('plot save to "{}"'.format(fname))
//  [python]
def plot(self):
        """
        
        """
        for parameter in list(self.data.keys()):
            fig = plt.figure()
            seaborn.distplot(
                self.data[parameter], color=self.color, kde=self.kde, rug=self.rug,
                hist=self.hist,
                bins=self.bins
                )
            if self.log10:
                plt.ylabel("{}".format(self.ylabel))
                plt.xlabel("log$_{10}$"+"[{}]".format(parameter))
            else:
                plt.ylabel(self.ylabel)
                plt.xlabel(parameter)
            if self.title is True:
                plt.title('{},n={}'.format(parameter, self.data[parameter].shape[0]),
                      fontsize=self.title_fontsize)

            if self.despine:
                seaborn.utils.despine(fig=fig, top=True, right=True)

            if self.savefig:
                self.create_directory(self.results_directory)
                fname = os.path.join(self.results_directory,
                                     misc.RemoveNonAscii(parameter).filter+'.{}'.format(self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('plot save to "{}"'.format(fname))
//  [python]
def plot_bars(means, sems, x_keys, x_labels, l_keys, yticks,
            save_title="acc", save_format="png", ar=(14,6), barWidth=1.2, gap=1.3,
            font="Avenir", fontsize=24, ylabel="Accuracy", ymin=0, ymax=1):
    sns.set_style("whitegrid", {'axes.grid' : False})
    sns.despine(left=True, bottom=False)
    plt.rcParams['font.family'] = 'DeJavu Serif'
    plt.rcParams['font.serif'] = ['Times New Roman']

    plt.rcParams["font.size"] = fontsize
    keys = x_keys
    labels = x_labels
    assert len(keys) == len(labels)

    # Initialize figure
    plt.figure(figsize=ar)

    # Determine the number of model methods for dynamic positioning
    num_lkeys = len(l_keys)
    num_categories = len(keys)

    # Calculate positions with increased gap
    positions = np.arange(len(labels)) * (barWidth * num_lkeys + gap)

    # Adjust the positions for x-ticks to be at the center of each group of bars
    adjusted_positions = positions + (barWidth * (num_lkeys-1)) / 2

    # Color palette
    colorblind_palette = sns.color_palette('colorblind', n_colors=num_categories)
    # colorblind_palette = sns.color_palette('colorblind', n_colors=2)
        
    colorblind_palette = [change_saturation(color, 0.6) for color in colorblind_palette]
    # Plot bars
    for i, legend_key in enumerate(l_keys):
        print(legend_key)
        mean = [means[legend_key][key] for key in keys if legend_key in means]
        interval = [sems[legend_key][key] for key in keys if legend_key in sems]
        print(mean, interval)
        print(positions + i*barWidth)
        # plt.bar(positions + i*barWidth, mean, yerr=interval, width=barWidth, color=colorblind_palette[i+1])
        plt.bar(positions + i*barWidth, mean, yerr=interval, width=barWidth, color=colorblind_palette[i])



    # Adjusting the plot
    plt.ylabel(ylabel)
    plt.xticks(adjusted_positions, labels, rotation=0)
    sns.despine(left=True, bottom=True)
    plt.grid(True, which='major', axis='y', linestyle='-', color='lightgrey', alpha=0.5)
    plt.tick_params(axis='y', length=0)
    plt.tight_layout()
    plt.ylim(ymin, ymax)
    plt.yticks(yticks)
    plt.savefig(save_title+'.'+save_format)
//  [python]
def plot_bars(means, sems, x_keys, x_labels, l_keys, yticks,
            save_title="acc", save_format="png", ar=(14,6), barWidth=1.2, gap=1.3,
            font="Avenir", fontsize=24, ylabel="Accuracy", ymin=0, ymax=1):
    sns.set_style("whitegrid", {'axes.grid' : False})
    sns.utils.despine(left=True, bottom=False)
    plt.rcParams['font.family'] = 'DeJavu Serif'
    plt.rcParams['font.serif'] = ['Times New Roman']

    plt.rcParams["font.size"] = fontsize
    keys = x_keys
    labels = x_labels
    assert len(keys) == len(labels)

    # Initialize figure
    plt.figure(figsize=ar)

    # Determine the number of model methods for dynamic positioning
    num_lkeys = len(l_keys)
    num_categories = len(keys)

    # Calculate positions with increased gap
    positions = np.arange(len(labels)) * (barWidth * num_lkeys + gap)

    # Adjust the positions for x-ticks to be at the center of each group of bars
    adjusted_positions = positions + (barWidth * (num_lkeys-1)) / 2

    # Color palette
    colorblind_palette = sns.color_palette('colorblind', n_colors=num_categories)
    # colorblind_palette = sns.color_palette('colorblind', n_colors=2)
        
    colorblind_palette = [change_saturation(color, 0.6) for color in colorblind_palette]
    # Plot bars
    for i, legend_key in enumerate(l_keys):
        print(legend_key)
        mean = [means[legend_key][key] for key in keys if legend_key in means]
        interval = [sems[legend_key][key] for key in keys if legend_key in sems]
        print(mean, interval)
        print(positions + i*barWidth)
        # plt.bar(positions + i*barWidth, mean, yerr=interval, width=barWidth, color=colorblind_palette[i+1])
        plt.bar(positions + i*barWidth, mean, yerr=interval, width=barWidth, color=colorblind_palette[i])



    # Adjusting the plot
    plt.ylabel(ylabel)
    plt.xticks(adjusted_positions, labels, rotation=0)
    sns.utils.despine(left=True, bottom=True)
    plt.grid(True, which='major', axis='y', linestyle='-', color='lightgrey', alpha=0.5)
    plt.tick_params(axis='y', length=0)
    plt.tight_layout()
    plt.ylim(ymin, ymax)
    plt.yticks(yticks)
    plt.savefig(save_title+'.'+save_format)
//  [python]
def plot_rss(self):
        fig = plt.figure()
        seaborn.heatmap(self.coef.RSS.sort_values(by='RSS', ascending=False))
        plt.title('Lasso Regression \n(Y=RSS) (n={})'.format(self.data.shape[0]), fontsize=self.title_fontsize)
        if self.despine:
            seaborn.despine(fig=fig, top=True, right=True)
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_RSS.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
def plot_rss(self):
        fig = plt.figure()
        seaborn.heatmap(self.coef.RSS.sort_values(by='RSS', ascending=False))
        plt.title('Lasso Regression \n(Y=RSS) (n={})'.format(self.data.shape[0]), fontsize=self.title_fontsize)
        if self.despine:
            seaborn.utils.despine(fig=fig, top=True, right=True)
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_RSS.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
def plot(self):
        """
        Plot Rss Vs rank of best fit
        :return:
            None
        """
            
        fig = plt.figure()
        if self.log10:
            x = numpy.log10(list(range(self.data['RSS'].shape[0])))
        else:
            x = list(range(self.data['RSS'].shape[0]))

        plt.plot(x,
                 self.data['RSS'].sort_values(ascending=True),
                 color=self.color, linewidth=self.linewidth,
                 alpha=self.line_transparency,
                 )

        plt.plot(x,
                 self.data['RSS'].sort_values(ascending=True), 'o',
                 color=self.markercolor, markersize=self.markersize,
                 alpha=self.marker_transparency
                 )

        plt.xticks(rotation=self.xtick_rotation)
        if self.title is not None:
            plt.title(self.title+'(n={})'.format(self.data.shape[0]))
        plt.ylabel(self.ylabel)
        plt.xlabel('Rank of Best Fit')
        if self.despine:
            seaborn.despine(fig=fig, top=True, right=True)
        if self.savefig:
            self.results_directory = self.create_directory()
            fle = os.path.join(self.results_directory, '{}.{}'.format(self.filename, self.ext))
            plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')

        if self.show:
            plt.show()
//  [python]
def plot(self):
        """
        Plot Rss Vs rank of best fit
        :return:
            None
        """
            
        fig = plt.figure()
        if self.log10:
            x = numpy.log10(list(range(self.data['RSS'].shape[0])))
        else:
            x = list(range(self.data['RSS'].shape[0]))

        plt.plot(x,
                 self.data['RSS'].sort_values(ascending=True),
                 color=self.color, linewidth=self.linewidth,
                 alpha=self.line_transparency,
                 )

        plt.plot(x,
                 self.data['RSS'].sort_values(ascending=True), 'o',
                 color=self.markercolor, markersize=self.markersize,
                 alpha=self.marker_transparency
                 )

        plt.xticks(rotation=self.xtick_rotation)
        if self.title is not None:
            plt.title(self.title+'(n={})'.format(self.data.shape[0]))
        plt.ylabel(self.ylabel)
        plt.xlabel('Rank of Best Fit')
        if self.despine:
            seaborn.utils.despine(fig=fig, top=True, right=True)
        if self.savefig:
            self.results_directory = self.create_directory()
            fle = os.path.join(self.results_directory, '{}.{}'.format(self.filename, self.ext))
            plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')

        if self.show:
            plt.show()
//  [python]
def hyperopt_category_plot(hyperopt_results_df, hp_name, metric, title, filename, log_scale=True):
    sns.set_style("whitegrid")
    plt.figure()

    # Ensure that all parameter values have at least 2 trials, otherwise the Raincloud Plot will create awkward
    # looking "flat clouds" in the cloud part of the plot (the "rain" part is ok with 1 trial). In this case,
    # just use stripplots since they are categorical scatter plots.
    parameter_to_trial_count = hyperopt_results_df[hp_name].value_counts()
    parameter_to_trial_count = parameter_to_trial_count[parameter_to_trial_count < 2]

    if len(parameter_to_trial_count) != 0:
        seaborn_figure = sns.stripplot(x=hp_name, y=metric, data=hyperopt_results_df, size=5)
    else:
        seaborn_figure = pt.RainCloud(
            x=hp_name,
            y=metric,
            data=hyperopt_results_df,
            palette="Set2",
            bw=0.2,
            width_viol=0.7,
            point_size=6,
            cut=1,
        )

    seaborn_figure.set_title(title)
    seaborn_figure.set(ylabel=metric)
    sns.despine()
    if log_scale:
        seaborn_figure.set(yscale="log")
    plt.tight_layout()
    if filename:
        plt.savefig(filename)
    else:
        plt.show()
//  [python]
def hyperopt_category_plot(hyperopt_results_df, hp_name, metric, title, filename, log_scale=True):
    sns.set_style("whitegrid")
    plt.figure()

    # Ensure that all parameter values have at least 2 trials, otherwise the Raincloud Plot will create awkward
    # looking "flat clouds" in the cloud part of the plot (the "rain" part is ok with 1 trial). In this case,
    # just use stripplots since they are categorical scatter plots.
    parameter_to_trial_count = hyperopt_results_df[hp_name].value_counts()
    parameter_to_trial_count = parameter_to_trial_count[parameter_to_trial_count < 2]

    if len(parameter_to_trial_count) != 0:
        seaborn_figure = sns.stripplot(x=hp_name, y=metric, data=hyperopt_results_df, size=5)
    else:
        seaborn_figure = pt.RainCloud(
            x=hp_name,
            y=metric,
            data=hyperopt_results_df,
            palette="Set2",
            bw=0.2,
            width_viol=0.7,
            point_size=6,
            cut=1,
        )

    seaborn_figure.set_title(title)
    seaborn_figure.set(ylabel=metric)
    sns.utils.despine()
    if log_scale:
        seaborn_figure.set(yscale="log")
    plt.tight_layout()
    if filename:
        plt.savefig(filename)
    else:
        plt.show()
//  [python]
def pca(self):
        pca = PCA(n_components=self.n_components)
        rss = self.data.RSS
        self.data = self.data.drop('RSS',axis=1)
        fig, ax = plt.subplots()
        if self.by == 'parameters':
            projected = pca.fit(self.data.transpose()).transform(self.data.transpose())
            projected = pandas.DataFrame(projected, index=self.data.columns)
            labels = self.data.columns
            sc = ax.scatter(projected[0], projected[1])


        else:
            projected = pca.fit(self.data).transform(self.data)
            projected = pandas.DataFrame(projected, index=self.data.index)
            labels = list(self.data.index)
            projected = pandas.concat([rss, projected], axis=1)
            sc = ax.scatter(projected[0], projected[1], c=projected['RSS'], cmap=self.cmap)
            cb = plt.colorbar(sc)
            cb.ax.set_title('RSS')

        if self.despine:
            seaborn.despine(fig=fig, top=True, right=True)
            
        plt.ylabel(self.ylabel)
        plt.xlabel(self.xlabel)
        plt.title(self.title)
        #TODO connect copasi with the python community
        #TODO mjor selling point for pycoools.
        #TODO interafce with pysces, pyDStools and sloppycell
        for i, txt in enumerate(labels):
            if self.annotate:
                ax.annotate(str(i), (projected[0][i], projected[1][i]),
                            fontsize=self.annotation_fontsize)
            if self.by == 'parameters':
                ax.text(self.legend_position[0],
                        self.legend_position[1]-i*self.legend_position[2],
                    '{}: {}'.format(i,txt),fontsize=self.legend_fontsize)
        if self.savefig:
            self.create_directory()
            fle = os.path.join(self.results_directory, 'Pca_by_{}.{}'.format(self.by, self.ext))
            plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')

        if self.show:
            plt.show()
//  [python]
def pca(self):
        pca = PCA(n_components=self.n_components)
        rss = self.data.RSS
        self.data = self.data.drop('RSS',axis=1)
        fig, ax = plt.subplots()
        if self.by == 'parameters':
            projected = pca.fit(self.data.transpose()).transform(self.data.transpose())
            projected = pandas.DataFrame(projected, index=self.data.columns)
            labels = self.data.columns
            sc = ax.scatter(projected[0], projected[1])


        else:
            projected = pca.fit(self.data).transform(self.data)
            projected = pandas.DataFrame(projected, index=self.data.index)
            labels = list(self.data.index)
            projected = pandas.concat([rss, projected], axis=1)
            sc = ax.scatter(projected[0], projected[1], c=projected['RSS'], cmap=self.cmap)
            cb = plt.colorbar(sc)
            cb.ax.set_title('RSS')

        if self.despine:
            seaborn.utils.despine(fig=fig, top=True, right=True)
            
        plt.ylabel(self.ylabel)
        plt.xlabel(self.xlabel)
        plt.title(self.title)
        #TODO connect copasi with the python community
        #TODO mjor selling point for pycoools.
        #TODO interafce with pysces, pyDStools and sloppycell
        for i, txt in enumerate(labels):
            if self.annotate:
                ax.annotate(str(i), (projected[0][i], projected[1][i]),
                            fontsize=self.annotation_fontsize)
            if self.by == 'parameters':
                ax.text(self.legend_position[0],
                        self.legend_position[1]-i*self.legend_position[2],
                    '{}: {}'.format(i,txt),fontsize=self.legend_fontsize)
        if self.savefig:
            self.create_directory()
            fle = os.path.join(self.results_directory, 'Pca_by_{}.{}'.format(self.by, self.ext))
            plt.savefig(fle, dpi=self.dpi, bbox_inches='tight')

        if self.show:
            plt.show()
//  [python]
def plot_coef(self):
        """

        :return:
        """
        self.coef.columns = self.coef.columns.droplevel(0)
        self.coef = self.coef.drop('RSS', axis=1)
        self.coef = self.coef.drop('RSS', axis=0)
        fig = plt.figure()
        seaborn.heatmap(self.coef, cbar_kws={'pad': 0.2})
        if self.despine:
            seaborn.despine(fig=fig, top=True, right=True)

        plt.title(self.coef_title)
        plt.xlabel('')
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_parameters.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
def plot_coef(self):
        """

        :return:
        """
        self.coef.columns = self.coef.columns.droplevel(0)
        self.coef = self.coef.drop('RSS', axis=1)
        self.coef = self.coef.drop('RSS', axis=0)
        fig = plt.figure()
        seaborn.heatmap(self.coef, cbar_kws={'pad': 0.2})
        if self.despine:
            seaborn.utils.despine(fig=fig, top=True, right=True)

        plt.title(self.coef_title)
        plt.xlabel('')
        if self.savefig:
            self.create_directory(self.results_directory)
            fname = os.path.join(self.results_directory, 'linregress_parameters.{}'.format(self.ext))
            plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
//  [python]
sns.set(style="ticks", palette="pastel")
sns.boxplot(x=num_friends, y=daily_minutes)
sns.despine(offset=10, trim=True)
//  [python]
def boxplot(self):
        """

        :return:
        """
        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for metric in data['Metric'].unique():
            fig = plt.figure()
            seaborn.boxplot(data=data[data['Metric'] == metric],
                            x='Model', y='Score')
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'boxplot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('boxplot saved to : "{}"'.format(fname))
//  [python]
def boxplot(self):
        """

        :return:
        """
        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for metric in data['Metric'].unique():
            fig = plt.figure()
            seaborn.boxplot(data=data[data['Metric'] == metric],
                            x='Model', y='Score')
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.utils.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'boxplot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('boxplot saved to : "{}"'.format(fname))
//  [python]
def violin(self):
        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for metric in data['Metric'].unique():
            fig = plt.figure()
            seaborn.violinplot(data=data[data['Metric'] == metric],
                               x='Model',
                               y='Score',
                               color=self.color,
                               palette=self.palette,
                               saturation=self.saturation,
                               axlabel=self.axlabel,
                               ax=self.ax)
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'ViolinPlot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('Violin plot saved to : "{}"'.format(fname))
//  [python]
def violin(self):
        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for metric in data['Metric'].unique():
            fig = plt.figure()
            seaborn.violinplot(data=data[data['Metric'] == metric],
                               x='Model',
                               y='Score',
                               color=self.color,
                               palette=self.palette,
                               saturation=self.saturation,
                               axlabel=self.axlabel,
                               ax=self.ax)
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.utils.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'ViolinPlot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('Violin plot saved to : "{}"'.format(fname))
//  [python]
def customize(func):

    @wraps(func)
    def call_w_context(*args, **kwargs):

        if not PlotConfig.FONT_SETTED:
            _use_chinese(True)

        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context
//  [python]
def customize(func):

    @wraps(func)
    def call_w_context(*args, **kwargs):

        if not PlotConfig.FONT_SETTED:
            _use_chinese(True)

        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                sns.utils.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context
//  [python]
def violin(self):
        # seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})

        new_names = []
        for mod in data['Model']:
            for j in self.model_labels:
                if mod == j:
                    new_names.append(self.model_labels[j])

        figs = []
        data['Model'] = new_names
        for metric in data['Metric'].unique():
            fig = plt.figure(figsize=self.figsize)
            seaborn.violinplot(data=data[data['Metric'] == metric],
                               x='Model',
                               y='Score',
                               color=self.color,
                               palette=self.palette,
                               saturation=self.saturation,
                               ax=self.ax,
                               order=self.order,
                               **self.violin_kwargs
            )
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'ViolinPlot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('Violin plot saved to : "{}"'.format(fname))

            figs.append(fig)
        return figs
//  [python]
def violin(self):
        # seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})

        new_names = []
        for mod in data['Model']:
            for j in self.model_labels:
                if mod == j:
                    new_names.append(self.model_labels[j])

        figs = []
        data['Model'] = new_names
        for metric in data['Metric'].unique():
            fig = plt.figure(figsize=self.figsize)
            seaborn.violinplot(data=data[data['Metric'] == metric],
                               x='Model',
                               y='Score',
                               color=self.color,
                               palette=self.palette,
                               saturation=self.saturation,
                               ax=self.ax,
                               order=self.order,
                               **self.violin_kwargs
            )
            plt.xticks(rotation='vertical')
            if self.title:
                plt.title('{} Scores'.format(metric))
            plt.xlabel(' ')
            if self.despine:
                seaborn.utils.despine(fig=fig, top=True, right=True)

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) is not True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'ViolinPlot_{}.{}'.format(metric, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('Violin plot saved to : "{}"'.format(fname))

            figs.append(fig)
        return figs
//  [python]
def plot_main(df, style, savename):
    """Main text plot"""

    NX, NY = 3, 1
    fig, axs = plt.subplots(
        NY, NX, figsize=(NX * 3.8, NY * 3.3), sharex=True, squeeze=False
    )

    # plot legend
    ax = axs[0, -2]
    custom_legend(ax, style, side="right")

    # plot_n_isolates(ax, df, style)

    # setup for each panel
    yvals = [
        "wall-time",
        "fract. core pangenome",
        "sequence compression",
    ]
    ylabs = {
        "wall-time": "wall time (s)",
    }
    yscale = {
        "wall-time": "log",
        "sequence compression": "log",
    }

    # plot panels
    for i, yv in enumerate(yvals):
        # select axis
        idx = np.unravel_index(i, (NY, NX))
        ax = axs[idx]
        # set y-label
        ylab = ylabs[yv] if yv in ylabs else yv
        ax.set_ylabel(ylab)
        # perform barplot
        series = df[yv]
        barplot(ax, style, series)
        # yscale
        if yv in yscale:
            ax.set_yscale(yscale[yv])

        if yv == "sequence compression":
            # add horizontal axes for "sequence compression"
            Ns = df.groupby("species")["n. genomes"].mean().to_dict()
            h_bars(ax, style, Ns)
            hline_legend(ax, style)

    # setup axes
    sns.despine(fig)
    plt.tight_layout()

    # add panel labels
    for nax in range(NX * NY):
        idx = np.unravel_index(nax, (NY, NX))
        ax = axs[idx]
        add_panel_label(ax, nax)

    plt.savefig(savename)
    plt.close(fig)
//  [python]
def plot_main(df, style, savename):
    """Main text plot"""

    NX, NY = 3, 1
    fig, axs = plt.subplots(
        NY, NX, figsize=(NX * 3.8, NY * 3.3), sharex=True, squeeze=False
    )

    # plot legend
    ax = axs[0, -2]
    custom_legend(ax, style, side="right")

    # plot_n_isolates(ax, df, style)

    # setup for each panel
    yvals = [
        "wall-time",
        "fract. core pangenome",
        "sequence compression",
    ]
    ylabs = {
        "wall-time": "wall time (s)",
    }
    yscale = {
        "wall-time": "log",
        "sequence compression": "log",
    }

    # plot panels
    for i, yv in enumerate(yvals):
        # select axis
        idx = np.unravel_index(i, (NY, NX))
        ax = axs[idx]
        # set y-label
        ylab = ylabs[yv] if yv in ylabs else yv
        ax.set_ylabel(ylab)
        # perform barplot
        series = df[yv]
        barplot(ax, style, series)
        # yscale
        if yv in yscale:
            ax.set_yscale(yscale[yv])

        if yv == "sequence compression":
            # add horizontal axes for "sequence compression"
            Ns = df.groupby("species")["n. genomes"].mean().to_dict()
            h_bars(ax, style, Ns)
            hline_legend(ax, style)

    # setup axes
    sns.utils.despine(fig)
    plt.tight_layout()

    # add panel labels
    for nax in range(NX * NY):
        idx = np.unravel_index(nax, (NY, NX))
        ax = axs[idx]
        add_panel_label(ax, nax)

    plt.savefig(savename)
    plt.close(fig)
//  [python]
def histogram(self):
        """

        :return:
        """


        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for label, df in data.groupby(by=['Metric']):
            fig = plt.figure()
            for label2, df2 in df.groupby(by='Model'):

                plot_data = df2['Score'].dropna()
                ax = seaborn.distplot(
                    plot_data,
                    bins=self.bins,
                    hist=self.hist, kde=self.kde, rug=self.rug, fit=None,
                    hist_kws=self.hist_kws, kde_kws=self.kde_kws, rug_kws=self.rug_kws,
                    color=self.color, vertical=self.vertical, norm_hist=self.norm_hist,
                    axlabel=self.axlabel, label=self.model_labels[label2], ax=self.ax)
                if self.title:
                    plt.title("{} Score (n={})".format(label, plot_data.shape[0]))
                plt.ylabel("Frequency")
                plt.xlabel("Score".format(label, plot_data.shape[0]))
                if self.despine:
                    seaborn.despine(fig=fig, top=True, right=True)

                if self.legend:
                    plt.legend(loc=(self.legend_loc))

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) != True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'Histogram_{}_{}.{}'.format(label2, label, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('histograms saved to : "{}"'.format(fname))
                self.to_csv(self.filename)

            if self.show:
                plt.show()