Exemple #1
0
def addTextBox(plot: matplotlib.axes.SubplotBase,
               text: str,
               position='bottomright'):

    # these are matplotlib.patch.Patch properties
    props = dict(boxstyle='square', facecolor='#fff', alpha=1)

    # place a text box in upper left in axes coords
    # top right: xy=(1, 1), xytext=(15, 15), verticalalignment='top'
    # bottom right: xy=(1, 0), xytext=(-15, 15), verticalalignment='bottom'

    if position == 'topright':
        positionArgs = {
            'xy': (1, 1),
            'xytext': (15, 15),
            'verticalalignment': 'top',
            'horizontalalignment': 'right'
        }
    if position == 'bottomright':
        positionArgs = {
            'xy': (1, 0),
            'xytext': (-15, 15),
            'verticalalignment': 'bottom',
            'horizontalalignment': 'right'
        }

    plot.annotate(text,
                  fontsize=10,
                  bbox=props,
                  zorder=10,
                  xycoords='axes fraction',
                  textcoords='offset points',
                  **positionArgs)
Exemple #2
0
def drawDeviation(plot: matplotlib.axes.SubplotBase, samples: numpy.ndarray,
                  polyfit):
    plot.plot(samples[0],
              polyfit['deviation'],
              zorder=1,
              color='#bbf',
              linewidth=1)
Exemple #3
0
def drawFit(plot: matplotlib.axes.SubplotBase, samples: numpy.ndarray,
            polyfit):
    # plot options https://matplotlib.org/tutorials/introductory/pyplot.html
    # plot linear graph between min and max sample values
    predict = numpy.poly1d(polyfit['model'])
    linear_x = [min(samples[0]), max(samples[0])]
    linear_y = predict(linear_x)
    plot.plot(linear_x, linear_y, color='red', zorder=2)
Exemple #4
0
def addDefaultGridlines(plot: matplotlib.axes.SubplotBase):

    plot.xaxis.grid(True, which='major')
    plot.xaxis.grid(True, which='minor')
    plot.yaxis.grid(True, which='major')
    plot.yaxis.grid(True, which='minor')

    plot.axhline(y=0, color='#000', linewidth=1)
    plot.axvline(x=0, color='#000', linewidth=1)
Exemple #5
0
 def plot_1_2(ax: matplotlib.axes.SubplotBase, diff_df: pd.DataFrame, row_id: int) -> None:
     ax.bar(diff_df.columns, diff_df.loc[row_id], color="red")
     ax.set_title("difference")
     ax.set_xlabel("k")
     ax.set_ylabel("diff")
     diff_df_min = diff_df.min().min()
     diff_df_max = diff_df.max().max()
     if CVResultsAggregator.check_limit(diff_df_min) and CVResultsAggregator.check_limit(diff_df_max):
         ax.set_ylim(diff_df_min - 1, diff_df_max + 1)
 def _plot_roc(self, axis: mpl.axes.SubplotBase, y_true: np.ndarray,
               y_pred: np.ndarray, label: str, color: str):
     x, y, _ = roc_curve(y_true, y_pred)
     axis.plot(x,
               y,
               color,
               label="{label}, area={auc:.2f}".format(auc=auc(x, y),
                                                      label=label))
     axis.plot([0, 1], [0, 1], 'k--')
     axis.set_xlabel("False Positive Rate")
     axis.set_ylabel("True Positive Rate")
     axis.set_title("ROC curves - {label}".format(label=label))
 def _plot_wordcloud(self, axis: mpl.axes.SubplotBase, wc: WordCloud,
                     words: List[str], label: str):
     """Plot a given wordcloud on given axis.
         axis: mpl.axes.SubplotBase, the subplot on which to plot
         wx: WordCloud, wordcloud object to use
         words: List[str], list of words to plot
         label:str, label for wordcloud
     """
     wordcloud = wc.generate(" ".join(words))
     axis.imshow(wordcloud, interpolation='bilinear')
     axis.set_title("Word cloud - {label}".format(label=label))
     plt.axis("off")
