Exemple #1
0
def my_legend(ax, pl_list, text, x, y, size, which, plt):
    l = Legend(ax, pl_list[which - 1:which], (text, ), loc=(x, y))
    ltext = l.get_texts()  # all the text.Text instance in the legend
    #plt.setp(ltext, fontsize='medium', linespacing=1)    # the legend text fontsize
    plt.setp(ltext, fontsize=size, linespacing=1)  # the legend text fontsize
    l.draw_frame(False)  # don't draw the legend frame
    ax.add_artist(l)
Exemple #2
0
def checkboxLegend(parent, *args, **kwargs):
    """
    Creates a Legend with checkboxes to toggle visibility of all
    elements corresponding to entries in the legend

    Parameters
    ----------
    parent : `~matplotlib.axes.Axes` or `.Figure`
        The artist that contains the legend.
    """
    # get user genarated handler_map, and set handlelength to a default of 3
    custom_handler_map = kwargs.get('handler_map', {})
    if kwargs.get('handlelength', None) is None:
        kwargs['handlelength'] = 3

    # update a default handler map to include user genarated handler_map
    hm = Legend.get_default_handler_map().copy()
    hm.update(custom_handler_map)

    # create interactive version of the new handler map
    for handler in hm:
        hm[handler] = VisibilityHandler(
            handler=Legend.get_legend_handler(hm, handler))
    kwargs['handler_map'] = hm

    # return interactive legend
    return parent.legend(*args, **kwargs)
Exemple #3
0
def plot_traps_legend():
    plt.subplot(1, 3, 1)
    Legend.update_default_handler_map({str: TextHandlerB()})
    plt.legend(handles=["S", "N", "R"],
               labels=["Security", "Normal", "Risky"],
               title="Dices",
               loc='center')
    plt.axis('off')

    plt.subplot(1, 3, 2)
    # handle1 = mpatches.FancyBboxPatch((0,0), 10, 10, boxstyle='Square, pad=0.5', facecolor='#f6f4f4', lw=0, label="False")
    # handle2 = mpatches.FancyBboxPatch((0,0), 10, 10, boxstyle='Circle, pad=0.5', facecolor='#f6f4f4', lw=0, label="False")
    handle1, = Line2D([0], [0],
                      marker='s',
                      color='w',
                      label='False',
                      markerfacecolor='lightgray',
                      markersize=11),
    handle2, = Line2D([0], [0],
                      marker='o',
                      color='w',
                      label='True',
                      markerfacecolor='lightgray',
                      markersize=11),
    plt.legend(handles=[handle1, handle2], loc='center', title='Circle')
    plt.axis('off')

    plt.subplot(1, 3, 3)
    handles = []
    for i, label in enumerate(traps_label):
        if label:
            patch = mpatches.Patch(label=label, color=traps_color[i])
            handles.append(patch)
    plt.legend(handles=handles, loc='center', title="Traps")
    plt.axis('off')
Exemple #4
0
    def plot_dos(self,
                 filename='dos.png',
                 smear=None,
                 styles='t',
                 xlim=[-3, 3]):
        """export dos"""
        efermi = self.values['calculation']['efermi']
        tdos = np.array(self.values['calculation']['tdos'][0])
        tdos[:, 0] -= efermi
        e = tdos[:, 0]
        rows = (e > xlim[0]) & (e < xlim[1])
        e = e[rows]
        plt_obj = {}
        for option in styles.split('+'):
            if option == 'spd':
                option = ['s', 'p', 'd']
            else:
                option = [option]
            for style in option:
                mydos, labels = self.get_dos(rows, style)
                for data, label in zip(mydos, labels):
                    plt_obj[label] = data

        fig, ax = plt.subplots()
        lines1 = []
        lines2 = []
        labels1 = []
        labels2 = []
        for label in plt_obj.keys():
            e = np.reshape(e, [len(e), 1])
            data = np.reshape(plt_obj[label], [len(e), 1])
            if smear is not None:
                data = np.hstack((e, data))
                data = smear_data(data, smear)
                data = data[:, 1]
            if label.find('down') > 0:
                lines2 += ax.plot(e, data)
                labels2.append(label)
            else:
                lines1 += ax.plot(e, data)
                labels1.append(label)
        leg1 = ax.legend(lines1, [label for label in labels1],
                         fancybox=True,
                         loc='upper right')
        leg1.get_frame().set_alpha(0.5)
        if len(lines2) > 0:
            from matplotlib.legend import Legend
            leg2 = Legend(ax,
                          lines2, [label for label in labels2],
                          fancybox=True,
                          loc='lower right')
            ax.add_artist(leg2)
            leg2.get_frame().set_alpha(0.5)

        plt.xlabel("Energy (eV)")
        plt.ylabel("DOS")
        plt.xlim(xlim)
        plt.savefig(filename)
def test_checkbox_legend_default_handler_set():
    line1, = plt.plot([1, 2], [1, 2], color='r', lw=2)
    handler_map = {line1: ExampleHandler()}
    Legend.set_default_handler_map(handler_map)
    legend = checkboxLegend(plt, [line1], ["R"], fontsize=16)
    assert isinstance(legend.get_legend_handler_map()[line1],
                      VisibilityHandler)
    assert isinstance(legend.get_legend_handler_map()[line1].handler,
                      ExampleHandler)