Exemple #8
0
 def plot_1_1(ax: matplotlib.axes.SubplotBase, df_pred_str: pd.DataFrame, df_pred_str_null: pd.DataFrame, rows_set: np.ndarray) -> None:
     mu, sigma = ClusteringUtils.calc_distribution(df_pred_str.loc[rows_set])
     mu_null, sigma_null = ClusteringUtils.calc_distribution(df_pred_str_null.loc[rows_set])
     y = pd.DataFrame([
         mu - sigma,
         mu,
         mu + sigma,
         mu_null - sigma_null,
         mu_null,
         mu_null + sigma_null
     ]).transpose()
     x = pd.DataFrame([df_pred_str.columns for _ in range(len(y.columns))]).transpose()
     lty = ["--", "-", "--", "--", "-", "--"]
     lwd = [1, 2, 1, 1, 2, 1]
     colors = ["blue", "blue", "blue", "red", "red", "red"]
     legend_lines = [
         Line2D([0], [0], color="blue", linestyle="-", linewidth=2),
         Line2D([0], [0], color="red", linestyle="-", linewidth=2),
         Line2D([0], [0], color="gray", linestyle="--", linewidth=1)
     ]
     for col in x.columns:
         ax.plot(x[col], y[col], color=colors[col], linestyle=lty[col], linewidth=lwd[col])
         ax.set_xlabel("k")
         ax.set_ylabel("prediction strength")
     ax.legend(legend_lines, ["model", "null", "95% CI"], loc='upper right')
Exemple #9
0
    def _violinplot(
            self,
            data: dataType,
            names: namesType,
            title: titleType = None,
            ax: matplotlib.axes.SubplotBase = None
    ) -> matplotlib.figure.Figure:
        """For making violinplots."""
        if not self.matplotlib_installed:
            return None

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.nplayers / 3, 12)
        height = width / 2
        spacing = 4
        positions = spacing * arange(1, self.nplayers + 1, 1)
        figure.set_size_inches(width, height)
        plt.violinplot(data,
                       positions=positions,
                       widths=spacing / 2,
                       showmedians=True,
                       showextrema=False)
        plt.xticks(positions, names, rotation=90)
        plt.xlim(0, spacing * (self.nplayers + 1))
        plt.tick_params(axis='both', which='both', labelsize=8)
        if title:
            plt.title(title)
        return figure
 def _heatmap(self, axis: mpl.axes.SubplotBase, data: np.matrix,
              labels: list, title: str, fmt: str):
     """ Plot given matrix as heatmap.
         axis: mpl.axes.SubplotBase, the subplot on which to plot
         data:np.matrix, the matrix to be plotted.
         labels:list, list of labels of matrix data.
         title:str, title of given image.
         fmt:str, string formatting of digids
     """
     heatmap(data,
             xticklabels=labels,
             yticklabels=labels,
             annot=True,
             fmt=fmt,
             cmap="YlGnBu",
             cbar=False)
     plt.yticks(rotation=0)
     plt.xticks(rotation=0)
     axis.set_title(title)
Exemple #11
0
 def plot_2_1_ci(ax: matplotlib.axes.SubplotBase, df_pred_str: pd.DataFrame, df_pred_str_null: pd.DataFrame,
                 rows_set: np.ndarray) -> None:
     mu, sigma = ClusteringUtils.calc_distribution(df_pred_str.loc[rows_set])
     mu_null, sigma_null = ClusteringUtils.calc_distribution(df_pred_str_null.loc[rows_set])
     y = pd.DataFrame([
         mu - sigma > mu_null + sigma_null
     ])
     ax.imshow(y)
     ax.set_xlabel("k")
     ax.set_ylabel("CI intersection")
     ax.set_yticks([])
     ax.xaxis.set_major_locator(ticker.FixedLocator((np.arange(len(y.columns)))))
     ax.xaxis.set_major_formatter(ticker.FixedFormatter(y.columns))