Exemple #6
0
def plot_scatter(dfs, sig1, sig2, hue='agent', alpha='dose',
                 color_dict=None, marker='o', plot_legend=True,
                 ax=None):
    if ax is None:
        fig, ax = plt.subplots(1, 1)
    labels = dfs[hue].unique()
    if color_dict is None:
        colrs = sns.color_palette("husl", len(labels))
        color_dict = {}
        for i, label in enumerate(labels):
            color_dict[label] = colrs[i] + (1,)
    for ftr in dfs[hue].unique():
        dfis = dfs[dfs[hue] == ftr]
        x = dfis[sig1].tolist()
        y = dfis[sig2].tolist()
        rgba_colors = np.zeros((dfis.shape[0], 4))
        rgba_colors[:, :] = color_dict[ftr]
        edge_colors = rgba_colors.copy()
        if alpha is not None:
            amin = dfs[alpha].min()
            amax = dfs[alpha].max()
            rgba_colors[:, 3] = [1 - (al-amin)/amax for
                                 al in dfis[alpha].tolist()]
            sizes = [100 * al for
                     al in dfis[alpha].tolist()]
        ax.scatter(y, x, s=sizes, facecolor=rgba_colors,
                   edgecolor=edge_colors, lw=1, marker=marker)
    # Legends
    # -------
    if plot_legend:    
        hue_recs = []
        for label in color_dict.keys():
            hue_recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=color_dict[label]))
        alpha_circles = []
        amin = dfs[alpha].min()
        amax = dfs[alpha].max()
        for ds in np.sort(dfs[alpha].unique()):
            alpha_val = 1 - (ds - amin)/amax
            gray_alpha = (128/255, 128/255, 128/255) + (alpha_val,)
            alpha_circles.append(
                mpatches.Circle((0, 0), radius=5, fc=gray_alpha))
        legend1 = Legend(parent=ax, handles=hue_recs,
                         labels=color_dict.keys(), loc=(0.6, 0.02), title='drug')
        legend2 = Legend(parent=ax, handles=alpha_circles,
                         labels=[1 * d for d in np.sort(dfs['dose'].unique())],
                         loc=4, title='dose',
                         handler_map={mpatches.Circle: HandlerEllipse()})
        ax.add_artist(legend2).get_frame().set_edgecolor("black")
        ax.add_artist(legend1).get_frame().set_edgecolor("black")
Exemple #7
0
 def add_legends(self, legend_infos: List[LegendInfo]) -> None:
     """Adds the legends
     """
     # # old way (keep it for fast hacking of plots if need be)
     # # this creates a legend box on the bottom, and algorithm names on the right with some angle to avoid overlapping
     # self._overlays.append(self._ax.legend(fontsize=7, ncol=2, handlelength=3,
     #                                       loc='upper center', bbox_to_anchor=(0.5, -0.2)))
     # upperbound = self._ax.get_ylim()[1]
     # filtered_legend_infos = [i for i in legend_infos if i.y <= upperbound]
     # for k, info in enumerate(filtered_legend_infos):
     #     angle = 30 - 60 * k / len(legend_infos)
     #     self._overlays.append(self._ax.text(info.x, info.y, info.text, {'ha': 'left', 'va': 'top' if angle < 0 else 'bottom'},
     #                                         rotation=angle))
     # new way
     ax = self._ax
     trans = ax.transScale + ax.transLimits
     fontsize = 10.0
     display_y = (ax.transAxes.transform((1, 1)) - ax.transAxes.transform((0, 0)))[1]  # height in points
     shift = (2.0 + fontsize) / display_y
     legend_infos = legend_infos[::-1]  # revert order for use in compute_best_placements
     values = [float(np.clip(trans.transform((0, i.y))[1], -0.01, 1.01)) for i in legend_infos]
     placements = compute_best_placements(values, min_diff=shift)
     for placement, info in zip(placements, legend_infos):
         self._overlays.append(
             Legend(ax, info.line, [info.text], loc="center left", bbox_to_anchor=(1, placement), frameon=False, fontsize=fontsize)
         )
         ax.add_artist(self._overlays[-1])
Exemple #8
0
def legendbox(text, ax=None, loc=0, *args, **kwargs):
    """Create a legend from class matplotlib.legend.Legend and add it to axis.
        `text` is a list of strings to be passed to `labels` parameter in Legend.
        Unclear how line styles are set (probably none).
        """

    from matplotlib.patches import Patch
    from matplotlib.legend import Legend
    #------ SAME BUT WITH CUSTOM LEGEND (DOESN'T ERASE OTHER LEGENDS)

    #plt.plot([1,2],[2,3],label='cane')
    #plt.legend(loc=1)

    #pdb.set_trace()
    if np.size(text) == 1 and not isinstance(text, list): text = [text]
    if ax is None:
        ax = plt.gca()
    p = [Patch(label=ll, visible=False) for ll in text]
    leg = Legend(ax,
                 p,
                 text,
                 loc=loc,
                 handletextpad=0,
                 handlelength=0,
                 *args,
                 **kwargs)
    ax.add_artist(leg)

    return leg
def plotLines(dataSource, feature, loc1, loc2, filename):
    fig = plt.figure(figsize=(6, 6), dpi=720)
    requests_plot = fig.add_subplot(1, 1, 1)
    lines, legends = [], []
    for method in ['direct', 'nginx']:
        if dataSource == 'locust':
            df0 = locust[method]
        if dataSource == 'cmonitor':
            df0 = cmonitor[method]
        for wsgi in ['gunicorn', 'uwsgi', 'uwsgi-http', 'werkzeug']:
            if wsgi in df0.keys():
                df = df0[wsgi]
                legends.append(wsgi)
                lines += requests_plot.plot(df['Timestamp'],
                                            df[feature],
                                            linestyle=linestyles[method],
                                            color=colors[wsgi])

    requests_plot.legend(lines[0:3],
                         legends[0:3],
                         loc=loc1,
                         prop={'size': 10},
                         frameon=True)
    leg = Legend(requests_plot,
                 lines[3:7],
                 legends[3:7],
                 loc=loc2,
                 prop={'size': 10},
                 frameon=True)
    requests_plot.add_artist(leg)
    fig.savefig(folder + '/' + filename + '.png', format='png', dpi=720)
    plt.close(fig)
Exemple #10
0
 def add_legends(self, legend_infos: tp.List[LegendInfo]) -> None:
     """Adds the legends
     """
     ax = self._ax
     trans = ax.transScale + ax.transLimits
     fontsize = 10.0
     display_y = (ax.transAxes.transform((1, 1)) - ax.transAxes.transform(
         (0, 0)))[1]  # height in points
     shift = (2.0 + fontsize) / display_y
     legend_infos = legend_infos[::
                                 -1]  # revert order for use in compute_best_placements
     values = [
         float(np.clip(trans.transform((0, i.y))[1], -0.01, 1.01))
         for i in legend_infos
     ]
     placements = compute_best_placements(values, min_diff=shift)
     for placement, info in zip(placements, legend_infos):
         self._overlays.append(
             Legend(ax,
                    info.line, [info.text],
                    loc="center left",
                    bbox_to_anchor=(1, placement),
                    frameon=False,
                    fontsize=fontsize))
         ax.add_artist(self._overlays[-1])
Exemple #11
0
def _plot_distributions_and_alignment(X,
                                      Y,
                                      R=None,
                                      thr=.1,
                                      title=None,
                                      tick_params=tick_params):
    fig, ax = plt.subplots(figsize=(3.5, 3.5))
    plt.plot(X[:, 0], X[:, 1], 'og', label='Source samples')
    plt.plot(Y[:, 0], Y[:, 1], 'or', label='Target samples')
    plt.legend()
    if R is not None:
        # if R has some negative coeffs, plot them too in red
        if not (R >= 0).all():
            _plot2D_samples_mat(X, Y, -R, thr=thr, c=[1, 0.2, 0.2])
            colors = ['blue', 'red']
            lines = [Line2D([0], [0], color=c, linewidth=2) for c in colors]
            labels = ['Positive coeffs', 'Negative coeffs']
            leg = Legend(ax, lines, labels, loc='upper left', fontsize=10)
            ax.add_artist(leg)
            plt.legend()
        # Then plot R positive coeffs above a threshold in blue
        _plot2D_samples_mat(X, Y, R, thr=thr, c=[0.2, 0.2, 1])

    plt.rcParams.update({
        'font.size': 12,
        'ytick.labelsize': 14,
        'xtick.labelsize': 14,
        'axes.titlesize': 14,
        "axes.labelsize": 12
    })
    plt.xlabel('Contrast 1', fontsize=14)
    plt.ylabel('Contrast 2', fontsize=14)
    plt.tick_params(**tick_params)
    plt.title(title, fontsize=16)
def MultiPlot3(DF, Tsample1):
    #region -------- Generating Title ------------
    print("*** Title already begins with 'Graph to show ' ***")
    title = input("Enter Desired Graph Title:")
    GraphName = title
    GraphName = GraphName.replace(" ", "_")
    #endregion
    #region -------- Plot Dimensions -------------
    fig, ax = plt.subplots(num=None,
                           figsize=(8, 3.5),
                           facecolor='w',
                           edgecolor='k')
    #endregion
    #region ---------- Plot Data -----------------
    # - empty lists for Styles & Data
    lines = []
    MeanLines = []
    Collumns = []
    styles = ['-', '--']
    for col in DF.columns:
        Collumns.append(col)
        # - Solid Lines Styling and Data
        lines += ax.plot(DF[col].resample("2T").mean(),
                         styles[0],
                         alpha=0.7,
                         color=Clr_Palete[col][2],
                         linewidth=0.75)

        # - Average lines Styling and Data
        MeanLines += ax.plot(DF[col].resample('{}H'.format(Tsample1)).mean(),
                             styles[1],
                             color=Clr_Palete[col][4],
                             linewidth=1.5)
    #endregion
    #region ---------- Plot Legend ---------------
    # specify the lines and labels of the first legend
    ax.legend(lines, Collumns, loc='upper right', frameon=False)
    # Create the second legend and add the artist manually.
    Collumns = [
        '{} / {} Hours'.format(element, Tsample1) for element in Collumns
    ]
    leg = Legend(ax, MeanLines, Collumns, loc='upper left', frameon=False)
    ax.add_artist(leg)
    #endregion
    #region ------- Plot Periferals --------------
    # - - Graph Title
    plt.title("Graph to show {}".format(title))
    # - - - Puts "$" infront of Y axis
    tick = mtick.FormatStrFormatter('$%.0f')
    ax.yaxis.set_major_formatter(tick)
    # - - - - Reduces White Boarder Size
    plt.tight_layout()
    #endregion
    #region --------- Saving Plot  ---------------
    plt.savefig("Graphs/Predictions/CompoundPlots/{}_avg{}.png".format(
        GraphName, Tsample1),
                dpi=My_DPI)
    #endregion
    plt.show()
Exemple #13
0
def tag(tagstr, **kwargs):
    from matplotlib.legend import Legend
    ax = plt.gca()
    h, = ax.plot(np.NaN, np.NaN, '-', color='none') # empty line for legend
    leg = Legend(ax, (h,), (tagstr,), handlelength=0, handletextpad=0, **kwargs)
    for item in leg.legendHandles:
        item.set_visible(False)
    ax.add_artist(leg)