Exemple #12
0
    def _payoff_heatmap(
            self,
            data: dataType,
            names: namesType,
            title: titleType = None,
            ax: matplotlib.axes.SubplotBase = None
    ) -> matplotlib.figure.Figure:
        """Generic heatmap plot"""
        if not self.matplotlib_installed:
            return None

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.nplayers / 4, 12)
        height = width
        figure.set_size_inches(width, height)
        cmap = default_cmap()
        mat = ax.matshow(data, cmap=cmap)
        plt.xticks(range(self.result_set.nplayers))
        plt.yticks(range(self.result_set.nplayers))
        ax.set_xticklabels(names, rotation=90)
        ax.set_yticklabels(names)
        plt.tick_params(axis='both', which='both', labelsize=16)
        if title:
            plt.xlabel(title)
        # Make the colorbar match up with the plot
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", "5%", pad="3%")
        plt.colorbar(mat, cax=cax)
        return figure
Exemple #13
0
    def stackplot(
            self,
            eco,
            title: titleType = None,
            logscale: bool = True,
            ax: matplotlib.axes.SubplotBase = None
    ) -> matplotlib.figure.Figure:

        populations = eco.population_sizes

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        turns = range(len(populations))
        pops = [[populations[iturn][ir] for iturn in turns]
                for ir in self.result_set.ranking]
        ax.stackplot(turns, *pops)

        ax.yaxis.tick_left()
        ax.yaxis.set_label_position("right")
        ax.yaxis.labelpad = 25.0

        ax.set_ylim([0.0, 1.0])
        ax.set_ylabel('Relative population size')
        ax.set_xlabel('Turn')
        if title is not None:
            ax.set_title(title)

        trans = transforms.blended_transform_factory(ax.transAxes,
                                                     ax.transData)
        ticks = []
        for i, n in enumerate(self.result_set.ranked_names):
            x = -0.01
            y = (i + 0.5) * 1 / self.result_set.nplayers
            ax.annotate(n,
                        xy=(x, y),
                        xycoords=trans,
                        clip_on=False,
                        va='center',
                        ha='right',
                        fontsize=5)
            ticks.append(y)
        ax.set_yticks(ticks)
        ax.tick_params(direction='out')
        ax.set_yticklabels([])

        if logscale:
            ax.set_xscale('log')

        plt.tight_layout()
        return figure
Exemple #14
0
    def _payoff_heatmap(
            self,
            data: dataType,
            names: namesType,
            title: titleType = None,
            ax: matplotlib.axes.SubplotBase = None
    ) -> matplotlib.figure.Figure:
        """Generic heatmap plot"""

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.nplayers / 4, 12)
        height = width
        figure.set_size_inches(width, height)
        matplotlib_version = matplotlib.__version__
        cmap = default_cmap(matplotlib_version)
        mat = ax.matshow(data, cmap=cmap)
        ax.set_xticks(range(self.result_set.nplayers))
        ax.set_yticks(range(self.result_set.nplayers))
        ax.set_xticklabels(names, rotation=90)
        ax.set_yticklabels(names)
        ax.tick_params(axis='both', which='both', labelsize=16)
        if title:
            ax.set_xlabel(title)
        figure.colorbar(mat, ax=ax)
        plt.tight_layout()
        return figure
Exemple #15
0
    def _violinplot(
        self,
        data: dataType,
        names: namesType,
        title: titleType = None,
        ax: matplotlib.axes.SubplotBase = None,
    ) -> matplotlib.figure.Figure:
        """For making violinplots."""

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.num_players / 3, 12)
        height = width / 2
        spacing = 4
        positions = spacing * arange(1, self.num_players + 1, 1)
        figure.set_size_inches(width, height)
        ax.violinplot(
            data,
            positions=positions,
            widths=spacing / 2,
            showmedians=True,
            showextrema=False,
        )
        ax.set_xticks(positions)
        ax.set_xticklabels(names, rotation=90)
        ax.set_xlim([0, spacing * (self.num_players + 1)])
        ax.tick_params(axis="both", which="both", labelsize=8)
        if title:
            ax.set_title(title)
        plt.tight_layout()
        return figure