Exemple #14
0
def scatter_football(x, y, ax=None, **kwargs):
    """ Scatter plot of football markers.
    Plots two scatter plots one for the hexagons and one for the pentagons of the football.

    Parameters
    ----------
    x, y : array-like or scalar.
        Commonly, these parameters are 1D arrays.
    ax : matplotlib.axes.Axes, default None
        The axis to plot on.
    **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.scatter.

    Returns
    -------
    (paths, paths) : a tuple of matplotlib.collections.PathCollection
    """
    linewidths = kwargs.pop('linewidths', 0.5)
    hexcolor = kwargs.pop('c', 'white')
    pentcolor = kwargs.pop('edgecolors', 'black')
    s = kwargs.pop('s', 500)
    sc_hex = ax.scatter(x,
                        y,
                        edgecolors=pentcolor,
                        c=hexcolor,
                        linewidths=linewidths,
                        marker=football_hexagon_marker,
                        s=s,
                        **kwargs)

    if 'label' in kwargs.keys():
        Legend.update_default_handler_map({sc_hex: HandlerFootball()})
        del kwargs['label']

    sc_pent = ax.scatter(x,
                         y,
                         edgecolors=pentcolor,
                         c=pentcolor,
                         linewidths=linewidths,
                         marker=football_pentagon_marker,
                         s=s,
                         **kwargs)

    return sc_hex, sc_pent
Exemple #15
0
def individual_plot(data_dir, plot_dir, mode):
    variants = OrderedDict()
    variants['1_near'] = ([], [])
    variants['2_near'] = ([], [])
    variants['1_far'] = ([], [])
    variants['2_far'] = ([], [])
    variants['1_near_1_far'] = ([], [])

    labels = []
    lines = []
    fig, ax = plt.subplots(1, 1, figsize=(4, 3))

    for (var, data) in variants.items():
        x_vals, y_vals = data
        get_bandwidth(f"{data_dir}/sequential_{mode}_{var}", var, x_vals, y_vals)
        print(f"{mode}: {x_vals}")
        color, marker = VAR_TO_STYLE[var]
        label = var.replace('_', ' ').replace(' sockets', '').replace(' socket', '').title()
        labels.append(label)
        lines += ax.plot(x_vals, y_vals, color=color, marker=marker, markersize=8, label=label)

    xticks = [1, 4, 8, 16, 18, 24, 32, 36]
    xtick_labels = ['1', '4', '8', '', '18', '24', '32', '36']

    ylim_max = 85 if mode == "read" else 27
    if "dram" in data_dir:
        ylim_max = 200 if mode == "read" else 140

    ax.set_xticks(xticks)
    ax.set_xticklabels(xtick_labels)
    ax.yaxis.grid(True)
    ax.set_axisbelow(True)
    ax.set_ylim(0, ylim_max)
    ax.set_ylabel('Bandwidth [GB/s]', fontsize=18)
    ax.set_xlabel('Threads per Socket [#]', fontsize=18)
    SET_LABEL_SIZE(ax)

    ax.legend(labels[:-1], frameon=False, bbox_to_anchor=(0.4, 1.35), loc='upper center', fontsize=18,
              columnspacing=0.4, handletextpad=0.3, labelspacing=0.0, ncol=3, handlelength=1.6)

    legend_1n1f = Legend(ax, lines[-1:], labels[-1:],
                        frameon=False, bbox_to_anchor=(0.58, 1.25),
                        loc='upper center', fontsize=18, handlelength=1.6,
                        handletextpad=0.3, labelspacing=0.5, ncol=1)
    ax.add_artist(legend_1n1f)

    plot_suffix = "_dram" if "dram" in data_dir else ""
    plot_path = f'{plot_dir}/{mode}_multiple_sockets{plot_suffix}'
    SAVE_PLOT(plot_path)
Exemple #16
0
def axlegend_vel(ax):
    'add custom legend (storm velocity) to axes'

    # velocity legend
    lls_vel = [
        Line2D([0], [0], color = 'black', ls = 'solid'),
        Line2D([0], [0], color = 'black', ls = 'dashed'),
        Line2D([0], [0], color = 'black', ls = 'dashdot'),
        Line2D([0], [0], color = 'black', ls = 'dotted'),
    ]
    leg_vel = Legend(
        ax, lls_vel, ['> 60 km/h', '> 40 km/h', '> 20 km/h', '< 20 km/h'],
        title = 'Velocity', bbox_to_anchor = (1.01, 0.7), loc= 'upper left',
    )
    ax.add_artist(leg_vel)
Exemple #17
0
def plot_list(L_value_list, optpdf, color, alpha):
    class TextHandlerB(HandlerBase):
        def create_artists(self, legend, text, xdescent, ydescent, width,
                           height, fontsize, trans):
            tx = Text(width / 2.,
                      height / 2,
                      text,
                      fontsize=fontsize,
                      ha="center",
                      va="center",
                      fontweight="normal")
            return [tx]

    Legend.update_default_handler_map({str: TextHandlerB()})
    f = plt.figure(figsize=(8, 4))
    (mu, sigma) = norm.fit(L_value_list)
    pvalue = norm.pdf(48, mu, sigma)
    pvalue = "%.2e" % pvalue
    ax=sns.distplot(pd.Series(L_value_list),bins=np.arange(25,36,1),fit=norm,kde=False,\
    kde_kws={"label":"Smooth",'linewidth':1.5,"linestyle":"--","color":"K"},\
    fit_kws={'label': 'Normal','linewidth':1.5, "color": "r"},hist_kws={'linewidth':0.05,"color": color,"edgecolor":"black","alpha":alpha,"align":"mid","rwidth":1},label=str(pvalue))#,ax=ax)
    plt.axvline(48, color='r')
    legend_i = ax.get_legend_handles_labels()
    smooth_normal_handles = legend_i[0][:1]
    smooth_normal_handles.append("Pvalue ")
    plt.xticks(np.arange(min(L_value_list) - 2, 55,
                         1))  #max(L_value_list)+3,1))
    plt.legend(smooth_normal_handles,
               legend_i[1],
               loc='upper right',
               framealpha=0)
    plt.ylabel("Probability", fontsize=10, fontweight='semibold')
    plt.xlabel("Bottleneck Size,n", fontsize=10, fontweight='semibold')
    plt.title("The distribution of n", fontsize=12, fontweight='bold')
    plt.tight_layout()
    plt.savefig(optpdf, dpi=200)
Exemple #18
0
    def test_path_collection(self):
        # Create a small scatter plot
        plot = plt.scatter([1, 2, 3], [2, 3, 4], c=[3, 4, 5],
                           cmap=cmr.rainforest)

        # Add a cmap legend entry
        set_cmap_legend_entry(plot, 'Test')

        # Check if the plot now has a special handler
        assert plot in Legend.get_default_handler_map()

        # Create a legend
        plt.legend()

        # Close the plot
        plt.close()
Exemple #19
0
    def LogMag(self):
        '''
        Plots the log values of magnetism versus temperature as well as the lines that divide the
        sections where we search for the maxium logmag value
        
        Parameters :
            None
        '''
        data = self.data
        color = self.color
        _, ax = plt.subplots(1, len(data), sharey=True)
        TMAX = self.CalcTMax()
        T_under = np.linspace(2.1, TMAX, 4)
        T_over = np.linspace(TMAX, 2.8, 4)
        T = np.sort(np.append(T_under, T_over))
        for i, d in enumerate(data):
            for j, tt in enumerate(T):
                df = pd.read_csv(d)
                df = df[df['T'] < tt]
                logt = np.log10(tt - df['T'])
                logm = df['LOGM']
                ax[i].scatter(logt, logm, color=color[j % len(color)])
                if tt == TMAX:
                    line = np.polyfit(logt, logm, 1)
                    line_f = np.poly1d(line)
                    line1 = ax[i].plot(logt,
                                       line_f(logt),
                                       color=color[j % len(color)],
                                       label='Original')
                    ax[i].legend(line1,
                                 ['T is %s and Slope is %s' % (tt, line[0])],
                                 loc=3)

                    logt_r = np.log10(tt - df['T'])
                    line = np.polyfit(logt_r, logm, 1)
                    line_f = np.poly1d(line)
                    line2 = ax[i].plot(logt,
                                       line_f(logt),
                                       color='black',
                                       label='Outliers Removed')
                    leg = Legend(ax[i],
                                 line2,
                                 ['T is %s and Slope is %s' % (tt, line[0])],
                                 loc=2)
                    ax[i].add_artist(leg)
            ax[i].grid(b=True)
        plt.show()