Exemple #16
0
def plt_settings_axes(g: matplotlib.axes.SubplotBase,
                      count_df: dask.dataframe.core.DataFrame,
                      grouping_col: list, facet: str, hide_xtitle: bool,
                      log_y: bool) -> None:
    """
    Helper function for plot settings, used in function plt_generic_1d.
    Modifies parameter g for setting titles, axis, formats, etc.
    :param g: matplotlib Axes which will be modified directly in the function.
    :param count_df: pandas dataframe which is plotted.
    :param grouping_col: column for x axis.
    :param facet: parameter passed by function plt_generic_1d, giving information
    on whether we are plotting and average or a count value (on y axis).
    :param hide_xtitle: if set to True, doesn't display title for x axis 
    :param log_y: if set to True, plot in logarithmic scale (for y axis)
    :return: nothing. changes are done directly by modifying parameter g.
    """

    if facet not in ['freq', 'avg']:
        raise ValueError(
            'Parameter facet should be a string of value either "freq" or "avg"'
        )

    # SET X AXIS
    # Labels
    # no particular setup if number of labels is less than the first threshold
    num_xlabels = len(count_df[grouping_col])

    if num_xlabels < LABEL_THRESHOLD_ROTATION:
        g.set_xticklabels(count_df[grouping_col])

    # rotate by 90 degrees if number of labels is between first and second threshold
    elif num_xlabels < LABEL_THRESHOLD_SELECT:
        g.set_xticklabels(count_df[grouping_col], rotation=90)

    # display only certain labels (and rotate by 45 degrees) if number of labels is higher
    else:
        number_of_steps = num_xlabels / 50

        l = np.arange(0, num_xlabels, number_of_steps)

        pos = (l / num_xlabels) * (max(g.get_xticks()) - min(g.get_xticks()))
        g.set_xticks(pos)
        g.set_xticklabels(count_df[grouping_col].iloc[l], rotation=45)

    # Title
    # option to remove the x axis title (when its obvious, e.g. for the years)
    if hide_xtitle:
        g.set_xlabel('')
    else:
        g.set_xlabel(grouping_col)

    # SET Y AXIS
    # log scale option
    if log_y:
        g.set_yscale("log")
        if facet == 'freq':
            g.set_ylabel('# content items (log scale)')
        elif facet == 'avg':
            g.set_ylabel('title length (log scale)')

    else:
        if facet == 'freq':
            g.set_ylabel('# content items')
        elif facet == 'avg':
            g.set_ylabel('title length')

    # Labels
    ylabels = ['{:,.0f}'.format(y) for y in g.get_yticks()]
    g.set_yticklabels(ylabels)

    # Plot Title
    if facet == 'freq':
        g.set_title('Number of content items by %s' % grouping_col)
    elif facet == 'avg':
        g.set_title('Average title length of content items by %s' %
                    grouping_col)
Exemple #17
0
 def plot_2_1(ax: matplotlib.axes.SubplotBase, pval_df: pd.DataFrame, row_id: int) -> None:
     ax.bar(pval_df.columns, -np.log10(pval_df.loc[row_id]), color="red")
     ax.set_title("significance of difference")
     ax.set_xlabel("k")
     ax.set_ylabel("-log10(p-value)")
     ax.set_ylim(0, 4)
Exemple #18
0
    def _violinplot(
        self,
        data: dataType,
        names: namesType,
        title: titleType = None,
        ax: matplotlib.axes.SubplotBase = None,
    ) -> matplotlib.figure.Figure:
        """For making violinplots."""

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.num_players / 3, 12)
        height = width / 2
        spacing = 4
        positions = spacing * arange(1, self.num_players + 1, 1)
        figure.set_size_inches(width, height)
        ax.violinplot(
            data,
            positions=positions,
            widths=spacing / 2,
            showmedians=True,
            showextrema=False,
        )
        ax.set_xticks(positions)
        ax.set_xticklabels(names, rotation=90)
        ax.set_xlim([0, spacing * (self.num_players + 1)])
        ax.tick_params(axis="both", which="both", labelsize=8)
        if title:
            ax.set_title(title)
        plt.tight_layout()
        return figure