Exemple #20
0
    def draw(self, colors, ylim, step=1.5, width=0.2):
        n = 0
        cs = cycle(colors)
        move = (len(self.cols) - 1) / 2

        self.f, ax = plt.subplots(figsize=(16, 9), facecolor=(.18, .31, .31))
        ax.set_facecolor('#eafff5')
        for ms, color in zip(self.getMeanStd(), cs):
            n += 1
            center = ((n - 1) // len(self.cols) + 1) * step
            x = (move - ((n - 1) % 6)) * width
            x = center - x
            ax.bar(x, ms[0], width=width, yerr=ms[1], color=color)

        ax.set_ylim(ylim)
        ax.spines['bottom'].set_color('#caaca8')
        ax.spines['right'].set_color('#caaca8')
        ax.spines['left'].set_color('#caaca8')
        ax.spines['top'].set_color('#caaca8')
        ax.spines['bottom'].set_linewidth(1.5)
        ax.spines['left'].set_linewidth(1.5)
        ax.spines['top'].set_linewidth(1.5)
        ax.spines['right'].set_linewidth(1.5)
        ax.tick_params(direction='in',
                       which='both',
                       labelsize=12,
                       width=0.3,
                       color='#caaca8')

        ax.set_xticks(np.arange(step, step * len(self.idxs) + step, step))
        ax.set_xticklabels(self.idxs)

        ax.grid(ls='--', color='#caaca8', axis="y")

        legend = [mlines.Line2D([0], [0], color=c, lw=12) for c in colors]
        leg = Legend(
            ax,
            legend,
            labels=self.cols,
            ncol=1,
            #bbox_to_anchor=(8.1, 0.7),
            edgecolor='white',
            borderpad=0.6,
            facecolor='#eafff5')
        ax.add_artist(leg)

        ax.tick_params(labelcolor='tab:orange')
Exemple #21
0
def axlegend_categ(ax):
    'add custom legend (storm category) to axes'

    # category legend
    lls_cat = [
        Line2D([0], [0], color = 'black'),
        Line2D([0], [0], color = 'purple'),
        Line2D([0], [0], color = 'red'),
        Line2D([0], [0], color = 'orange'),
        Line2D([0], [0], color = 'yellow'),
        Line2D([0], [0], color = 'green'),
    ]
    leg_cat = Legend(
        ax, lls_cat, ['5','4','3','2','1','0'],
        title = 'Category', bbox_to_anchor = (1.01, 1), loc='upper left',
    )
    ax.add_artist(leg_cat)
def plot_losses(losses_dict, path):
    """ plots the losses over the epochs for a dictionary of model losses """
    epochs = list(range(1, len(next(iter(losses_dict.values()))) + 1))

    color_mapper = {
        'single': 'C0',
        '10': 'C1',
        'curriculum': 'C2',
        'dynamic': 'C3'
    }
    linestyle_mapper = {'lots': 'solid', 'pgd': 'dashed'}
    fig, ax = plt.subplots()

    for setting, losses in losses_dict.items():
        if setting == 'base':
            linestyle, color = 'solid', 'black'
        else:
            attack, training = setting.split('-')
            color = color_mapper[training]
            linestyle = linestyle_mapper[attack]
        ax.plot(epochs, losses, linestyle=linestyle, color=color)

    color_legend_handles = []
    for v in color_mapper.values():
        color_legend_handles.append(Line2D([0], [0], color=v, lw=1))
    ax.legend(color_legend_handles,
              list(color_mapper.keys()),
              loc='upper right')

    shape_legend_handles = []
    for v in linestyle_mapper.values():
        shape_legend_handles.append(
            Line2D([0], [0], color='black', lw=1, linestyle=v))
    ax.add_artist(
        Legend(ax,
               shape_legend_handles,
               list(linestyle_mapper.keys()),
               loc='upper center'))

    plt.title('Losses')
    plt.xlabel('Epoch')
    plt.ylabel('Negative Log Likelihood Loss')
    filename = '{}training_losses.png'.format(path)
    plt.savefig(filename, transparent=False)
    plt.close()
def metrics_scatter(ax, data, colors, sizes, metrics=['sensitivity', 'specificity'],
                    show_legend=True, legend_cols=2):
    assert len(metrics) == 2
    for k, (label, row) in enumerate(data.iterrows()):
        ax.scatter(row[metrics[0]], row[metrics[1]], label=label, color='none',
                   edgecolors=colors[k], s=sizes[k], facecolors='none', lw=1, alpha=0.85)

    legend = Legend(ax, *ax.get_legend_handles_labels(), handletextpad=-0.1, columnspacing=0.7,
                    loc='lower right', ncol=legend_cols)
    if show_legend:
        ax.add_artist(legend)

    ax.set_xlabel(metrics[0].capitalize())
    ax.set_ylabel(metrics[1].capitalize())
    ax.set_xlim(-0.015, 1.05)
    ax.set_ylim(-0.015, 1.05)

    ax.axvline(0.5, color='0.6', lw=0.25)
    ax.axhline(0.5, color='0.6', lw=0.25)

    return ax
Exemple #24
0
def survival(time, status, pGroups=None):
  kmf = KaplanMeierFitter()
  if pGroups is None:
    order = [i for i in range(2, len(time)) 
		if time[i] != "" and status[i] != ""]
    t = [float(time[i]) for i in order]
    s = [int(status[i]) for i in order]
    kmf.fit(t, s)
    ax = kmf.plot(color='red')
    return ax
  else:
    ax = None
    groups = [ "" for i in time]
    for k in range(len(pGroups)):
      df = pd.DataFrame()
      order = [i for i in pGroups[k][2]
               if time[i] != "" and status[i] != ""]
      if len(order) <= 0:
          continue
      for i in order:
        groups[i] = k
      t = [float(time[i]) for i in order]
      s = [int(status[i]) for i in order]
      kmf.fit(t, s, label = pGroups[k][0])
      if ax is None:
        ax = kmf.plot(color=pGroups[k][1], ci_show=False, show_censors=True)
      else:
        ax = kmf.plot(ax = ax, color=pGroups[k][1], ci_show=False, show_censors=True)
    order = [i for i in range(len(groups)) if groups[i] != ""]
    if len(order) > 0:
      t = [float(time[i]) for i in order]
      s = [int(status[i]) for i in order]
      g = [int(groups[i]) for i in order]
      from lifelines.statistics import multivariate_logrank_test
      from matplotlib.legend import Legend
      res = multivariate_logrank_test(t, g, s)
      leg = Legend(ax, [], [], title = "p = %.2g" % res.p_value,
                   loc='lower left', frameon=False)
      ax.add_artist(leg);
    return ax
Exemple #25
0
def multiple_legends():
    fig, ax = plt.subplots()
    lines = []
    styles = ['-', '--', '-.', ':']
    x = np.linspace(0, 10, 1000)
    for i in range(4):
        lines += ax.plot(x,
                         np.sin(x - i * np.pi / 2),
                         styles[i],
                         color='black')
    ax.axis('equal')
    # specify the lines and labels of the first legend
    ax.legend(lines[:2], ['line A', 'line B'],
              loc='upper right',
              frameon=False)
    # Create the second legend and add the artist manually.
    leg = Legend(ax,
                 lines[2:], ['line C', 'line D'],
                 loc='lower right',
                 frameon=False)
    ax.add_artist(leg)
    plt.show()
Exemple #26
0
def set_cmap_legend_entry(artist, label):
    """
    Sets the label of the provided `artist` to `label`, and creates a legend
    entry using a miniature version of the colormap of `artist` as the legend
    icon.

    This function can be used to add legend entries for *MPL* artists that use
    a colormap, like those made with :func:`~matplotlib.pyplot.hexbin`;
    :func:`~matplotlib.pyplot.hist2d`; :func:`~matplotlib.pyplot.scatter`; or
    any :mod:`~matplotlib.pyplot` function that takes `cmap` as an input
    argument.
    Keep in mind that using this function will override any legend entry that
    already exists for `artist`.

    Parameters
    ----------
    artist : :obj:`~matplotlib.artist.Artist` object
        Any artist object that has the `cmap` attribute, for which a legend
        entry must be made using its colormap as the icon.
    label : str
        The string that must be set as the label of `artist`.

    """

    # Obtain the colormap of the provided artist
    cmap = getattr(artist, 'cmap', None)

    # If cmap is None, raise error
    if cmap is None:
        raise ValueError("Input argument 'artist' does not have attribute "
                         "'cmap'!")

    # Set the label of this artist
    artist.set_label(label)

    # Add the HandlerColorPolyCollection to the default handler map for artist
    Legend.get_default_handler_map()[artist] = _HandlerColorPolyCollection()
Exemple #27
0
    extra, extra, extra, extra, extra, extra, extra, extra, extra, extra
], ("loss: " + loss_function, "learning rate: " + str(learning_rate),
    "batch_size: " + str(batch_size), "speed_bucket_size: " +
    speed_bucket_size, "epochs: " + str(training_epochs),
    "input_num_timestamps: " + str(input_num_timestamps),
    "num_labels: " + str(len(labels_to_number)),
    "evaluation metric 1:" + accuracy_reporting_metric_1,
    "evaluation metric 2:" + accuracy_reporting_metric_2,
    "evaluation metric 3:" + accuracy_reporting_metric_3, "note:" + plot_note),
           bbox_to_anchor=(1.05, 1),
           loc=2,
           borderaxespad=0.)

leg = Legend(ax1,
             lines[0:],
             ['Train Eval 1', 'Dev Eval 1', 'Train Eval 1', 'Dev Eval 2'],
             loc='right',
             frameon=False)
ax1.add_artist(leg)

plot_filename = str(time.time()) + "User-" + str(
    socket.gethostname()) + plot_note  # add plot not to identify this plot

plt.savefig("../plots/" + plot_filename + "_AccuracyVsEpoch.png",
            bbox_inches="tight")

#fig.tight_layout()

plt.show()

# #### Record results of a model in a table:
Exemple #28
0
def visualize_genome(genome: Genome,
                     show_learning_rules: bool = True,
                     with_legend: bool = True):
    def get_color(node: NodeGene):
        if isinstance(node, InputNodeGene):
            return GREEN
        elif isinstance(node, (HiddenNodeGene, OutputNodeGene)):
            if node.is_inhibitory:
                if node.bias:
                    return PINK
                else:
                    return RED
            else:
                if node.bias:
                    return CYAN
                else:
                    return BLUE

    def legend_circle(color: str):
        return Line2D([0], [0], color=color, marker='o', linewidth=0)

    g, nodes, edges = genome_to_graph(genome)
    pos = get_node_coordinates(genome)

    labels = {
        key: f"{node.learning_rule.value if isinstance(node, NeuralNodeGene) else key}{'↩' if (key, key) in edges else ''}"
        for key, node in genome.nodes.items()} if show_learning_rules \
        else {node: f"{node}{'↩' if (node, node) in edges else ''}" for node in nodes}

    node_color = [get_color(genome.nodes[node]) for node in nodes]
    edgecolors = [
        'k' if isinstance(genome.nodes[node], OutputNodeGene) else get_color(
            genome.nodes[node]) for node in nodes
    ]
    nx.draw_networkx_nodes(g,
                           pos=pos,
                           nodes=nodes,
                           node_color=node_color,
                           edgecolors=edgecolors,
                           node_size=400)
    nx.draw_networkx_labels(g, pos=pos, labels=labels)
    nx.draw_networkx_edges(g, pos=pos, connectionstyle="arc3, rad=0.05")
    # nx.draw_networkx(g, pos=pos, with_labels=True, labels=labels, nodes=nodes, node_color=node_color, node_size=400,
    #                  font_size=10, connectionstyle="arc3, rad=0.05")

    Legend.update_default_handler_map({Text: CustomTextHandler()})
    legend_dict = {
        legend_circle(GREEN): 'input node',
        Line2D([0], [0],
               color='w',
               markeredgecolor='k',
               marker='o',
               linewidth=0): 'output node',
        legend_circle(BLUE): 'excitatory, without bias',
        legend_circle(RED): 'inhibitory, without bias',
        legend_circle(CYAN): 'excitatory, with bias',
        legend_circle(PINK): 'inhibitory, with bias',
        Text(text='AH'): 'asymmetric hebbian',
        Text(text='AA'): 'asymmetric anti-hebbian',
        Text(text='SH'): 'symmetric hebbian',
        Text(text='SA'): 'symmetric anti-hebbian'
    }
    if with_legend:
        plt.figlegend(handles=legend_dict.keys(),
                      labels=legend_dict.values(),
                      loc='upper right')
    plt.box(False)
    plt.show()
plt2 = ax.scatter(predictor_amici_x, predictor_amici_y, c='green', label='Prediction is better than Amicis default setting')
plt3 = ax.scatter(equal_x, equal_y, c='blue', label='Both are equally good')
ax.plot(z)
ax.set_xlim([0.5, 250])
ax.set_ylim([0.5, 250])
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('Amicis default simulation time [ms]', fontsize=12, fontweight='bold')
ax.set_ylabel('Predictors simulation time [ms]', fontsize=12, fontweight='bold')
ax.set_title('Amici default vs. predictor settings', fontsize=24, fontweight='bold')
ax.legend(loc=2)