Exemple #19
0
    def stackplot(
        self,
        eco,
        title: titleType = None,
        logscale: bool = True,
        ax: matplotlib.axes.SubplotBase = None,
    ) -> matplotlib.figure.Figure:

        populations = eco.population_sizes

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        turns = range(len(populations))
        pops = [
            [populations[iturn][ir] for iturn in turns]
            for ir in self.result_set.ranking
        ]
        ax.stackplot(turns, *pops)

        ax.yaxis.tick_left()
        ax.yaxis.set_label_position("right")
        ax.yaxis.labelpad = 25.0

        ax.set_ylim([0.0, 1.0])
        ax.set_ylabel("Relative population size")
        ax.set_xlabel("Turn")
        if title is not None:
            ax.set_title(title)

        trans = transforms.blended_transform_factory(ax.transAxes, ax.transData)
        ticks = []
        for i, n in enumerate(self.result_set.ranked_names):
            x = -0.01
            y = (i + 0.5) * 1 / self.result_set.num_players
            ax.annotate(
                n,
                xy=(x, y),
                xycoords=trans,
                clip_on=False,
                va="center",
                ha="right",
                fontsize=5,
            )
            ticks.append(y)
        ax.set_yticks(ticks)
        ax.tick_params(direction="out")
        ax.set_yticklabels([])

        if logscale:
            ax.set_xscale("log")

        plt.tight_layout()
        return figure
Exemple #20
0
    def _payoff_heatmap(
        self,
        data: dataType,
        names: namesType,
        title: titleType = None,
        ax: matplotlib.axes.SubplotBase = None,
    ) -> matplotlib.figure.Figure:
        """Generic heatmap plot"""

        if ax is None:
            _, ax = plt.subplots()
        else:
            ax = ax

        figure = ax.get_figure()
        width = max(self.num_players / 4, 12)
        height = width
        figure.set_size_inches(width, height)
        matplotlib_version = matplotlib.__version__
        cmap = default_cmap(matplotlib_version)
        mat = ax.matshow(data, cmap=cmap)
        ax.set_xticks(range(self.result_set.num_players))
        ax.set_yticks(range(self.result_set.num_players))
        ax.set_xticklabels(names, rotation=90)
        ax.set_yticklabels(names)
        ax.tick_params(axis="both", which="both", labelsize=16)
        if title:
            ax.set_xlabel(title)
        figure.colorbar(mat, ax=ax)
        plt.tight_layout()
        return figure
Exemple #21
0
 def plot_2_2(ax: matplotlib.axes.SubplotBase, df_eff_k: pd.DataFrame, rows_set: np.ndarray) -> None:
     lty = ["--", "-", "--"]
     lwd = [1, 2, 1]
     mu, sigma = ClusteringUtils.calc_distribution(df_eff_k.loc[rows_set])
     y = pd.DataFrame([mu - sigma, mu, mu + sigma]).transpose()
     for col in y.columns:
         ax.plot(df_eff_k.columns, y[col], color="red", linestyle=lty[col], linewidth=lwd[col])
         ax.set_xlabel("k")
         ax.set_ylabel("effective k")
         ax.set_xlim(1, df_eff_k.columns.max())
         ax.set_ylim(1, df_eff_k.columns.max())
     abline_vals = np.array(ax.get_xlim())
     ax.plot(abline_vals, abline_vals, color="grey", linestyle="--")
Exemple #22
0
def drawSamples(plot: matplotlib.axes.SubplotBase, samples: numpy.ndarray):
    plot.scatter(samples[0], samples[1], c="#4444ff", s=1, zorder=5)