# second legend
#second_legend = plt.legend(handles=[plt1, plt2, plt3], loc='lower right')
leg = Legend(ax, [plt1, plt2, plt3], [str(round(len(amici_predictor_x)/len(amici_tsv_file['t_intern_ms'])*100, 2)) + ' %',
                                      str(round(len(predictor_amici_x)/len(amici_tsv_file['t_intern_ms'])*100, 2)) + ' %',
                                      str(round(len(equal_x)/len(amici_tsv_file['t_intern_ms'])*100, 2)) + ' %'], loc='lower right', frameon=True)
ax.add_artist(leg)

# better layout
plt.tight_layout()

# change plotting size
fig = plt.gcf()
fig.set_size_inches(18.5, 10.5)

# save figure
plt.savefig('../bachelor_thesis/New_Figures/Figures_study_5/Predictor_vs_Amici_166SBML.pdf')

# show figure
plt.show()
                                                    "loss: " + loss_function,
                                                    "learning rate: " + str(learning_rate),
                                                    "batch_size: " + str(batch_size),
                                                    "speed_bucket_size: " + speed_bucket_size,
                                                    "epochs: "+str(training_epochs),
                                                    "input_window_size: " + str(input_window_size),
                                                    "num_labels: " + str(len(labels_to_number)),
                                                    "evaluation metric 1:"+accuracy_reporting_metric_1,
                                                    "evaluation metric 2:"+accuracy_reporting_metric_2,
                                                    "evaluation metric 3:"+accuracy_reporting_metric_3,
                                                    "note:" + plot_note),
                                                    bbox_to_anchor=(1.05, 1),
                                                    loc=2,
                                                    borderaxespad=0.)

    leg = Legend(ax1, lines[0:], ['Train ACC', 'Dev ACC','Train Eval 1','Dev Eval 1'],
                 loc='bestoutside', frameon=False)
    ax1.add_artist(leg);
    plt.savefig(folder_head_loc + "Learning Curves/" + str(file_name) + "_AccuracyPerEpoch_Image.png", bbox_inches = "tight")
    plt.show()


# #### Record results of the model in a table

# In[29]:


# Add the results of the most recent run to the results file for documentation

if  model_architecture == 'FCN':
    a=[[model_architecture,
        file_name,
fsp.plot(lon, lat, marker='^', ls='', mec='k', mfc='k')
for (x, y, code, name) in USGS_SW:
    fsp.annotate(" " + code, basemap(x, y), **annotate_args)
#
fsp.set_xlim(98400., 482300.)
fsp.set_ylim(33627., 228051.)
fsp.set_position((0.05, 0.35, 0.90, 0.6))

draw_default_args = dict(ax=fsp, resol=1, xoffset=0.001)
basemap.draw_default_parallels(**draw_default_args)
basemap.draw_default_meridians(**draw_default_args)

usgslabel = "USGS\n"
usgslabel += "\n".join(["%s : %s" % (a, b) for (_, _, a, b) in (USGS_SE + USGS_SW)])
coapslabel = "COAPS\n"
coapslabel += "\n".join(["%s : %s" % (a, b) for (_, _, a, b) in (COAPS_SE + COAPS_SW)])

from matplotlib.legend import Legend
leg = Legend(fig, (usgs,), (usgslabel,), loc="lower left", numpoints=1)
for t in leg.get_texts():
    t.set_fontsize(10)
fig.legends.append(leg)
leg = Legend(fig, (coaps,), (coapslabel,), loc="lower right", numpoints=1)
for t in leg.get_texts():
    t.set_fontsize(10)
fig.legends.append(leg)

fig.savefig('station_location.png', dpi=600)

#mpl.show()
        self._patch_func = patch_func
        
    def create_artists (self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize,
                       trans):
        x0, y0 = xdescent, ydescent
        width, height = width, height
        linewidth = orig_handle.get_linewidth () [0] if len (orig_handle.get_linewidth ()) != 0 else None
        patch = matplotlib.patches.Rectangle([x0, y0], width, height, hatch=orig_handle.get_hatch (), lw=linewidth,
                                   transform=trans)
        cmap = orig_handle.get_cmap ()
        patch.set_facecolor (orig_handle.get_cmap () (0.5))
        patch.set_edgecolor (orig_handle.get_edgecolor () [0])
        return [patch]

Legend.update_default_handler_map({matplotlib.collections.PolyCollection: PolyCollectionHandler()})
            
class KippenhahnPlot(object):
    """This object takes a matplotlib axis and attaches a Kippenhahn plot to it associated with the given CNVFile"""
    def __init__(self, axis, cnv_file, useModels = False):
        super(KippenhahnPlot, self).__init__()
        self.axis = axis
        self.cnv_file = cnv_file
        
        self.times = (u.Quantity ([model ['timesec'] for model in self.cnv_file], 's').to ('year')).value
        
        if (not useModels):
            self.x = self.times
        else:
            self.x = list (range (len (self.times)))
            
Exemple #33
0

        legline1.set_transform(trans)
        legline2.set_transform(trans)

        return [legline1, legline2]

class HandlerPatch2(HandlerBase):
    """
    Handler for Patch instances.
    """
    def __init__(self, **kw):
        HandlerBase.__init__(self, **kw)

    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        p1 = Rectangle(xy=(-xdescent, -ydescent),
                       width=width, height=height)
        p2 = Rectangle(xy=(-xdescent, -ydescent),
                       width=width, height=height)
        self.update_prop(p1, orig_handle, legend)
        self.update_prop(p2, orig_handle, legend)
        p2.set_facecolor('none')
        p1.set_transform(trans)
        p2.set_transform(trans)
        return [p1,p2]


Legend.update_default_handler_map({ErrorLine2D: HandlerErrorLine2D()})
Legend.update_default_handler_map({Patch: HandlerPatch2()})